views:

155

answers:

3

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?

+4  A: 

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
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
"quaffle"... that's a new one for me :D
trinithis
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
@Tony, exactly.
Edward Kmett
+1  A: 

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

Ignacio Vazquez-Abrams
+4  A: 

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
@Stephan202: Here the image says "Only texify.com may use mimetext on this server. Please read ... Thank you, John Forkosh"
yairchu
@yairchu: that's odd (I can see the image here; it's cached I suppose). I'll look into it, thanks! For now, the image is this one: http://bit.ly/cpk7H3
Stephan202
Alright, hosted it myself.
Stephan202