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

Num.clamp : Num a, Num bound, Num bound -> Num a #2439

Open
JanCVanB opened this issue Feb 2, 2022 · 3 comments
Open

Num.clamp : Num a, Num bound, Num bound -> Num a #2439

JanCVanB opened this issue Feb 2, 2022 · 3 comments
Labels
builtins question Question about the language

Comments

@JanCVanB
Copy link
Sponsor Collaborator

JanCVanB commented Feb 2, 2022

Should this be a builtin?

Inspired by C++ std::clamp, #2411, and the imagined verbosity of implementing this in pure Roc.

Examples:

Num.clamp 3 4 6 == 4
Num.clamp 5 4 6 == 5
Num.clamp 7 4 6 == 6

Num.clamp Num.maxU16 Num.minI8 Num.maxI8 == (Num.maxI8 |> Num.toU16)
@JanCVanB JanCVanB added question Question about the language builtins labels Feb 2, 2022
@rtfeldman
Copy link
Sponsor Contributor

Makes sense to me! 👍

So I assume the type would be clamp : Num a, Num a, Num a -> Num a yeah?

@JanCVanB
Copy link
Sponsor Collaborator Author

JanCVanB commented Feb 2, 2022

Actually, take a look at that second example:

Num.clamp Num.maxU16 Num.minI8 Num.maxI8 == (Num.maxI8 |> Num.toU16)

I'm hoping this function can help #2411 by clamping one type to another's bounds before casting it:

toI8Clamped = \n -> n |> Num.clamp Num.minI8 Num.maxI8 |> Num.toI8
toI8Clamped Num.maxU16 == Num.maxI8

However, if all the types are the same, then a signed minimum bound couldn't be used to clamp an unsigned input, since it's unrepresentable in the unsigned type:

toI8ClampedUgly = \n -> n |> Num.clamp 0 (Num.maxI8 |> Num.toU16) |> Num.toI8
toI8ClampedUgly Num.maxU16 == (Num.maxI8 |> Num.toU16)

Right?

@ayazhafiz
Copy link
Sponsor Member

ayazhafiz commented Feb 7, 2022

I would prefer clamp to take a single type parameter as suggested in #2439 (comment), otherwise it feels a little bit too magical IMO

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
builtins question Question about the language
Projects
None yet
Development

No branches or pull requests

3 participants