Reputation: 165
How do you get the (x - y) < 20
always positive?
I'd like to make a condition for:
getJOL :: [Int] -> String
getJOL [w,x,y,z] = if x - w < 20 && y - x < 20 && z - y < 20
then "Good calibration"
else "Bad calibration"
The difference between two values must be positive.
Upvotes: 3
Views: 772
Reputation: 120741
Yes, abs
is the function you want. That's the conventional name for |x| in most languages.
BTW you should probably not hard-code the case for exactly four list-elements. It's both unsafe (what if someone hands you a list with five elements?) and repetitive. Just recurse over the list, and abort when a pair with too large distance is found:
getJOL (w:x:ys)
| abs (x - w) >= 20 = "Bad calibration"
getJOL (_:xs) = getJOL xs
getJOL [] = "Good calibration"
Upvotes: 10
Reputation: 786
Just use the absolute values abs
. This will check, whether the absolute difference is lower than 20.
getJOL :: [Int] -> String
getJOL [w,x,y,z] = if abs(x - w) < 20 && abs(y - x) < 20 && abs(z - y) < 20
then "Good calibration"
else "Bad calibration"
Upvotes: 5