In the following code you have to write a function to check if a list is sorted or not.
isOrd :: [Int] -> Bool
isOrd [] = True
isOrd [_] = True
isOrd (x:y:xs) = x<=y && isOrd (y:xs)
I would like to know why there is no need to write if/then/else or case for the last line? Why don't we need to check if it's True or False?
What if/then/else would you propose writing? The one I would imagine would look something like this:
isOrd (x:y:xs) = if x<=y && isOrd (y:xs)
then True
else False
But we know that if x then True else False is always just a particularly long-winded way to write x. So there's not really any need for a specific conditional branch here: we can just return the condition itself.
That is checked by the (&&) :: Bool -> Bool -> Bool function: if the left operand is False, it returns False. If the left operand is True, it returns the right operand.
Indeed, the function is implemented as [src]:
(&&) :: Bool -> Bool -> Bool True && x = x False && _ = False
It thus will check the first operand, and based on that either return False, or recurse on the rest of the function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With