Logos
Island
Guru
Bluff
Bottomless
Methodology
Caves
Cannibals
Temple of the
Zillionth Feature
Performance
Falls
Nil Point
Compiler
Pass
Ivory
Towers
Software
Pirates
Cove
PhD
Springs
Mother
Lode
Binary
Jungle
Vast Typeless Traps
CoralRef
Elec
tric Sea
Pointer Forest
Impenetrable
IO Stream
Sli
ppery
Sl
opes
BuggyBight
Bay of NaĆÆv
etƩ
Valley
M
onomorphic
Memory
Leaks
Considerable Coast
CriticalPath
+ +
Lazy
Swamp
OptimizationRapids
+
+
+
+
+
+
+LaptopBeach
+
Doped
Silicon
Mines
Intermittent Faults
Data Flow
C
ont
rol Flo
w
+
Opaque
View
CodeWalk
Audit Trail
+
Loophole
Lair
Brown-out Current
N
LC
93
Z
R Q
+Scope
Nest
User
Desert
Great
Ad-Hoc
Volcano
Abstraction
Peaks
Introduction to Functional Languages
1. Referential transparency, no side effects
ā€œsubstitution of equals for equalsā€
2. Function definitions can be used
Suppose f is defined to be the function (fn x=>exp), then f
(arg) can be replaced by exp[x := arg]
3. Lists not arrays
4. Recursion not iteration
5. Higher-order functions
New idioms, total procedural abstraction
Rewriting
fun square x = x * x;
fun sos (x,y) = (square x) + (square y);
sos (3,4)
==> (square 3) + (square 4) [Def’n of sos]
==> 3*3 + (square 4) [Def’n of square]
==> 9 + (square 4) [Def’n of *]
==> 9 + 4*4 [Def’n of square]
==> 9 + 16 [Def’n of *]
==> 25 [Def’n of +]
Language of expressions only, no statements.
fun test (x) = if x>20 then "big" else "small"
test (sos (3,4))
==> test(25)
==> if 25>20 then "big" else "small"
Canonical Value
Canonical value. A canonical value is one which cannot be rewritten
further.
For example, 2+3 is not canonical, it evaluates to 5; 5 is a canonical
value.
See canonical in the ā€œThe on-line hacker Jargon File,ā€ version 4.4.7, 29
Dec 2003.
History of Functional Languages
1959 LISP: List processing, John McCarthy
1975 Scheme: MIT
1977 FP: John Backus
1980 Hope: Burstall, McQueen, Sannella
1984 COMMON LISP: Guy Steele
1985 ML: meta-language (of LCF), Robin Milner
1986 Miranda: Turner
1990 Haskell: Hudak & Wadler editors
xkcd—a webcomic of romance, sarcasm, math, and language by
Randall Munroe
Functional Languages
Lazy: don’t evaluate the function (constructor) arguments until needed
(call-by-name), e.g., Haskell. Permits infinite data structures.
Eager: call-by-value, e.g., ML
ML and Haskell
Similar to ML: functional, strongly-typed, algebraic data types,
type inferencing
Differences: no references, exception handling, or side effects of
any kind; lazy evaluation, list comprehensions
Introduction to Haskell
1. Haskell (1.0) 1990
2. By 1997 four iterations of language design (1.4)
Salient Features of Haskell
1. Strongly-typed, lazy, functional language
2. Polymorphic types, type inference
3. Algebraic type definitions
4. Pattern matching function definitions
5. System of classes
6. Interactive
Information about Haskell
O’Sullivan, Goerzen, Stewart Real World Haskell
Hutton, Graham, Programming in Haskell.
O’Donnell et al., Discrete Mathematics Using a Computer.
Introduction to SML
1. Robin Milner, Turing Award winner 1991
2. Metalanguage (ML) in Logic of Computable Functions (LCF)
1980s
3. Actually general purpose language
4. SML definition 1990, revised 1997.
5. AT&T (D. McQueen), Princeton (A. Appel) implementation
Salient Features of SML
1. Strongly-typed, eager, functional language
2. Polymorphic types, type inference
3. Algebraic type definitions
4. Pattern matching function definitions
5. Exception handling
6. Module (signatures/structures) system
7. Interactive
Information about ML
Ullman, Jeffrey D. Elements of ML Programming. Second edition.
Prentice-Hall, Upper Saddle River, New Jersey, 1998. 0-13-790387-1.
Paulson, Lawrence C. ML for the Working Programmer. Second
edition. Cambridge University Press, Cambridge, England, 1996.
ISBN 0-521-56543-X.
Haskell
Similar to ML: functional, strongly-typed, algebraic data types,
type inferencing
Differences: no references, exception handling, or side effects of
any kind; lazy evaluation, list comprehensions
fac n = if n==0 then 1 else n * fac (n-1)
data Tree = Leaf | Node (Tree , String, Tree)
size (Leaf) = 1
size (Node (l,_,r)) = size (l) + size (r)
squares = [ n*n | n <- [0..] ]
pascal = iterate (row ->zipWith (+) ([0]++row) (row
Haskell List Comprehension
[e | x1 <- l1, ..., xm <- lm, P1, ..., Pn]
e is an expression, xi is a variable, li is a list, Pi is a predicate
[ xˆ2 | x <- [ 1..10 ], even x]
[ xˆ2 | x <- [ 2,4..10 ] ]
[ x+y | x <- [1..3], y <- [1..4] ]
perms [] = [[]]
perms x = [a:y | a<-x, y<-perms (x  [a]) ]
quicksort [] = []
quicksort (s:xs) =
quicksort[x|x<-xs,x<s]++[s]++quicksort[x|x<-xs,x>=
Patterns
Patterns are a very natural way of expression complex problems.
Consider the code to re-balance red-black trees. This is usually quite
complex to express in a programming language. But with patterns it
can be more concise. Notice that constructors of user-defined types
(line RBTree) as well as pre-defined types (like list) can be used in
patterns.
data Color = R | B deriving (Show, Read)
data RBTree a = Empty | T Color (RBTree a) a (RBTr
deriving (Show, Read)
balance :: RBTree a -> a -> RBTree a -> RBTree a
balance (T R a x b) y (T R c z d)=T R (T B a x b)
balance (T R (T R a x b) y c) z d=T R (T B a x b)
balance (T R a x (T R b y c)) z d=T R (T B a x b)
balance a x (T R b y (T R c z d))=T R (T B a x b)
balance a x (T R (T R b y c) z d)=T R (T B a x b)
balance a x b = T B a x b
Functions
Prelude> : m Text.Show.Functions
Prelude Text.Show.Functions > x->x+1
<function >
Prelude Text.Show.Functions > :t x->x+(1::Int)
x->x+(1::Int) :: Int -> Int
Prelude Text.Show.Functions > :t x->x+1
x->x+1 :: (Num a) => a -> a
Partial Application
Any curried function may be called with fewer arguments than it was
defined for. The result is a function of the remaining arguments.
If f is a function Int->Bool->Int->Bool, then
f :: Int->Bool->Int->Bool
f 2 :: Bool->Int->Bool
f 2 True :: Int->Bool
f 2 True 3 :: Bool
Higher-order functions after lists.
Haskell Fold
ā€œA tutorial on the universality and expressiveness of foldā€ by Graham
Hutton.
Fold
foldr z[x1,x2,...,xn] = x1 (x2 (...(xn z)...))
foldr f z [x1, x2, ..., xn] = x1 f (x2 f (...(xn f z)...))
Fold
foldl z[x1,x2,...,xn] = (...((z x1) x2)...) xn
foldl f z [x1, x2, ..., xn] = (...((z f x1) f x2) ... ) f xn
Haskell Fold
foldr :: (b -> a -> a) -> a -> [b] ->
foldr f z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
foldl :: (a -> b -> a) -> a -> [b] ->
foldl f z [] = z
foldl f z (x:xs) = foldl f (f z x) xs
foldl’ :: (a -> b -> a) -> a -> [b] -> a
foldl’ f z0 xs = foldr f’ id xs z0
where f’ x k z = k $! f z x
[Real World Haskell says never use foldl instead use foldl’.]
Haskell Fold
Evaluates its first argument to head normal form, and then returns its
second argument as the result.
seq :: a -> b -> b
Strict (call-by-value) application, defined in terms of ’seq’.
($!) :: (a -> b) -> a -> b
f $! x = x ā€˜seqā€˜ f x
Haskell Fold
One important thing to note in the presence of lazy, or
normal-order evaluation, is that foldr will immediately return
the application of f to the recursive case of folding over the
rest of the list. Thus, if f is able to produce some part of its
result without reference to the recursive case, and the rest of
the result is never demanded, then the recursion will stop.
This allows right folds to operate on infinite lists. By contrast,
foldl will immediately call itself with new parameters until it
reaches the end of the list. This tail recursion can be
efficiently compiled as a loop, but can’t deal with infinite lists
at all – it will recurse forever in an infinite loop.
Haskell Fold
Another technical point to be aware of in the case of left
folds in a normal-order evaluation language is that the new
initial parameter is not being evaluated before the recursive
call is made. This can lead to stack overflows when one
reaches the end of the list and tries to evaluate the resulting
gigantic expression. For this reason, such languages often
provide a stricter variant of left folding which forces the
evaluation of the initial parameter before making the
recursive call, in Haskell, this is the foldl’ (note the
apostrophe) function in the Data.List library. Combined with
the speed of tail recursion, such folds are very efficient when
lazy evaluation of the final result is impossible or
undesirable.
Haskell Fold
sum’ = foldl (+) 0
product’ = foldl (*) 1
and’ = foldl (&&) True
or’ = foldl (||) False
concat’ = foldl (++) []
composel = foldl (.) id
composer = foldr (.) id
length = foldl (const (+1)) 0
list_identity = foldr (:) []
reverse’ = foldl (flip (:)) []
unions = foldl Set.union Set.empty
Haskell Fold
reverse = foldl ( xs x -> xs ++ [x]) []
map f = foldl ( xs x -> f x : xs) []
filter p = foldl ( xs x -> if p x then x:xs el
Haskell Fold
If this is your pattern
g [] = v
g (x:xs) = f x (g xs)
then
g = foldr f v
Haskell Data Structures
data Bool = False | True
data Color = Red | Green | Blue
deriving Show
data Day = Mon|Tue|Wed|Thu|Fri|Sat|Sun
deriving (Show,Eq,Ord)
Types and constructors capitalized.
Show allows Haskell to print data structures.
Haskell Data Structures
Constructors can take arguments.
data Shape = Circle Float | Rectangle Float Floa
deriving Show
area (Circle r) = pi*r*r
area (Rectangle s1 s2) = s1*s2
Haskell Classes
next :: (Enum a, Bounded a, Eq a) => a -> a
next x | x == maxBound = minBound
| otherwise = succ x
Haskell Classes
data Triangle = Triangle
data Square = Square
data Octagon = Octagon
class Shape s where
sides :: s -> Integer
instance Shape Triangle where
sides _ = 3
instance Shape Square where
sides _ = 4
instance Shape Octagon where
sides _ = 8
Haskell Types
Type constructors can type types as parameters.
data Maybe a = Nothing | Just a
maybe :: b -> (a -> b) -> Maybe a -> b
maybe n _ Nothing = n
maybe _ f (Just x) = f x
data Either a b = Left a | Right b
either :: (a -> c) -> (b -> c) -> Either a b ->
either f _ (Left x) = f x
either _ g (Right y) = g y
Haskell Lists
Data types can be recursive, as in lists:
data Nat = Nil | Succ Nat
data IList = Nil | Cons Integer IList
data PolyList a = Nil | Cons a (PolyList a)
Haskell Trees
See Hudak PPT, Ch7.
data SimpleTree = SimLeaf | SimBranch SimpleTree
data IntegerTree = IntLeaf Integer |
IntBranch IntegerTree IntegerTree
data InternalTree a = ILeaf |
IBranch a (InternalTree a) (InternalTree a)
data Tree a = Leaf a | Branch (Tree a) (Tree a)
data FancyTree a b = FLeaf a |
FBranch b (FancyTree a b) (FancyTree a b)
data GTree = GTree [GTree]
data GPTree a = GPTree a [GPTree a]
Nested Types
data List a = NilL | ConsL a (List a)
data Nest a = NilN | ConsN a (Nest (a,a))
data Bush a = NilB | ConsB a (Bush (Bush a))
data Node a = Node2 a a | Node3 a a a
data Tree a = Leaf a | Succ (Tree (Node a))
Bird and Meertens, Nested Datatypes, 1998.
Hinze, Finger Trees.
Haskell
input stream --> program --> output stream
Real World
[Char] --> program --> [Char]
Haskell World
module Main where
main = do
input <- getContents
putStr $ unlines $ f $ lines input
countWords :: String -> String
countWords = unlines . format . count . words
count :: [String] -> [(String,Int)]
count = map (ws->(head ws, length ws))
. groupBy (==)
. sort
Haskell
input stream --> program --> output stream
Real World
[Char] --> program --> [Char]
Haskell World
module Main where
main = interact countWords
countWords :: String -> String
countWords = unlines . format . count . words
count :: [String] -> [(String,Int)]
count = map (ws->(head ws, length ws))
. groupBy (==)
. sort

Introduction to Functional Languages

  • 1.
    Logos Island Guru Bluff Bottomless Methodology Caves Cannibals Temple of the ZillionthFeature Performance Falls Nil Point Compiler Pass Ivory Towers Software Pirates Cove PhD Springs Mother Lode Binary Jungle Vast Typeless Traps CoralRef Elec tric Sea Pointer Forest Impenetrable IO Stream Sli ppery Sl opes BuggyBight Bay of Naïv eté Valley M onomorphic Memory Leaks Considerable Coast CriticalPath + + Lazy Swamp OptimizationRapids + + + + + + +LaptopBeach + Doped Silicon Mines Intermittent Faults Data Flow C ont rol Flo w + Opaque View CodeWalk Audit Trail + Loophole Lair Brown-out Current N LC 93 Z R Q +Scope Nest User Desert Great Ad-Hoc Volcano Abstraction Peaks
  • 2.
    Introduction to FunctionalLanguages 1. Referential transparency, no side effects ā€œsubstitution of equals for equalsā€ 2. Function definitions can be used Suppose f is defined to be the function (fn x=>exp), then f (arg) can be replaced by exp[x := arg] 3. Lists not arrays 4. Recursion not iteration 5. Higher-order functions New idioms, total procedural abstraction
  • 3.
    Rewriting fun square x= x * x; fun sos (x,y) = (square x) + (square y); sos (3,4) ==> (square 3) + (square 4) [Def’n of sos] ==> 3*3 + (square 4) [Def’n of square] ==> 9 + (square 4) [Def’n of *] ==> 9 + 4*4 [Def’n of square] ==> 9 + 16 [Def’n of *] ==> 25 [Def’n of +] Language of expressions only, no statements. fun test (x) = if x>20 then "big" else "small" test (sos (3,4)) ==> test(25) ==> if 25>20 then "big" else "small"
  • 4.
    Canonical Value Canonical value.A canonical value is one which cannot be rewritten further. For example, 2+3 is not canonical, it evaluates to 5; 5 is a canonical value. See canonical in the ā€œThe on-line hacker Jargon File,ā€ version 4.4.7, 29 Dec 2003.
  • 5.
    History of FunctionalLanguages 1959 LISP: List processing, John McCarthy 1975 Scheme: MIT 1977 FP: John Backus 1980 Hope: Burstall, McQueen, Sannella 1984 COMMON LISP: Guy Steele 1985 ML: meta-language (of LCF), Robin Milner 1986 Miranda: Turner 1990 Haskell: Hudak & Wadler editors
  • 6.
    xkcd—a webcomic ofromance, sarcasm, math, and language by Randall Munroe
  • 7.
    Functional Languages Lazy: don’tevaluate the function (constructor) arguments until needed (call-by-name), e.g., Haskell. Permits infinite data structures. Eager: call-by-value, e.g., ML
  • 8.
    ML and Haskell Similarto ML: functional, strongly-typed, algebraic data types, type inferencing Differences: no references, exception handling, or side effects of any kind; lazy evaluation, list comprehensions
  • 9.
    Introduction to Haskell 1.Haskell (1.0) 1990 2. By 1997 four iterations of language design (1.4)
  • 10.
    Salient Features ofHaskell 1. Strongly-typed, lazy, functional language 2. Polymorphic types, type inference 3. Algebraic type definitions 4. Pattern matching function definitions 5. System of classes 6. Interactive
  • 12.
    Information about Haskell O’Sullivan,Goerzen, Stewart Real World Haskell Hutton, Graham, Programming in Haskell. O’Donnell et al., Discrete Mathematics Using a Computer.
  • 13.
    Introduction to SML 1.Robin Milner, Turing Award winner 1991 2. Metalanguage (ML) in Logic of Computable Functions (LCF) 1980s 3. Actually general purpose language 4. SML definition 1990, revised 1997. 5. AT&T (D. McQueen), Princeton (A. Appel) implementation
  • 14.
    Salient Features ofSML 1. Strongly-typed, eager, functional language 2. Polymorphic types, type inference 3. Algebraic type definitions 4. Pattern matching function definitions 5. Exception handling 6. Module (signatures/structures) system 7. Interactive
  • 15.
    Information about ML Ullman,Jeffrey D. Elements of ML Programming. Second edition. Prentice-Hall, Upper Saddle River, New Jersey, 1998. 0-13-790387-1. Paulson, Lawrence C. ML for the Working Programmer. Second edition. Cambridge University Press, Cambridge, England, 1996. ISBN 0-521-56543-X.
  • 16.
    Haskell Similar to ML:functional, strongly-typed, algebraic data types, type inferencing Differences: no references, exception handling, or side effects of any kind; lazy evaluation, list comprehensions fac n = if n==0 then 1 else n * fac (n-1) data Tree = Leaf | Node (Tree , String, Tree) size (Leaf) = 1 size (Node (l,_,r)) = size (l) + size (r) squares = [ n*n | n <- [0..] ] pascal = iterate (row ->zipWith (+) ([0]++row) (row
  • 17.
    Haskell List Comprehension [e| x1 <- l1, ..., xm <- lm, P1, ..., Pn] e is an expression, xi is a variable, li is a list, Pi is a predicate [ xˆ2 | x <- [ 1..10 ], even x] [ xˆ2 | x <- [ 2,4..10 ] ] [ x+y | x <- [1..3], y <- [1..4] ] perms [] = [[]] perms x = [a:y | a<-x, y<-perms (x [a]) ] quicksort [] = [] quicksort (s:xs) = quicksort[x|x<-xs,x<s]++[s]++quicksort[x|x<-xs,x>=
  • 18.
    Patterns Patterns are avery natural way of expression complex problems. Consider the code to re-balance red-black trees. This is usually quite complex to express in a programming language. But with patterns it can be more concise. Notice that constructors of user-defined types (line RBTree) as well as pre-defined types (like list) can be used in patterns.
  • 19.
    data Color =R | B deriving (Show, Read) data RBTree a = Empty | T Color (RBTree a) a (RBTr deriving (Show, Read) balance :: RBTree a -> a -> RBTree a -> RBTree a balance (T R a x b) y (T R c z d)=T R (T B a x b) balance (T R (T R a x b) y c) z d=T R (T B a x b) balance (T R a x (T R b y c)) z d=T R (T B a x b) balance a x (T R b y (T R c z d))=T R (T B a x b) balance a x (T R (T R b y c) z d)=T R (T B a x b) balance a x b = T B a x b
  • 20.
    Functions Prelude> : mText.Show.Functions Prelude Text.Show.Functions > x->x+1 <function > Prelude Text.Show.Functions > :t x->x+(1::Int) x->x+(1::Int) :: Int -> Int Prelude Text.Show.Functions > :t x->x+1 x->x+1 :: (Num a) => a -> a
  • 21.
    Partial Application Any curriedfunction may be called with fewer arguments than it was defined for. The result is a function of the remaining arguments. If f is a function Int->Bool->Int->Bool, then f :: Int->Bool->Int->Bool f 2 :: Bool->Int->Bool f 2 True :: Int->Bool f 2 True 3 :: Bool Higher-order functions after lists.
  • 25.
    Haskell Fold ā€œA tutorialon the universality and expressiveness of foldā€ by Graham Hutton.
  • 26.
    Fold foldr z[x1,x2,...,xn] =x1 (x2 (...(xn z)...)) foldr f z [x1, x2, ..., xn] = x1 f (x2 f (...(xn f z)...))
  • 27.
    Fold foldl z[x1,x2,...,xn] =(...((z x1) x2)...) xn foldl f z [x1, x2, ..., xn] = (...((z f x1) f x2) ... ) f xn
  • 28.
    Haskell Fold foldr ::(b -> a -> a) -> a -> [b] -> foldr f z [] = z foldr f z (x:xs) = f x (foldr f z xs) foldl :: (a -> b -> a) -> a -> [b] -> foldl f z [] = z foldl f z (x:xs) = foldl f (f z x) xs foldl’ :: (a -> b -> a) -> a -> [b] -> a foldl’ f z0 xs = foldr f’ id xs z0 where f’ x k z = k $! f z x [Real World Haskell says never use foldl instead use foldl’.]
  • 29.
    Haskell Fold Evaluates itsfirst argument to head normal form, and then returns its second argument as the result. seq :: a -> b -> b Strict (call-by-value) application, defined in terms of ’seq’. ($!) :: (a -> b) -> a -> b f $! x = x ā€˜seqā€˜ f x
  • 30.
    Haskell Fold One importantthing to note in the presence of lazy, or normal-order evaluation, is that foldr will immediately return the application of f to the recursive case of folding over the rest of the list. Thus, if f is able to produce some part of its result without reference to the recursive case, and the rest of the result is never demanded, then the recursion will stop. This allows right folds to operate on infinite lists. By contrast, foldl will immediately call itself with new parameters until it reaches the end of the list. This tail recursion can be efficiently compiled as a loop, but can’t deal with infinite lists at all – it will recurse forever in an infinite loop.
  • 31.
    Haskell Fold Another technicalpoint to be aware of in the case of left folds in a normal-order evaluation language is that the new initial parameter is not being evaluated before the recursive call is made. This can lead to stack overflows when one reaches the end of the list and tries to evaluate the resulting gigantic expression. For this reason, such languages often provide a stricter variant of left folding which forces the evaluation of the initial parameter before making the recursive call, in Haskell, this is the foldl’ (note the apostrophe) function in the Data.List library. Combined with the speed of tail recursion, such folds are very efficient when lazy evaluation of the final result is impossible or undesirable.
  • 32.
    Haskell Fold sum’ =foldl (+) 0 product’ = foldl (*) 1 and’ = foldl (&&) True or’ = foldl (||) False concat’ = foldl (++) [] composel = foldl (.) id composer = foldr (.) id length = foldl (const (+1)) 0 list_identity = foldr (:) [] reverse’ = foldl (flip (:)) [] unions = foldl Set.union Set.empty
  • 33.
    Haskell Fold reverse =foldl ( xs x -> xs ++ [x]) [] map f = foldl ( xs x -> f x : xs) [] filter p = foldl ( xs x -> if p x then x:xs el
  • 34.
    Haskell Fold If thisis your pattern g [] = v g (x:xs) = f x (g xs) then g = foldr f v
  • 35.
    Haskell Data Structures dataBool = False | True data Color = Red | Green | Blue deriving Show data Day = Mon|Tue|Wed|Thu|Fri|Sat|Sun deriving (Show,Eq,Ord) Types and constructors capitalized. Show allows Haskell to print data structures.
  • 36.
    Haskell Data Structures Constructorscan take arguments. data Shape = Circle Float | Rectangle Float Floa deriving Show area (Circle r) = pi*r*r area (Rectangle s1 s2) = s1*s2
  • 37.
    Haskell Classes next ::(Enum a, Bounded a, Eq a) => a -> a next x | x == maxBound = minBound | otherwise = succ x
  • 38.
    Haskell Classes data Triangle= Triangle data Square = Square data Octagon = Octagon class Shape s where sides :: s -> Integer instance Shape Triangle where sides _ = 3 instance Shape Square where sides _ = 4 instance Shape Octagon where sides _ = 8
  • 39.
    Haskell Types Type constructorscan type types as parameters. data Maybe a = Nothing | Just a maybe :: b -> (a -> b) -> Maybe a -> b maybe n _ Nothing = n maybe _ f (Just x) = f x data Either a b = Left a | Right b either :: (a -> c) -> (b -> c) -> Either a b -> either f _ (Left x) = f x either _ g (Right y) = g y
  • 40.
    Haskell Lists Data typescan be recursive, as in lists: data Nat = Nil | Succ Nat data IList = Nil | Cons Integer IList data PolyList a = Nil | Cons a (PolyList a)
  • 41.
    Haskell Trees See HudakPPT, Ch7. data SimpleTree = SimLeaf | SimBranch SimpleTree data IntegerTree = IntLeaf Integer | IntBranch IntegerTree IntegerTree data InternalTree a = ILeaf | IBranch a (InternalTree a) (InternalTree a) data Tree a = Leaf a | Branch (Tree a) (Tree a) data FancyTree a b = FLeaf a | FBranch b (FancyTree a b) (FancyTree a b) data GTree = GTree [GTree] data GPTree a = GPTree a [GPTree a]
  • 42.
    Nested Types data Lista = NilL | ConsL a (List a) data Nest a = NilN | ConsN a (Nest (a,a)) data Bush a = NilB | ConsB a (Bush (Bush a)) data Node a = Node2 a a | Node3 a a a data Tree a = Leaf a | Succ (Tree (Node a)) Bird and Meertens, Nested Datatypes, 1998. Hinze, Finger Trees.
  • 43.
    Haskell input stream -->program --> output stream Real World [Char] --> program --> [Char] Haskell World module Main where main = do input <- getContents putStr $ unlines $ f $ lines input countWords :: String -> String countWords = unlines . format . count . words count :: [String] -> [(String,Int)] count = map (ws->(head ws, length ws)) . groupBy (==) . sort
  • 44.
    Haskell input stream -->program --> output stream Real World [Char] --> program --> [Char] Haskell World module Main where main = interact countWords countWords :: String -> String countWords = unlines . format . count . words count :: [String] -> [(String,Int)] count = map (ws->(head ws, length ws)) . groupBy (==) . sort