Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting between integer types #22235

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion base/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@ end

"""
clamp(x, lo, hi)
clamp(T, x)
Copy link
Member

@fredrikekre fredrikekre Jun 7, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that this would be more clear (i.e. more distinct) with two separate docstrings instead of trying to explain two things in the same docstring.
Something like:

"""
    clamp(T, x)

Clamp `x` between `typemin(T)` and `typemax(T)` and convert the result to type `T`.

```jldoctest
julia> clamp(Int8, 200)
127

julia> clamp(Int8, -200)
-128
```
"""


Return `x` if `lo <= x <= hi`. If `x < lo`, return `lo`. If `x > hi`, return `hi`. Arguments
are promoted to a common type.
are promoted to a common type. If a type `T` is given, `lo` and `hi` are `typemin(T)`
and `typemax(T)` respectively, and the result is converted to `T`.

```jldoctest
julia> clamp.([pi, 1.0, big(10.)], 2., 9.)
Expand All @@ -59,6 +61,7 @@ clamp(x::X, lo::L, hi::H) where {X,L,H} =
convert(promote_type(X,L,H), lo),
convert(promote_type(X,L,H), x)))

clamp(::Type{T}, x) where {T} = clamp(x, typemin(T), typemax(T)) % T
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe where {T<:Integer} ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. It doesn't make sense for floats - the % operator isn't defined, and the problem doesn't exist because conversion to a narrower float clamps to typemin and typemax (+/-Inf) anyway.

"""
clamp!(array::AbstractArray, lo, hi)

Expand Down
5 changes: 5 additions & 0 deletions test/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@

@test clamp.([0, 1, 2, 3, 4], 1.0, 3.0) == [1.0, 1.0, 2.0, 3.0, 3.0]
@test clamp.([0 1; 2 3], 1.0, 3.0) == [1.0 1.0; 2.0 3.0]

@test clamp(Int8,-200) === typemin(Int8)
@test clamp(Int8,100) === Int8(100)
@test clamp(Int8,200) === typemax(Int8)

begin
x = [0.0, 1.0, 2.0, 3.0, 4.0]
clamp!(x, 1, 3)
Expand Down