Functional Programming a (very) short introduction Ben Couste 06/10/2010
Functional Programming “ML, Lisp, and Haskell are the only programming languages that I've seen where one spends more time thinking than typing.” - Philip Greenspun
Outline What is Functional Programming (FP)? Why would I want to use it? Examples!
What is FP? Different paradigm Imperative programming (think C or Java) is about changes in the state of data Functional programming is about the application of functions Writing “pure” code
Barrier to entry Different programming paradigm “A monad is just a monoid in the category of endofunctors!” Mathematicians love FP Large and intimidating community (#haskell on irc.freenode.org) Generally very business-unfriendly
Purity Pure code has no side effects Easier to debug! Not always possible (I/O, mutable arrays)
Typing Write well-typed programs Program will not compile otherwise!
Recursion example Classic method in CS Heavily used in FP Each new term in the Fibonacci sequence is generated by adding the previous two terms. Find the sum of all the even-valued terms in the sequence which do not exceed four million. (project-euler.net)
Haskell Implementation Prelude> let fibs = 0 : 1 : zipWith (+) fibs (tail fibs) Prelude> sum [x | x <- (takeWhile (< ) fibs), even x]
Shifting functions around Functions can be passed as parameters! Code reuse anyone? Syntactic sugar Fun!
Further reading My handouts on the course website