# Declaration vs. expression style

### From HaskellWiki

(Difference between revisions)

(SPJ's filter example) |
(introduction) |
||

Line 2: | Line 2: | ||

which are both supported by Haskell mainly because several language designers preferred these different styles. |
which are both supported by Haskell mainly because several language designers preferred these different styles. |
||

+ | In the '''declaration style''' you formulate an algorithm in terms of several equations that shall be satisfied. |
||

+ | In the '''expression style''' you compose big expressions from small expressions. |
||

+ | |||

+ | == Comparison == |
||

As illustration for the two styles, Simon Peyton Jones give two implementations of the Prelude function <hask>filter</hask>: |
As illustration for the two styles, Simon Peyton Jones give two implementations of the Prelude function <hask>filter</hask>: |
||

Line 8: | Line 12: | ||

</haskell> |
</haskell> |
||

− | == Declaration style == |
+ | === Declaration style === |

<haskell> |
<haskell> |
||

Line 19: | Line 23: | ||

</haskell> |
</haskell> |
||

− | == Expression style == |
+ | === Expression style === |

<haskell> |
<haskell> |
||

Line 33: | Line 37: | ||

</haskell> |
</haskell> |
||

− | == Comparison == |
+ | == Syntactic elements == |

There are characteristic elements of both styles. |
There are characteristic elements of both styles. |
||

{| |
{| |
||

− | | Declaration style || || Expression-style || |
+ | | '''Declaration style''' || || '''Expression-style''' || |

|- |
|- |
||

| <hask>where</hask> clause || || <hask>let</hask> expression || |
| <hask>where</hask> clause || || <hask>let</hask> expression || |

## Revision as of 12:58, 3 July 2007

There are two main styles of writing functional programs, which are both supported by Haskell mainly because several language designers preferred these different styles.

In the **declaration style** you formulate an algorithm in terms of several equations that shall be satisfied.
In the **expression style** you compose big expressions from small expressions.

## Contents |

## 1 Comparison

As illustration for the two styles, Simon Peyton Jones give two implementations of the Prelude functionfilter

filter :: (a -> Bool) -> [a] -> [a]

### 1.1 Declaration style

filter p [] = [] filter p (x:xs) | p x = x : rest | otherwise = rest where rest = filter p xs

### 1.2 Expression style

filter = \p -> \ xs -> case xs of [] -> [] (x:xs) -> let rest = filter p xs in if p x then x : rest else rest

## 2 Syntactic elements

There are characteristic elements of both styles.

Declaration style |
Expression-style |
||

where |
let |
||

Function arguments on left hand side: | f x = x*x |
Lambda abstraction: | f = \x -> x*x |

Pattern matching in function definitions: | f [] = 0 |
case |
f xs = case xs of [] -> 0 |

Guards on function definitions: | f [x] | x>0 = 'a' |
if |
f [x] = if x>0 then 'a' else ... |