How to put values in limit?

I am trying to limit the values so that whenever the program gets a value first it looks at it if its inbound or not. For example, I need the users to input the r, g, and b colors but if it’s greater then 255 then it should take it as 255 and if it’s less then 0 then it should take it as 0.

rgb(r, g, b)

rgb(-23, 345, 222) 

should be 

rgb(0, 255, 222)

I have tried guards and case statements but it doesn’t look good.


I’m on a mobile device so untested but something like:

def rgb(r, g, b) do
  r = max(0, r) |> min(255)
  # Same for G and B

(Corrected per the comment below)

1 Like

It worked, thanks a lot. It’s a very sleek method of limiting the numbers. Just one modification. You are using pipe operator so there won’t be r as the first argument.

 def rgb(r, g, b) do
    r = max(0, r) |> min(255)
    g = max(0, g) |> min(255)
    b = max(0, b) |> min(255)

If you need to clamp a number n such that 0 <= n < m, you can use rem/2.

clamped = rem(n, m)

If now you need to clamp it with another lower bound, like in l <= n < m you can do it like this:

delta = m - l
clamped = rem(n - delta, m - delta) + delta

For most cases when I was checking, clamped value meant saturating counter, so it would be more like:

def clamp(n, min..max), do: min(min, max(n, max))

Args! Yes, you are totally right… Seems as if I have confused some bits…