I just found out about guarded equations in Haskell, here's an example:
abs n | n >= 0 = n
| otherwise = -n
it basically says that function abs
returns n
if n >= 0
, otherwise it returns -n
.
In the book it says that the the standard prelude otherwise is defined like this: otherwise = True
, why is that?
CodePudding user response:
The reason why otherwise
exists - and why it is defined the way it is - is purely for stylistic purposes. The example you gave could be just as validly, writtent like so:
abs n | n >= 0 = n
| True = -n
But otherwise
just reads more nicely. In particular it reads like a mathematical definition.
CodePudding user response:
It is defined as True
, because the otherwise
case always has to succeed.
For example, we can write:
signum n | n < 0 = -1
| n == 0 = 0
| otherwise = 1
and in this case Haskell checks if n < 0
is True
, then, if it is False
it checks if n == 0
is True
, and then if it is False
it checks if otherwise
is True
. As you can see, it has to go case by case until it finds one that is True
, this is why otherwise has to be True (in order to succeed, when everything else is False
).