Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 977
Tony The Lion Avatar asked Feb 08 '10 22:02

Tony The Lion


People also ask

What is guarded equation in Haskell?

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

What does otherwise do in Haskell?

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 .

What does apostrophe mean in Haskell?

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.

What does in do in Haskell?

in goes along with let to name one or more local expressions in a pure function.


1 Answers

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.

like image 99
Edward Kmett Avatar answered Sep 26 '22 20:09

Edward Kmett