Functional Programming

download Functional Programming

of 16

  • date post

    11-May-2015
  • Category

    Technology

  • view

    1.834
  • download

    5

Embed Size (px)

Transcript of Functional Programming

  • 1.Functional Programming Chris EidhofEelco Lempsink Amsterdam.rb, October 27, 2008 ( tp, ui ) l

2. Functional programming in Ruby (1..4).collect {|i| i*i }#=> [1, 4, 9, 16](1..10).inject {|sum, n| sum + n}#=> 55 3. 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 4. What is Haskell? Haskell is a strongly typed lazy purely functional programming language 5. Everything is a function No assignment Referential transparancy Partial application, no parentheses needed a=5 a=6 -- Invalid!squares xs = map (x x x) xs 6. Why should I learn Haskell? Functional Programming gives you a fresh way to look at problems Even if you dont use a functional language Python, Ruby, C# all use ideas from FP Googles Map/Reduce and Hadoop are large scale FP 7. Lists data [a] = [ ]| a : [a] 8. Some standard functionssum [ ]=0 sum (x : xs) = x + sum xs product [ ]=1 product (x : xs) = x product xs and [ ]= True and (x : xs) = x and xs 9. Everything is a fold! foldr () e [ ]=e foldr () e (x : xs) = x (foldr () e xs)sum = foldr ( + ) 0 product = foldr ( ) 1 and = foldr ( ) True 10. Even map! map f = foldr (x tail (f x) : tail) [ ] 11. Innite lists... primes = sieve [2 . . ] sieve (p : xs) = p : sieve [x | x xs , x mod p 0] 12. QuickSort qsort [ ]= [] qsort (x : xs) = qsort (lter (