Skip to content

Commit

Permalink
clamp: Turn ifelse into ternary
Browse files Browse the repository at this point in the history
Fixes JuliaLang#54022

Co-authored-by: Klaus Crusius <KlausC@users.noreply.github.com>
  • Loading branch information
barucden and KlausC committed Apr 12, 2024
1 parent 630f754 commit 6156be8
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
9 changes: 4 additions & 5 deletions base/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,10 @@ julia> clamp.([11, 8, 5], 10, 6) # an example where lo > hi
10
```
"""
clamp(x::X, lo::L, hi::H) where {X,L,H} =
ifelse(x > hi, convert(promote_type(X,L,H), hi),
ifelse(x < lo,
convert(promote_type(X,L,H), lo),
convert(promote_type(X,L,H), x)))
function clamp(x::X, lo::L, hi::H) where {X,L,H}
T = promote_type(X, L, H)
return (x < lo) ? convert(T, lo) : (x > hi) ? convert(T, hi) : x
end

"""
clamp(x, T)::T
Expand Down
3 changes: 3 additions & 0 deletions test/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ has_fma = Dict(
clamp!(x, 1, 3)
@test x == [1.0, 1.0, 2.0, 3.0, 3.0]
end

@test clamp(typemax(UInt64), Int64) === typemax(Int64)
@test clamp(typemin(Int), UInt64) === typemin(UInt64)
end

@testset "constants" begin
Expand Down

0 comments on commit 6156be8

Please sign in to comment.