Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

A guarded equation is an equation (a statement about an equality) which involves what is called a case distinction. An example is:

fac :: Integer -> Integer
fac n | n > 0     = n * fac (n - 1)
      | otherwise = 1

This is a definition of the factorial function. Mathematicians would write,

Latex

0! = 1, by definition. For all values n greater than 0, n! can be defined in terms of (n - 1)!. This is not the case for 0!. That is the reason that two cases need to be distinguished. And that is what a guarded equation does.

A guarded equation is the Haskell equivalent construct of a piecewise function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top