gc16/3011 functional programming lecture 5 miranda
DESCRIPTION
GC16/3011 Functional Programming Lecture 5 Miranda. patterns, functions, recursion and lists. Contents. Offside rule / where blocks / evaluation Partial / polymorphic functions Patterns and pattern-matching Recursive functions Lists Functions using lists Recursive functions using lists. - PowerPoint PPT PresentationTRANSCRIPT
04/20/2304/20/23 11
GC16/3011 Functional ProgrammingLecture 5
Mirandapatterns, functions, recursion and listspatterns, functions, recursion and lists
04/20/2304/20/23 22
Contents
Offside rule / where blocks / evaluationOffside rule / where blocks / evaluation Partial / polymorphic functionsPartial / polymorphic functions Patterns and pattern-matchingPatterns and pattern-matching Recursive functionsRecursive functions ListsLists
Functions using listsFunctions using lists Recursive functions using listsRecursive functions using lists
04/20/2304/20/23 33
Functions
The offside rule and “where” blocksThe offside rule and “where” blocks
Mapping from source to target type domainsMapping from source to target type domains
Application associates to the left!Application associates to the left!
Function evaluationFunction evaluation normal order, lazynormal order, lazy main = fst (34, (23 / 0) )main = fst (34, (23 / 0) )
04/20/2304/20/23 44
Functions
Partial functionsPartial functions those which have no result (i.e. return an error) for those which have no result (i.e. return an error) for
some valid values of valid input typesome valid values of valid input type f (x,y) = x / yf (x,y) = x / y
Polymorphic functionsPolymorphic functions fst, sndfst, snd g (x,y) = (-y, x)g (x,y) = (-y, x) three x = 3three x = 3
04/20/2304/20/23 55
Patterns
Tuple patternsTuple patterns (x,y,z) = (3, “hello”, (34,True,[3]))(x,y,z) = (3, “hello”, (34,True,[3]))
as a testas a test as a definitionas a definition
Patterns for function definitionsPatterns for function definitionsnot True = Falsenot True = Falsenot False = Truenot False = True
Top-down evaluation semanticsTop-down evaluation semanticsf 3 = 45f 3 = 45f 489 = 3f 489 = 3f any = 345*219f any = 345*219
04/20/2304/20/23 66
Patterns
Non-exhaustive patternsNon-exhaustive patternsf True = Falsef True = False
Patterns can destroy lazinessPatterns can destroy lazinessfst (x,0) = xfst (x,0) = xfst (x,y) = xfst (x,y) = x
Can a pattern contain a redex?Can a pattern contain a redex? No! A pattern must be a constant expressionNo! A pattern must be a constant expression (special exception – “(n + 1)” in Miranda)(special exception – “(n + 1)” in Miranda)
Duplicate parameter names (Miranda only)Duplicate parameter names (Miranda only)
04/20/2304/20/23 77
Recursive Functions
Recursion is the ONLY way to program loops in a Recursion is the ONLY way to program loops in a functional languagefunctional language Function calls itself inside its own bodyFunction calls itself inside its own body
Very powerful – very flexibleVery powerful – very flexible
In imperative languages, can be slow In imperative languages, can be slow
In functional languages, highly optimisedIn functional languages, highly optimised
04/20/2304/20/23 88
Recursive Functions
Beware:Beware:loop_forever x = loop_forever xloop_forever x = loop_forever x
Must have:Must have: Terminating conditionTerminating condition Changing argumentChanging argument ……that converges on the terminating condition!that converges on the terminating condition!
f :: num -> [char]f :: num -> [char]f 0 = “”f 0 = “”f n = “X” ++ (f (n – 1))f n = “X” ++ (f (n – 1))
04/20/2304/20/23 99
Recursive Functions
Stack recursion Stack recursion f 3f 3 “ “X” ++ (f (3 – 1))X” ++ (f (3 – 1)) “ “X” ++ (f 2)X” ++ (f 2) “ “X” ++ (“X” ++ (f (2-1)))X” ++ (“X” ++ (f (2-1))) “ “X” ++ (“X” ++ (f 1))X” ++ (“X” ++ (f 1)) “ “X” ++ (“X” ++ (“X” ++ (f (1-1))))X” ++ (“X” ++ (“X” ++ (f (1-1)))) “ “X” ++ (“X” ++ (“X” ++ “”))X” ++ (“X” ++ (“X” ++ “”)) “ “X” ++ (“X” ++ “X”)X” ++ (“X” ++ “X”) “ “X” ++ “XX”X” ++ “XX” “ “XXX”XXX”
04/20/2304/20/23 1010
Recursive Functions
Accumulative recursion Accumulative recursion plus :: (num, num) -> numplus :: (num, num) -> num
plus (x, 0) = xplus (x, 0) = x
plus (x, y) = plus (x+1, y-1)plus (x, y) = plus (x+1, y-1)
04/20/2304/20/23 1111
Type Synonyms
f :: (([char],num,[char]),(num,num,num)) -> boolf :: (([char],num,[char]),(num,num,num)) -> bool
str = = [char]str = = [char] coord = = (num, num, num)coord = = (num, num, num)
f :: ((str,num,str), coord) -> boolf :: ((str,num,str), coord) -> bool
04/20/2304/20/23 1212
LISTS
Lists are another way to collect together Lists are another way to collect together related datarelated data
But lists are special - they are RECURSIVEBut lists are special - they are RECURSIVE Data can be recursive, just like functions!Data can be recursive, just like functions!
04/20/2304/20/23 1313
LISTS
A list of type A list of type is either: is either: Empty, orEmpty, or An element of type An element of type together with a list of together with a list of
elements of the same typeelements of the same type List of num:List of num:
[][] (34: []) [34](34: []) [34] (34: (13: [])) [34, 13](34: (13: [])) [34, 13]
04/20/2304/20/23 1414
Functions using lists
bothempty :: ([*],[**]) -> boolbothempty :: ([*],[**]) -> bool
bothempty ([], []) = Truebothempty ([], []) = True
bothempty anything = Falsebothempty anything = False
myhd :: [*] -> *myhd :: [*] -> *
myhd [] = error “take head of empty list”myhd [] = error “take head of empty list”
myhd (x : rest) = xmyhd (x : rest) = x
04/20/2304/20/23 1515
Recursive functions using lists
sumlist :: [num] -> numsumlist :: [num] -> num
sumlist [] = 0sumlist [] = 0
sumlist (x : rest) = x + (sumlist rest)sumlist (x : rest) = x + (sumlist rest)
length :: [*] -> numlength :: [*] -> num
length [] = 0length [] = 0
length (x : rest) = 1 + (length rest)length (x : rest) = 1 + (length rest)
04/20/2304/20/23 1616
Exercise
Can you write a function “threes” which Can you write a function “threes” which takes as input a list of whole numbers and takes as input a list of whole numbers and produces as output a count of how many 3s produces as output a count of how many 3s occur in the input?occur in the input?
04/20/2304/20/23 1717
Summary
Offside rule / where blocks / evaluationOffside rule / where blocks / evaluation Partial / polymorphic functionsPartial / polymorphic functions Patterns and pattern-matchingPatterns and pattern-matching Recursive functionsRecursive functions ListsLists
Functions using listsFunctions using lists Recursive functions using listsRecursive functions using lists