Re: [RFC] [Discussion] Add clamp function
| From: | Kyle Katarn | Date: | Thu, 28 Aug 2025 18:26:08 +0000 |
| Subject: | Re: [RFC] [Discussion] Add clamp function | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-128588@lists.php.net to get a copy of this message | ||
Hi,
2025-08-28 at 09:37, Tim Düsterhus <tim@bastelstu.be> wrote :
> Hi
>
> Am 2025-08-28 08:35, schrieb Hans Krentel:
> > This also highlights a minor but important clarification for the
> > documentation. To make the behavior perfectly unambiguous, I suggest
> > a small edit to explicitly state the bounds are inclusive.
>
> This is a good point and I agree that it should be spelled out
> explicitly. However to me this also raises the question if the interval
> boundaries should be configurable to switch between closed intervals and
> (half-)open intervals. For many applications of continuous values a
> right-open interval (excluding the upper boundary) is more useful, since
> this makes it easy to generate non-overlapping ranges (e.g. to clamp to
> a given day when passing DateTimeImmutable). This would also provide an
> additional value-add over the min-max construction, where the boundaries
> would need to be calculated manually, which is super complicated to do
> in userland for floats.
>
> There's precedent in ext/random with the Randomizer::getFloat() method
> that takes a Random\IntervalBoundary enum to decide on the the
> interpretation of the boundary values. Translated to
clamp()
> this
> could mean:
>
> $value = 1.0;
> clamp($value, 0.0, 1.0, IntervalBoundary::ClosedOpen); //
> 0.999999999999999888978
>
> Best regards
> Tim Düsterhus
>
Just my opinion but the function aims to provide an alternative to
min(max()) that would be:
- easier to read
- faster to execute
If having many different behaviors depending on an option and so a lot of
if-else path complexity, then it will tend to defeat the second goal. I
would add it if there is a strong interest, otherwise I'd rather stick to a
minimalist implementation (like seen in most languages where clamp() is
available.