Difference between revisions of "Declaration vs. expression style"
From HaskellWiki
(Add table borders) 
(Add link to Let vs. Where and History of Haskell pages) 

Line 56:  Line 56:  
== See also == 
== See also == 

−  
+  * [[Let vs. Where]] 

−  * http://research.microsoft.com/~simonpj/papers/historyofhaskell/ section 4.4 

+  * [[History of Haskell]] (in section 4.4) 

[[Category:Style]] 
[[Category:Style]] 
Latest revision as of 00:41, 23 August 2008
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.
Comparison
As illustration for the two styles, Simon Peyton Jones give two implementations of the Prelude function filter
:
filter :: (a > Bool) > [a] > [a]
Declaration style
filter p [] = []
filter p (x:xs)
 p x = x : rest
 otherwise = rest
where
rest = filter p xs
Expression style
filter =
\p > \ xs >
case xs of
[] > []
(x:xs) >
let rest = filter p xs
in if p x
then x : rest
else rest
Syntactic elements
There are characteristic elements of both styles.
Declaration style  Expressionstyle  

where clause

let expression
 
Function arguments on left hand side:  f x = x*x 
Lambda abstraction:  f = \x > x*x

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

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

See also
 Let vs. Where
 History of Haskell (in section 4.4)