Skip to content

Commit 6156be8

Browse files
barucdenKlausC
andcommitted
clamp: Turn ifelse into ternary
Fixes #54022 Co-authored-by: Klaus Crusius <[email protected]>
1 parent 630f754 commit 6156be8

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

base/math.jl

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,10 @@ julia> clamp.([11, 8, 5], 10, 6) # an example where lo > hi
9595
10
9696
```
9797
"""
98-
clamp(x::X, lo::L, hi::H) where {X,L,H} =
99-
ifelse(x > hi, convert(promote_type(X,L,H), hi),
100-
ifelse(x < lo,
101-
convert(promote_type(X,L,H), lo),
102-
convert(promote_type(X,L,H), x)))
98+
function clamp(x::X, lo::L, hi::H) where {X,L,H}
99+
T = promote_type(X, L, H)
100+
return (x < lo) ? convert(T, lo) : (x > hi) ? convert(T, hi) : x
101+
end
103102

104103
"""
105104
clamp(x, T)::T

test/math.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ has_fma = Dict(
4747
clamp!(x, 1, 3)
4848
@test x == [1.0, 1.0, 2.0, 3.0, 3.0]
4949
end
50+
51+
@test clamp(typemax(UInt64), Int64) === typemax(Int64)
52+
@test clamp(typemin(Int), UInt64) === typemin(UInt64)
5053
end
5154

5255
@testset "constants" begin

0 commit comments

Comments
 (0)