ln012 - Patterns The Essence of Functional Programming Up...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
Patterns The Essence of Functional Programming Up to now we have defined functions in a very traditional way: function name + variable name parameters In functional programming we can exploit the structure of objects during a function definition by using patterns and pattern matching . Example: no pattern matching, factorial - fun fact(x) = if x = 0 then 1 else x*fact(x-1); x! 1 if x = 0 x*(x-1)! otherwise Example : with pattern matching, factorial - fun fact 0 = 1 | fact n = n * fact(n-1); Very simple pattern: either it is 0 or not. Read Chap 7
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Patterns In order to use patterns we need to extend our ML syntax for function definitions: <fun-def> ::= fun <fun-bodies> <fun-bodies> ::= <fun-body> | <fun-body> | <fun-bodies> <fun-body> ::= <fun-name> <pattern> = <expression> <pattern> ::= any function and operator free expression (constructors are allowed). Valid Patterns: 1 (a,b) [2,3] q::rest Invalid Patterns : 1+a f(q)
Background image of page 2
Patterns Example : Pattern matching on lists. Write a function sumlist that accepts a list of integer values and returns the sum of the integers on the list. - fun sumlist ([ ]) = 0 | sumlist(x :: xs) = x + sumlist(xs);
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Example : write a function that reverses a given list. - fun reverse ([ ]) = [ ]
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 10/03/2011 for the course CSC 301 taught by Professor Hamel during the Spring '08 term at Rhode Island.

Page1 / 17

ln012 - Patterns The Essence of Functional Programming Up...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online