Personal tools

Declaration vs. expression style

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
(taken table from "History of Haskell")
 
(SPJ's filter example)
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.
   
  +
  +
As illustration for the two styles, Simon Peyton Jones give two implementations of the Prelude function <hask>filter</hask>:
  +
<haskell>
  +
filter :: (a -> Bool) -> [a] -> [a]
  +
</haskell>
  +
  +
== Declaration style ==
  +
  +
<haskell>
  +
filter p [] = []
  +
filter p (x:xs)
  +
| p x = x : rest
  +
| otherwise = rest
  +
where
  +
rest = filter p xs
  +
</haskell>
  +
  +
== Expression style ==
  +
  +
<haskell>
  +
filter =
  +
\p -> \ xs ->
  +
case xs of
  +
[] -> []
  +
(x:xs) ->
  +
let rest = filter p xs
  +
in if p x
  +
then x : rest
  +
else rest
  +
</haskell>
  +
  +
== Comparison ==
   
 
There are characteristic elements of both styles.
 
There are characteristic elements of both styles.

Revision as of 12:53, 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.


As illustration for the two styles, Simon Peyton Jones give two implementations of the Prelude function
filter
:
filter :: (a -> Bool) -> [a] -> [a]

Contents

1 Declaration style

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

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

3 Comparison

There are characteristic elements of both styles.

Declaration style Expression-style
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 ...

4 See also