SlideShare a Scribd company logo
1 of 44
Download to read offline
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

More Related Content

What's hot

Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Philip Schwarz
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Philip Schwarz
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Bryan O'Sullivan
 
A brief introduction to lisp language
A brief introduction to lisp languageA brief introduction to lisp language
A brief introduction to lisp languageDavid Gu
 
Scala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypeScala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypePhilip Schwarz
 
Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Bryan O'Sullivan
 
Real World Haskell: Lecture 4
Real World Haskell: Lecture 4Real World Haskell: Lecture 4
Real World Haskell: Lecture 4Bryan O'Sullivan
 
Advance LISP (Artificial Intelligence)
Advance LISP (Artificial Intelligence) Advance LISP (Artificial Intelligence)
Advance LISP (Artificial Intelligence) wahab khan
 
Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Bryan O'Sullivan
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
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 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
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
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Philip Schwarz
 
Left and Right Folds - Comparison of a mathematical definition and a programm...
Left and Right Folds- Comparison of a mathematical definition and a programm...Left and Right Folds- Comparison of a mathematical definition and a programm...
Left and Right Folds - Comparison of a mathematical definition and a programm...Philip Schwarz
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISPDevnology
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data scienceJohn Cant
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a MomentSergio Gil
 
INTRODUCTION TO LISP
INTRODUCTION TO LISPINTRODUCTION TO LISP
INTRODUCTION TO LISPNilt1234
 

What's hot (20)

Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 
Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2
 
Monads do not Compose
Monads do not ComposeMonads do not Compose
Monads do not Compose
 
A brief introduction to lisp language
A brief introduction to lisp languageA brief introduction to lisp language
A brief introduction to lisp language
 
Prolog & lisp
Prolog & lispProlog & lisp
Prolog & lisp
 
Scala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data TypeScala 3 enum for a terser Option Monad Algebraic Data Type
Scala 3 enum for a terser Option Monad Algebraic Data Type
 
Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Real World Haskell: Lecture 7
Real World Haskell: Lecture 7
 
Real World Haskell: Lecture 4
Real World Haskell: Lecture 4Real World Haskell: Lecture 4
Real World Haskell: Lecture 4
 
Advance LISP (Artificial Intelligence)
Advance LISP (Artificial Intelligence) Advance LISP (Artificial Intelligence)
Advance LISP (Artificial Intelligence)
 
Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Real World Haskell: Lecture 5
Real World Haskell: Lecture 5
 
Lisp
LispLisp
Lisp
 
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...N-Queens Combinatorial Problem - Polyglot FP for Fun and Profit – Haskell and...
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 ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
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
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 4
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...
Left and Right Folds- Comparison of a mathematical definition and a programm...Left and Right Folds- Comparison of a mathematical definition and a programm...
Left and Right Folds - Comparison of a mathematical definition and a programm...
 
Learn a language : LISP
Learn a language : LISPLearn a language : LISP
Learn a language : LISP
 
Haskell for data science
Haskell for data scienceHaskell for data science
Haskell for data science
 
Five Languages in a Moment
Five Languages in a MomentFive Languages in a Moment
Five Languages in a Moment
 
INTRODUCTION TO LISP
INTRODUCTION TO LISPINTRODUCTION TO LISP
INTRODUCTION TO LISP
 

Viewers also liked

Viewers also liked (12)

Passescd
PassescdPassescd
Passescd
 
Classification of Compilers
Classification of CompilersClassification of Compilers
Classification of Compilers
 
Introduction to Compiler Construction
Introduction to Compiler Construction Introduction to Compiler Construction
Introduction to Compiler Construction
 
Ch2
Ch2Ch2
Ch2
 
Compiler unit 1
Compiler unit 1Compiler unit 1
Compiler unit 1
 
Lecture 01 introduction to compiler
Lecture 01 introduction to compilerLecture 01 introduction to compiler
Lecture 01 introduction to compiler
 
Compiler Design Basics
Compiler Design BasicsCompiler Design Basics
Compiler Design Basics
 
Compiler Design(NANTHU NOTES)
Compiler Design(NANTHU NOTES)Compiler Design(NANTHU NOTES)
Compiler Design(NANTHU NOTES)
 
Phases of Compiler
Phases of CompilerPhases of Compiler
Phases of Compiler
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
What is Compiler?
What is Compiler?What is Compiler?
What is Compiler?
 
Compiler Chapter 1
Compiler Chapter 1Compiler Chapter 1
Compiler Chapter 1
 

Similar to Introduction to Functional Languages

Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsKirill Kozlov
 
Using Language Oriented Programming to Execute Computations on the GPU
Using Language Oriented Programming to Execute Computations on the GPUUsing Language Oriented Programming to Execute Computations on the GPU
Using Language Oriented Programming to Execute Computations on the GPUSkills Matter
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospectivechenge2k
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1Hang Zhao
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture TwoAngelo Corsaro
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and FuturePushkar Kulkarni
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present FutureIndicThreads
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
The Next Great Functional Programming Language
The Next Great Functional Programming LanguageThe Next Great Functional Programming Language
The Next Great Functional Programming LanguageJohn De Goes
 
Is there a perfect data-parallel programming language? (Experiments with More...
Is there a perfect data-parallel programming language? (Experiments with More...Is there a perfect data-parallel programming language? (Experiments with More...
Is there a perfect data-parallel programming language? (Experiments with More...Julian Hyde
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2Hang Zhao
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskellJongsoo Lee
 
Functional programming seminar (haskell)
Functional programming seminar (haskell)Functional programming seminar (haskell)
Functional programming seminar (haskell)Bikram Thapa
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersChris
 

Similar to Introduction to Functional Languages (20)

Frp2016 3
Frp2016 3Frp2016 3
Frp2016 3
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
 
Using Language Oriented Programming to Execute Computations on the GPU
Using Language Oriented Programming to Execute Computations on the GPUUsing Language Oriented Programming to Execute Computations on the GPU
Using Language Oriented Programming to Execute Computations on the GPU
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospective
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
haskell_fp1
haskell_fp1haskell_fp1
haskell_fp1
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
The Next Great Functional Programming Language
The Next Great Functional Programming LanguageThe Next Great Functional Programming Language
The Next Great Functional Programming Language
 
Special topics in finance lecture 2
Special topics in finance   lecture 2Special topics in finance   lecture 2
Special topics in finance lecture 2
 
Is there a perfect data-parallel programming language? (Experiments with More...
Is there a perfect data-parallel programming language? (Experiments with More...Is there a perfect data-parallel programming language? (Experiments with More...
Is there a perfect data-parallel programming language? (Experiments with More...
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
Functional programming seminar (haskell)
Functional programming seminar (haskell)Functional programming seminar (haskell)
Functional programming seminar (haskell)
 
Functional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative ProgrammersFunctional Programming Concepts for Imperative Programmers
Functional Programming Concepts for Imperative Programmers
 

More from suthi

Object Oriented Programming -- Dr Robert Harle
Object Oriented Programming -- Dr Robert HarleObject Oriented Programming -- Dr Robert Harle
Object Oriented Programming -- Dr Robert Harlesuthi
 
THE ROLE OF EDGE COMPUTING IN INTERNET OF THINGS
THE ROLE OF EDGE COMPUTING IN INTERNET OF THINGSTHE ROLE OF EDGE COMPUTING IN INTERNET OF THINGS
THE ROLE OF EDGE COMPUTING IN INTERNET OF THINGSsuthi
 
EDGE COMPUTING: VISION AND CHALLENGES
EDGE COMPUTING: VISION AND CHALLENGESEDGE COMPUTING: VISION AND CHALLENGES
EDGE COMPUTING: VISION AND CHALLENGESsuthi
 
Document Classification Using KNN with Fuzzy Bags of Word Representation
Document Classification Using KNN with Fuzzy Bags of Word RepresentationDocument Classification Using KNN with Fuzzy Bags of Word Representation
Document Classification Using KNN with Fuzzy Bags of Word Representationsuthi
 
AUTOMATA THEORY - SHORT NOTES
AUTOMATA THEORY - SHORT NOTESAUTOMATA THEORY - SHORT NOTES
AUTOMATA THEORY - SHORT NOTESsuthi
 
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTESOBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTESsuthi
 
PARALLEL ARCHITECTURE AND COMPUTING - SHORT NOTES
PARALLEL ARCHITECTURE AND COMPUTING - SHORT NOTESPARALLEL ARCHITECTURE AND COMPUTING - SHORT NOTES
PARALLEL ARCHITECTURE AND COMPUTING - SHORT NOTESsuthi
 
SOFTWARE QUALITY ASSURANCE AND TESTING - SHORT NOTES
SOFTWARE QUALITY ASSURANCE AND TESTING - SHORT NOTESSOFTWARE QUALITY ASSURANCE AND TESTING - SHORT NOTES
SOFTWARE QUALITY ASSURANCE AND TESTING - SHORT NOTESsuthi
 
COMPUTER HARDWARE - SHORT NOTES
COMPUTER HARDWARE - SHORT NOTESCOMPUTER HARDWARE - SHORT NOTES
COMPUTER HARDWARE - SHORT NOTESsuthi
 
DATA BASE MANAGEMENT SYSTEM - SHORT NOTES
DATA BASE MANAGEMENT SYSTEM - SHORT NOTESDATA BASE MANAGEMENT SYSTEM - SHORT NOTES
DATA BASE MANAGEMENT SYSTEM - SHORT NOTESsuthi
 
OPERATING SYSTEM - SHORT NOTES
OPERATING SYSTEM - SHORT NOTESOPERATING SYSTEM - SHORT NOTES
OPERATING SYSTEM - SHORT NOTESsuthi
 
SOFTWARE ENGINEERING & ARCHITECTURE - SHORT NOTES
SOFTWARE ENGINEERING & ARCHITECTURE - SHORT NOTESSOFTWARE ENGINEERING & ARCHITECTURE - SHORT NOTES
SOFTWARE ENGINEERING & ARCHITECTURE - SHORT NOTESsuthi
 
ALGORITHMS - SHORT NOTES
ALGORITHMS - SHORT NOTESALGORITHMS - SHORT NOTES
ALGORITHMS - SHORT NOTESsuthi
 
COMPUTER NETWORKS - SHORT NOTES
COMPUTER NETWORKS - SHORT NOTESCOMPUTER NETWORKS - SHORT NOTES
COMPUTER NETWORKS - SHORT NOTESsuthi
 
DATA STRUCTURES - SHORT NOTES
DATA STRUCTURES - SHORT NOTESDATA STRUCTURES - SHORT NOTES
DATA STRUCTURES - SHORT NOTESsuthi
 
ARTIFICIAL INTELLIGENCE - SHORT NOTES
ARTIFICIAL INTELLIGENCE - SHORT NOTESARTIFICIAL INTELLIGENCE - SHORT NOTES
ARTIFICIAL INTELLIGENCE - SHORT NOTESsuthi
 
LIGHT PEAK
LIGHT PEAKLIGHT PEAK
LIGHT PEAKsuthi
 
Action Recognition using Nonnegative Action
Action Recognition using Nonnegative ActionAction Recognition using Nonnegative Action
Action Recognition using Nonnegative Actionsuthi
 
C Programming Tutorial
C Programming TutorialC Programming Tutorial
C Programming Tutorialsuthi
 
Data structure - mcqs
Data structure - mcqsData structure - mcqs
Data structure - mcqssuthi
 

More from suthi (20)

Object Oriented Programming -- Dr Robert Harle
Object Oriented Programming -- Dr Robert HarleObject Oriented Programming -- Dr Robert Harle
Object Oriented Programming -- Dr Robert Harle
 
THE ROLE OF EDGE COMPUTING IN INTERNET OF THINGS
THE ROLE OF EDGE COMPUTING IN INTERNET OF THINGSTHE ROLE OF EDGE COMPUTING IN INTERNET OF THINGS
THE ROLE OF EDGE COMPUTING IN INTERNET OF THINGS
 
EDGE COMPUTING: VISION AND CHALLENGES
EDGE COMPUTING: VISION AND CHALLENGESEDGE COMPUTING: VISION AND CHALLENGES
EDGE COMPUTING: VISION AND CHALLENGES
 
Document Classification Using KNN with Fuzzy Bags of Word Representation
Document Classification Using KNN with Fuzzy Bags of Word RepresentationDocument Classification Using KNN with Fuzzy Bags of Word Representation
Document Classification Using KNN with Fuzzy Bags of Word Representation
 
AUTOMATA THEORY - SHORT NOTES
AUTOMATA THEORY - SHORT NOTESAUTOMATA THEORY - SHORT NOTES
AUTOMATA THEORY - SHORT NOTES
 
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTESOBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
OBJECT ORIENTED PROGRAMMING LANGUAGE - SHORT NOTES
 
PARALLEL ARCHITECTURE AND COMPUTING - SHORT NOTES
PARALLEL ARCHITECTURE AND COMPUTING - SHORT NOTESPARALLEL ARCHITECTURE AND COMPUTING - SHORT NOTES
PARALLEL ARCHITECTURE AND COMPUTING - SHORT NOTES
 
SOFTWARE QUALITY ASSURANCE AND TESTING - SHORT NOTES
SOFTWARE QUALITY ASSURANCE AND TESTING - SHORT NOTESSOFTWARE QUALITY ASSURANCE AND TESTING - SHORT NOTES
SOFTWARE QUALITY ASSURANCE AND TESTING - SHORT NOTES
 
COMPUTER HARDWARE - SHORT NOTES
COMPUTER HARDWARE - SHORT NOTESCOMPUTER HARDWARE - SHORT NOTES
COMPUTER HARDWARE - SHORT NOTES
 
DATA BASE MANAGEMENT SYSTEM - SHORT NOTES
DATA BASE MANAGEMENT SYSTEM - SHORT NOTESDATA BASE MANAGEMENT SYSTEM - SHORT NOTES
DATA BASE MANAGEMENT SYSTEM - SHORT NOTES
 
OPERATING SYSTEM - SHORT NOTES
OPERATING SYSTEM - SHORT NOTESOPERATING SYSTEM - SHORT NOTES
OPERATING SYSTEM - SHORT NOTES
 
SOFTWARE ENGINEERING & ARCHITECTURE - SHORT NOTES
SOFTWARE ENGINEERING & ARCHITECTURE - SHORT NOTESSOFTWARE ENGINEERING & ARCHITECTURE - SHORT NOTES
SOFTWARE ENGINEERING & ARCHITECTURE - SHORT NOTES
 
ALGORITHMS - SHORT NOTES
ALGORITHMS - SHORT NOTESALGORITHMS - SHORT NOTES
ALGORITHMS - SHORT NOTES
 
COMPUTER NETWORKS - SHORT NOTES
COMPUTER NETWORKS - SHORT NOTESCOMPUTER NETWORKS - SHORT NOTES
COMPUTER NETWORKS - SHORT NOTES
 
DATA STRUCTURES - SHORT NOTES
DATA STRUCTURES - SHORT NOTESDATA STRUCTURES - SHORT NOTES
DATA STRUCTURES - SHORT NOTES
 
ARTIFICIAL INTELLIGENCE - SHORT NOTES
ARTIFICIAL INTELLIGENCE - SHORT NOTESARTIFICIAL INTELLIGENCE - SHORT NOTES
ARTIFICIAL INTELLIGENCE - SHORT NOTES
 
LIGHT PEAK
LIGHT PEAKLIGHT PEAK
LIGHT PEAK
 
Action Recognition using Nonnegative Action
Action Recognition using Nonnegative ActionAction Recognition using Nonnegative Action
Action Recognition using Nonnegative Action
 
C Programming Tutorial
C Programming TutorialC Programming Tutorial
C Programming Tutorial
 
Data structure - mcqs
Data structure - mcqsData structure - mcqs
Data structure - mcqs
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 

Recently uploaded (20)

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 

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
  • 11.
  • 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.
  • 22.
  • 23.
  • 24.
  • 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