Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Functional Programming

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.

Functional Programming

Avatar for Adrien Couque

Adrien Couque

May 22, 2014
Tweet

More Decks by Adrien Couque

Other Decks in Technology

Transcript

  1. Focus on Functional Programming 2014 • Here is the legend

    or source Imperative Programming Ordinateur = machine à états Chaque instruction modifie l’état Développeur écrit toutes les instructions à exécuter Variables représentent des zones mémoires dont le contenu peut changer Exemples : C, Objective-C, Java...
  2. Focus on Functional Programming 2014 • Functional Programming 2 règles

    seulement : • Pas d’effets de bord (les instructions ne peuvent pas modifier l’état) • Referential transparency (le résultat d’une méthode dépend uniquement des paramètres)
  3. 2014 • Fibonacci Impératif : int fibonacci(int n) { if

    (n <= 2) { return 1; } int a = 1; int b = 1; for (int i = 2; i < n; i++) { int c = a + b; a = b; b = c; } return b; } 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Fonctionnel : int fibonacci(int n) { if (n <= 2) { return 1; } return fibonacci(n, 1, 1); } int fibonacci(int n, int a, int b) { if (n == 2) { return b; } return fibonacci(n-1, b, a+b); } Focus on Functional Programming
  4. 2014 • Recursion > Boucles Difficile de faire une boucle

    sans modifier la mémoire (for interdit) Problème: Stack Overflow Solution: Tail Recursion Focus on Functional Programming
  5. 2014 • Tail recursion Focus on Functional Programming int fibonacci(int

    n) { if (n <= 2) { return 1; } return fibonacci(n, 1, 1); } int fibonacci(int n, int a, int b) { if (n == 2) { return b; } return fibonacci(n-1, b, a+b); } int fibonacci(int n) { if (n <= 2) { return 1; } return fibonacci(n-1) + fibonacci(n-2); }
  6. 2014 • Opérations de base: map, reduce/fold map square [1,2,3,4,5]

    => [1,4,9,16,25] reduce sum [1,2,3,4,5] => 15 foldr ( \x y -> concat ["(",x,"+",y,")"]) "0" (map show [1..10]) => (1+(2+(3+(4+(5+(6+(7+(8+(9+(10+0)))))))))) Focus on Functional Programming
  7. 2014 • Opérations de base: map, reduce/fold Fibonacci : fibs

    = 1 : 1 : [ a + b | (a, b) <- zip fibs (tail fibs)] take 15 fibs => [1,1,2,3,5,8,13,21,34,55] Focus on Functional Programming
  8. 2014 • Avantage n°1: Scope Une fonction est auto-suffisante =>

    Plus facile à lire, à comprendre => Plus facile à tester Focus on Functional Programming
  9. 2014 • Avantage n°2: Memoization Valeur de retour dépend uniquement

    des paramètres => même appel donne toujours les mêmes résultats => possibilité de stocker la valeur int fibonacci(int n) { if (n <= 2) { return 1; } return fibonacci(n-1) + fibonacci(n-2); } Focus on Functional Programming
  10. 2014 • Avantage n°3:  Persistent data structure Données immutables

    permettent d’optimiser l’utilisation de la mémoire zs = xs ++ ys Focus on Functional Programming
  11. 2014 • Avantage n°3:  Persistent data structure ys =

    insert(‘e’, xs) Focus on Functional Programming
  12. 2014 • Avantage n°4: Concurrency a et b ne dépendent

    que de x + pas d’effet de bord => a et b peuvent être évalués dans n’importe quel ordre Lazy evaluation a et b peuvent être exécutés dans n’importe quel ordre Focus on Functional Programming f(a(x), b(x)) a(x) b(x)
  13. 2014 • Problème: I/O Consistance : Pas de lecture de

    fichier, pas d’accès réseaux... Pas de random Pas d’effets de bord : Pas d’écriture dans un fichier, pas d’affichage à l’écran... Focus on Functional Programming
  14. 2014 • Problème: I/O 2 solutions : • Abandonner la

    consistance et autoriser les effets de bord => différence entre méthodes pures et impures • Monads Focus on Functional Programming
  15. 2014 • Lisp • Créé en 1958 • Typage dynamique

    • I/O: impure • Homoiconic • Plein de parenthèses ! Nombreuses déclinaisons: • Common Lisp • Clojure (-> JVM, JavaScript) • Scheme • Racket Focus on Functional Programming
  16. 2014 • Lisp (defparameter *animals* (list (make-animal :x (ash *width*

    -1) :y (ash *height* -1) :energy 1000 :dir 0 :genes (loop repeat 8 collecting (1+ (random 10)))))) (defun move (animal) (let ((dir (animal-dir animal)) (x (animal-x animal)) (y (animal-y animal))) (setf (animal-x animal) (mod (+ x (cond ((and (>= dir 2) (< dir 5)) 1) ((or (= dir 1) (= dir 5)) 0) (t -1)) *width*) *width*)) (setf (animal-y animal) (mod (+ y (cond ((and (>= dir 0) (< dir 3)) -1) ((and (>= dir 4) (< dir 7)) 1) (t 0)) *height*) *height*)) (decf (animal-energy animal)))) Focus on Functional Programming
  17. 2014 • Homoiconicity (function f (params x y) (block (var

    b 3) (if (< x (* a (+ b 7))) (while found (block (for i (range 2 5) (print i)) (if (== a 2) (break)))) (= p (cos 5))) (return (/ a 5)))) Focus on Functional Programming
  18. 2014 • Haskell • Créé en 1990 • Typage statique

    • I/O: monads • Lazy evaluation • Compilé (GHC) : performances équivalentes au C Focus on Functional Programming
  19. 2014 • Haskell import Data.Aeson import Control.Applicative import Data.ByteString.Lazy.Char8 hiding

    (empty) data MyData = MyData { text :: String, number :: Int } deriving Show instance ToJSON MyData where toJSON (MyData text number) = object ["text" .= text, "number" .= number] instance FromJSON MyData where parseJSON (Object v) = MyData <$> v .: "text" <*> v .: "number" parseJSON _ = empty myData = MyData "Hello" 123 main = do print myData print $ unpack $ encode myData print $ (decode "{ \"number\" : 123, \"text\" : \"Hello\" }" :: Maybe MyData) Focus on Functional Programming
  20. Paris, 22 Mai 2014 Applidium 17 rue du Faubourg du

    Temple 75010 Paris www.applidium.com Merci