Home > Enterprise >  why there is no conditional statements in the last line of this code?
why there is no conditional statements in the last line of this code?

Time:05-04

In the following code you have to write a function to check if a List is soretd 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? like why we don't need to check if it's True or False?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related