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

What's hot (20)

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

Viewers also liked (12)

PPTX
Passescd
BBDITM LUCKNOW
 
PPT
Classification of Compilers
Sarmad Ali
 
PPT
Introduction to Compiler Construction
Sarmad Ali
 
PDF
Compiler unit 1
BBDITM LUCKNOW
 
PDF
Lecture 01 introduction to compiler
Iffat Anjum
 
PPT
Compiler Design Basics
Akhil Kaushik
 
DOC
Compiler Design(NANTHU NOTES)
guest251d9a
 
PPTX
Phases of Compiler
Tanzeela_Hussain
 
PPT
Compiler Design
Mir Majid
 
PPT
What is Compiler?
Huawei Technologies
 
PPTX
Compiler Chapter 1
Huawei Technologies
 
Passescd
BBDITM LUCKNOW
 
Classification of Compilers
Sarmad Ali
 
Introduction to Compiler Construction
Sarmad Ali
 
Compiler unit 1
BBDITM LUCKNOW
 
Lecture 01 introduction to compiler
Iffat Anjum
 
Compiler Design Basics
Akhil Kaushik
 
Compiler Design(NANTHU NOTES)
guest251d9a
 
Phases of Compiler
Tanzeela_Hussain
 
Compiler Design
Mir Majid
 
What is Compiler?
Huawei Technologies
 
Compiler Chapter 1
Huawei Technologies
 
Ad

Similar to Introduction to Functional Languages (20)

PDF
Frp2016 3
Kirill Kozlov
 
PDF
Scala. Introduction to FP. Monads
Kirill Kozlov
 
PDF
Using Language Oriented Programming to Execute Computations on the GPU
Skills Matter
 
PPT
Haskell retrospective
chenge2k
 
PDF
Fp in scala part 1
Hang Zhao
 
PDF
Programming in Scala - Lecture Two
Angelo Corsaro
 
PPT
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
PPT
Functional Programming Past Present Future
IndicThreads
 
PDF
Lambda? You Keep Using that Letter
Kevlin Henney
 
PDF
haskell_fp1
Sambaiah Kilaru
 
PDF
Functional programming ii
Prashant Kalkar
 
PDF
Why Haskell Matters
romanandreg
 
PDF
The Next Great Functional Programming Language
John De Goes
 
PPTX
Special topics in finance lecture 2
Dr. Muhammad Ali Tirmizi., Ph.D.
 
PDF
Is there a perfect data-parallel programming language? (Experiments with More...
Julian Hyde
 
PDF
Fp in scala part 2
Hang Zhao
 
PPT
Scala introduction
Yardena Meymann
 
PDF
Humble introduction to category theory in haskell
Jongsoo Lee
 
PPT
haskell5.ppt is a marketing document lol
dopointt
 
PPTX
Functional programming seminar (haskell)
Bikram Thapa
 
Frp2016 3
Kirill Kozlov
 
Scala. Introduction to FP. Monads
Kirill Kozlov
 
Using Language Oriented Programming to Execute Computations on the GPU
Skills Matter
 
Haskell retrospective
chenge2k
 
Fp in scala part 1
Hang Zhao
 
Programming in Scala - Lecture Two
Angelo Corsaro
 
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Functional Programming Past Present Future
IndicThreads
 
Lambda? You Keep Using that Letter
Kevlin Henney
 
haskell_fp1
Sambaiah Kilaru
 
Functional programming ii
Prashant Kalkar
 
Why Haskell Matters
romanandreg
 
The Next Great Functional Programming Language
John De Goes
 
Special topics in finance lecture 2
Dr. Muhammad Ali Tirmizi., Ph.D.
 
Is there a perfect data-parallel programming language? (Experiments with More...
Julian Hyde
 
Fp in scala part 2
Hang Zhao
 
Scala introduction
Yardena Meymann
 
Humble introduction to category theory in haskell
Jongsoo Lee
 
haskell5.ppt is a marketing document lol
dopointt
 
Functional programming seminar (haskell)
Bikram Thapa
 
Ad

More from suthi (20)

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

Recently uploaded (20)

PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PDF
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
community health nursing question paper 2.pdf
Prince kumar
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 

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