110 likes | 131 Views
Understand pattern matching in functional programming to write efficient functions. Explore Fibonacci, Ackermann, repeated elements, and lists. Get ready to ace your exam with these key concepts.
E N D
But first... • Any questions about your homework assignment or the upcoming exam?
But second... • Let's talk about a certain error message...
Pattern matching • Pattern matching allows us to have different implementations for a function based on the values of the parameters • This can make functions a lot easier to write • Let's look at a few functions...
fib n • Computes the nth Fibonacci number • If you hit an infinite loop, Control-C should cancel it • You need to use parentheses to get things to parse how you want
ackermann m n • Computes the specified value of the Ackermann function • Be very careful with parentheses!
repeated a n • Returns a new list with 'n' copies of 'a' in it • repeated 10 5 [10, 10, 10, 10, 10] • repeated 'a' 4 "aaaa" (note single vs double quotes!)
myNulllst • Returns True if the list is empty • Returns False otherwise • Write this using pattern matching
Pattern matching and lists • Pattern matching can provide an easy way to work with lists • We already saw matching against [] for the empty list • We can match against a cons expression to separate head and tail • For example... • myHead, myTail, myLength • isEvenLength :: [a] -> Bool
mySumlst • Returns the sum of the elements in lst • mySum [3, 1, 4] 8
myDrop n lst • Return a list consisting of the elements of 'lst', minus the first n elements • Base case: if asked to drop zero, return lst • Recursive case: make a recursive call to myDrop with (n-1) as the first parameter and something else as the second