SlideShare a Scribd company logo
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
Introduction to Functional Languages
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.
Introduction to Functional Languages
Introduction to Functional Languages
Introduction to Functional Languages
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

More Related Content

PDF
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
PDF
Real World Haskell: Lecture 6
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
PDF
[FLOLAC'14][scm] Functional Programming Using Haskell
PDF
Real World Haskell: Lecture 3
PDF
Real World Haskell: Lecture 1
PDF
Functional Programming by Examples using Haskell
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit - Haskell and...
Real World Haskell: Lecture 6
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
[FLOLAC'14][scm] Functional Programming Using Haskell
Real World Haskell: Lecture 3
Real World Haskell: Lecture 1
Functional Programming by Examples using Haskell
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 5

What's hot (20)

PDF
Sequence and Traverse - Part 2
PDF
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
PDF
Real World Haskell: Lecture 2
PDF
Monads do not Compose
PPTX
A brief introduction to lisp language
PPTX
Prolog & lisp
PDF
Scala 3 enum for a terser Option Monad Algebraic Data Type
PDF
Real World Haskell: Lecture 7
PDF
Real World Haskell: Lecture 4
PPT
Advance LISP (Artificial Intelligence)
PDF
Real World Haskell: Lecture 5
PDF
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
PDF
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
PDF
Left and Right Folds - Comparison of a mathematical definition and a programm...
PDF
Learn a language : LISP
PDF
Haskell for data science
KEY
Five Languages in a Moment
PPT
INTRODUCTION TO LISP
Sequence and Traverse - Part 2
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Real World Haskell: Lecture 2
Monads do not Compose
A brief introduction to lisp language
Prolog & lisp
Scala 3 enum for a terser Option Monad Algebraic Data Type
Real World Haskell: Lecture 7
Real World Haskell: Lecture 4
Advance LISP (Artificial Intelligence)
Real World Haskell: Lecture 5
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Left and Right Folds - Comparison of a mathematical definition and a programm...
Learn a language : LISP
Haskell for data science
Five Languages in a Moment
INTRODUCTION TO LISP
Ad

Viewers also liked (12)

PPTX
Passescd
PPT
Classification of Compilers
PPT
Introduction to Compiler Construction
PDF
Compiler unit 1
PDF
Lecture 01 introduction to compiler
PPT
Compiler Design Basics
DOC
Compiler Design(NANTHU NOTES)
PPTX
Phases of Compiler
PPT
Compiler Design
PPT
What is Compiler?
PPTX
Compiler Chapter 1
Passescd
Classification of Compilers
Introduction to Compiler Construction
Compiler unit 1
Lecture 01 introduction to compiler
Compiler Design Basics
Compiler Design(NANTHU NOTES)
Phases of Compiler
Compiler Design
What is Compiler?
Compiler Chapter 1
Ad

Similar to Introduction to Functional Languages (20)

KEY
An Introduction to Functional Programming using Haskell
PDF
Why Haskell Matters
PPT
haskell5.ppt is a marketing document lol
PDF
Functional programming with haskell
PDF
The Next Great Functional Programming Language
PPTX
Introduction to Haskell: 2011-04-13
PDF
Functional programming using haskell notes iitk
PDF
02. haskell motivation
PPTX
Functional programming seminar (haskell)
PDF
Functional Programming
PDF
High-Performance Haskell
PDF
Reasoning about laziness
PDF
01. haskell introduction
PDF
Functional Programming and Haskell - TWBR Away Day 2011
PDF
Haskell - Being lazy with class
PDF
Introduction to Functional Programming with Haskell and JavaScript
PDF
Programming in Haskell 2nd Edition Graham Hutton
PDF
Making the most of lambdas
PPTX
(2015 06-16) Three Approaches to Monads
An Introduction to Functional Programming using Haskell
Why Haskell Matters
haskell5.ppt is a marketing document lol
Functional programming with haskell
The Next Great Functional Programming Language
Introduction to Haskell: 2011-04-13
Functional programming using haskell notes iitk
02. haskell motivation
Functional programming seminar (haskell)
Functional Programming
High-Performance Haskell
Reasoning about laziness
01. haskell introduction
Functional Programming and Haskell - TWBR Away Day 2011
Haskell - Being lazy with class
Introduction to Functional Programming with Haskell and JavaScript
Programming in Haskell 2nd Edition Graham Hutton
Making the most of lambdas
(2015 06-16) Three Approaches to Monads

More from suthi (20)

PDF
Object Oriented Programming -- Dr Robert Harle
PDF
THE ROLE OF EDGE COMPUTING IN INTERNET OF THINGS
PDF
EDGE COMPUTING: VISION AND CHALLENGES
PDF
Document Classification Using KNN with Fuzzy Bags of Word Representation
DOC
AUTOMATA THEORY - SHORT NOTES
DOC
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
DOC
PARALLEL ARCHITECTURE AND COMPUTING - SHORT NOTES
DOC
SOFTWARE QUALITY ASSURANCE AND TESTING - SHORT NOTES
DOC
COMPUTER HARDWARE - SHORT NOTES
DOC
DATA BASE MANAGEMENT SYSTEM - SHORT NOTES
DOC
OPERATING SYSTEM - SHORT NOTES
DOC
SOFTWARE ENGINEERING & ARCHITECTURE - SHORT NOTES
DOC
ALGORITHMS - SHORT NOTES
DOC
COMPUTER NETWORKS - SHORT NOTES
DOC
DATA STRUCTURES - SHORT NOTES
DOC
ARTIFICIAL INTELLIGENCE - SHORT NOTES
PDF
LIGHT PEAK
PDF
Action Recognition using Nonnegative Action
PDF
C Programming Tutorial
PDF
Data structure - mcqs
Object Oriented Programming -- Dr Robert Harle
THE ROLE OF EDGE COMPUTING IN INTERNET OF THINGS
EDGE COMPUTING: VISION AND CHALLENGES
Document Classification Using KNN with Fuzzy Bags of Word Representation
AUTOMATA THEORY - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
PARALLEL ARCHITECTURE AND COMPUTING - SHORT NOTES
SOFTWARE QUALITY ASSURANCE AND TESTING - SHORT NOTES
COMPUTER HARDWARE - SHORT NOTES
DATA BASE MANAGEMENT SYSTEM - SHORT NOTES
OPERATING SYSTEM - SHORT NOTES
SOFTWARE ENGINEERING & ARCHITECTURE - SHORT NOTES
ALGORITHMS - SHORT NOTES
COMPUTER NETWORKS - SHORT NOTES
DATA STRUCTURES - SHORT NOTES
ARTIFICIAL INTELLIGENCE - SHORT NOTES
LIGHT PEAK
Action Recognition using Nonnegative Action
C Programming Tutorial
Data structure - mcqs

Recently uploaded (20)

PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Cell Types and Its function , kingdom of life
PDF
Classroom Observation Tools for Teachers
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
STATICS OF THE RIGID BODIES Hibbelers.pdf
01-Introduction-to-Information-Management.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Microbial disease of the cardiovascular and lymphatic systems
Supply Chain Operations Speaking Notes -ICLT Program
Complications of Minimal Access Surgery at WLH
Cell Types and Its function , kingdom of life
Classroom Observation Tools for Teachers
Microbial diseases, their pathogenesis and prophylaxis
Pharma ospi slides which help in ospi learning
Final Presentation General Medicine 03-08-2024.pptx
PPH.pptx obstetrics and gynecology in nursing
O7-L3 Supply Chain Operations - ICLT Program
O5-L3 Freight Transport Ops (International) V1.pdf
human mycosis Human fungal infections are called human mycosis..pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Module 4: Burden of Disease Tutorial Slides S2 2025
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...

Introduction to Functional Languages

  • 1. 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
  • 2. 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
  • 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 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
  • 6. xkcd—a webcomic of romance, sarcasm, math, and language by Randall Munroe
  • 7. 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
  • 8. 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
  • 9. Introduction to Haskell 1. Haskell (1.0) 1990 2. By 1997 four iterations of language design (1.4)
  • 10. 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
  • 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 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
  • 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 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.
  • 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> : 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
  • 21. 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.
  • 25. Haskell Fold “A tutorial on 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 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
  • 30. 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.
  • 31. 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.
  • 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 this is your pattern g [] = v g (x:xs) = f x (g xs) then g = foldr f v
  • 35. 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.
  • 36. 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
  • 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 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
  • 40. 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)
  • 41. 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]
  • 42. 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.
  • 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