14

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?

nbro
  • 15,395
  • 32
  • 113
  • 196
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415

3 Answers3

13

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.

Edward Kmett
  • 29,632
  • 7
  • 85
  • 107
  • So, its kind of like executing a function on a condition that... and depending on the condition, it will execute only that function where the condition is true, and all previous conditions will have been false? right? – Tony The Lion Feb 08 '10 at 22:35
  • 1
    "quaffle"... that's a new one for me :D – Thomas Eding Feb 09 '10 at 06:00
  • 1
    I read the "|" as "when": `foo x, when x < 0, = bar ... when x < 5, = baz` and so on. Not to be confused with `when` though. – Nefrubyr Feb 09 '10 at 11:45
9

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.

Stephan202
  • 59,965
  • 13
  • 127
  • 133
4

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358