1 / 11

Mastering Pattern Matching in Functional Programming

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.

kum
Download Presentation

Mastering Pattern Matching in Functional Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Pattern matching

  2. But first... • Any questions about your homework assignment or the upcoming exam?

  3. But second... • Let's talk about a certain error message...

  4. 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...

  5. 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

  6. ackermann m n • Computes the specified value of the Ackermann function • Be very careful with parentheses!

  7. 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!)

  8. myNulllst • Returns True if the list is empty • Returns False otherwise • Write this using pattern matching

  9. 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

  10. mySumlst • Returns the sum of the elements in lst • mySum [3, 1, 4] 8

  11. 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

More Related