Can somebody provide me with an easy to understand explanation of a guarded equation as it is used in Haskell and also its mathematical sense?
A guarded equation is the Haskell equivalent construct of a piecewise function.
In the prelude, it defines otherwise = True . Using it in a pattern match just shadows that definition, introducing a new, more local variable which also happens to be called otherwise .
That apostrophe doesn't have any special meaning in Haskell's syntax. It's a valid character to use in a function name. We usually use ' to either denote a strict version of a function (one that isn't lazy) or a slightly modified version of a function or a variable.
in goes along with let to name one or more local expressions in a pure function.
Haskell guards can be viewed as a mathematical function defined piecewise over the input.
foo x | x < 0 = bar
| x < 5 = baz
| x < 20 = quux
| otherwise = quaffle
would be written by a mathematician like:
foo(x) = { bar, if x < 0
baz, if x >= 0 && x < 5
quux, if x >= 5 && x < 20
quaffle, if x >= 20
Each of the guards in a Haskell function implicitly carries the negation of all of the guards that precede it, because they are tried one after the other.
Haskell chooses to write the guard on the left of the equal sign to make it easier to follow the control flow. If you choose to read the | as 'such that' then it becomes fairly intuitive.
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