Functional Programming

Post on 11-May-2015

1.837 views 5 download

Transcript of Functional Programming

Functional Programming

Chris Eidhof Eelco Lempsink

Amsterdam.rb, October 27, 2008

(,) tupil

Functional programming in Ruby

(1..4).collect {|i| i*i }#=> [1, 4, 9, 16]

(1..10).inject {|sum, n| sum + n}#=> 55

Functional programming with Haskell

(1..4).collect {|i| i*i }

map (λi → i ∗ i) [1 . .4] -- [1,4,9,16]

(1..10).inject {|sum, n| sum + n}

foldr (λn sum→ sum + n) 0 [1 . .10] -- 55

What is Haskell?

Haskell is a

• strongly typed

• lazy

• purely functional

programming language

Everything is a function

• No “assignment”

• Referential transparancy

• Partial application, no parentheses needed

a = 5a = 6 -- Invalid!

squares xs = map (λx → x ∗ x) xs

Why should I learn Haskell?

• Functional Programming gives you a fresh way to look atproblems

• Even if you don’t use a functional language

• Python, Ruby, C# all use ideas from FP

• Google’s Map/Reduce and Hadoop are large scale FP

Lists

data [a ] = [ ]| a : [a ]

Some standard functions

sum [ ] = 0sum (x : xs) = x + sum xs

product [ ] = 1product (x : xs) = x ∗ product xs

and [ ] = Trueand (x : xs) = x ∧ and xs

Everything is a fold!

foldr (⊕) e [ ] = efoldr (⊕) e (x : xs) = x ⊕ (foldr (⊕) e xs)

sum = foldr ( + ) 0product = foldr ( ∗ ) 1and = foldr ( ∧ ) True

Even map!

map f = foldr (λx tail → (f x) : tail) [ ]

Infinite lists...

primes = sieve [2 . . ]sieve (p : xs) = p : sieve [x | x ← xs

, x ‘mod ‘ p 6≡ 0]

QuickSort

qsort [ ] = [ ]qsort (x : xs) = qsort (filter (<x) xs)

++ [x ]++ qsort (filter (> x) xs)

What we didn’t tell you

• Function composition

• Types

• Purity and I/O

• Monads

• Foreign Function Interface

• . . .

Haskell in the Real World

• Large applications (XMonad, Darcs, GHC, Yi)

• Lots of libraries (Today on hackage: 814 libraries andprograms)

• Used by large companies (Credit Suisse, Galois, Microsoft,ABN Amro . . . )

• Lots of ways to learn Haskell ((free) textbooks, universitycourses, haskell wiki, blogs)

Functional programming

• ... sharpens your brain

• ... is lots of fun

• ... can help you become a better programmer

More information

• http://haskell.org

• http://hackage.haskell.org

• http://book.realworldhaskell.org/

• http://tupil.com