开发者

Guarded Equations in Haskell

开发者 https://www.devze.com 2022-12-19 08:22 出处:网络
Can somebody provide me with an easy to understand explanation of a guarded equation as it is used in Haskell and also its mathematical sens开发者_运维知识库e?Haskell guards can be viewed as a mathema

Can somebody provide me with an easy to understand explanation of a guarded equation as it is used in Haskell and also its mathematical sens开发者_运维知识库e?


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.


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,

Guarded Equations in Haskell

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消