mathhaskellequations

Guarded Equations in Haskell


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?


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.