rebellion
rebellion copied to clipboard
Ensuring a value is within a range
If you want to make sure a number x
is between <lowest>
and <highest>
, you have to do something like this:
(max <lowest> (min <highest> x))
This is kind of confusing and easy to get wrong. For example, I've made this mistake countless times:
(max <highest> (min <lowest> x))
This could instead be expressed with a range-clamp
function. Signature:
(range-clamp [range inclusive-range?] [v any/c]) -> any/c
Examples:
> (range-clamp (closed-range 1 9) 4)
4
> (range-clamp (closed-range 1 9) 8000)
9
> (range-clamp (closed-range 1 9) -8000)
1
> (range-clamp (at-most-range 9) 8000)
9
> (range-clamp (at-most-range 9) -8000)
-8000
> (range-clamp (at-least-range 1) 8000)
8000
> (range-clamp (at-least-range 1) -8000)
1
There isn't really any way to do this with ranges that have exclusive bounds, but it can be done with ranges that are unbounded. So there needs to be some sort of inclusive-range?
predicate, and probably an exclusive-range?
predicate. Paradoxically, (unbounded-range)
is both an inclusive range and an exclusive range by this definition.