SlideShare une entreprise Scribd logo
1  sur  21
Télécharger pour lire hors ligne
La programmation fonctionnelle
Orleans Tech - Stéphane Legrand - 26 avril 2016
Le langage OCaml ocaml.org try.ocamlpro.com
● INRIA (Institut National de Recherche en Informatique et en Automatique)
● Première version en 1996
● Communauté restreinte mais active
● Compilé : natif, bytecode et Javascript
● Fortement typé
● Fonctionnel mais aussi impératif et objet
Les bases
● Définition d’une variable
let toto = 42
● Définition d’une fonction
let add x y = x + y
● Appel d’une fonction
let seven = add 4 3
Immutabilité : variables non modifiables
let x = 10
let f y = x + y
let x = 20
f 100 renvoie 110, et non pas 120
● Ligne 3 : on a construit un nouveau x
● Ce second x “cache” le premier
Immutabilité : listes non modifiables
let l = [1; 2; 3] liste d’entiers
aucun moyen de modifier directement un élément de l
let l = 4 :: l [4; 1; 2; 3]
let l = l @ [4; 5] [4; 1; 2; 3; 4; 5]
● A chaque fois, on construit une nouvelle liste
● Les listes l ne sont pas modifiées, elles sont juste “cachées”
Immutabilité : enregistrements non modifiables
type t = { name : string ; age : int }
let person = { name = “titi” ; age = 42 }
let older = { person with age = person.age * 2 }
● Nouvel enregistrement older à partir de person
● L’enregistrement person n’est pas modifié
Récursivité
let rec suml acc = function
[] -> acc
| e :: tail -> suml (acc + e) tail
suml 0 [1; 2; 3]
1. suml (0 + 1) [2; 3]
2. suml (1 + 2) [3]
3. suml (3 + 3) [] renvoie acc = 6
● Pas de boucle for ni de while
Composition de fonctions les bases
● Fonction en paramètre
let f g x = (g x) + (g 10)
● Fonction qui retourne une fonction
let add10 x = x + 10
ou let add10 = fun x -> x + 10
ou let add x y = x + y
let add10 = add 10 application partielle
Composition de fonctions filter et map
let l = [1; 2; 3; 4]
let even v =
v mod 2 = 0 vrai si v est pair, faux sinon
List.filter even l renvoie liste des nb pairs = [2; 4]
List.map (fun e -> e + 10) l renvoie [11; 12; 13; 14]
Composition de fonctions fold_left
List.fold_left (fun acc e -> acc + e) 0 [1; 2; 3]
(fun acc e -> acc + e) fonction appliquée
0 valeur initiale acc(umulateur)
[1; 2; 3] liste utilisée
⇔ f (f (f 0 1) 2) 3 = ((0 + 1) + 2) + 3 = 6
Composition de fonctions opérateur |>
let l = [1; 2; 3; 4]
let x = List.filter even l liste nb pairs = [2; 4]
List.map (fun e -> e * 2) x nombres * 2 = [4; 8]
⇔ List.filter even l liste nb pairs = [2; 4]
|> List.map (fun e -> e * 2) nombres * 2 = [4; 8]
x |> f ⇔ f x
x |> f |> g ⇔ g (f x)
Typage
let x = 10 + "99" Error: This expression has type
string but an expression was
expected of type int
let l = [1; "x"] Error: This expression has type
string but an expression was
expected of type int
let f v =
if v then
(fun x y -> x + y)
else (fun x -> x + 1)
Error: This expression has type int
but an expression was expected of
type int -> int
Typage
Printf.printf "v = %s" 10 Error: This expression has type int
but an expression was expected of
type string
let c = cm 1.0
let k = km 50.0
let total = c + k
Error: This expression has type
[ `Km ] Measure.t
but an expression was expected of
type [ `Cm ] Measure.t
...
Exemple
type data = {
id : string ; identifiant client
discount : float -> float fct calcule un rabais
}
type customer =
| Individual of data
| Company of data
Exemple
let c1 = Individual {
id = “toto”;
discount = fun v -> v *. 0.05
}
let c2 = Company {
id = “google”;
discount = fun v -> v *. 0.15
}
Exemple
let l = [(c1, 60.25); (c2, 100.00)] (client, somme)
let f (c, sum) = match c with
| Individual d ->
if d.id = “toto” then (c, sum *. 2.) $$$
else (c, sum -. d.discount sum)
| Company d -> (c, sum -. d.discount sum)
List.map f l [(c1, 120.5); (c2, 85)]
Plein d’autres choses encore...
● Modules
○ paramétrés par d’autres modules
○ manipulables comme des valeurs
■ en paramètres d’une fonction
■ renvoyés par une fonction
● Interfaces
● Types génériques
● Gestion des packages
● ...
Pour le web
● Projet Ocsigen : ocsigen.org
applications web côté serveur et client
démos : github.com/slegrand45/examples_ocsigen
● Webmachine : github.com/inhabitedtype/ocaml-webmachine
API REST
● Elm : elm-lang.org
langage fonctionnel dédié côté client
Style de programmation
● Peut essayer en Javascript par exemple, avec complément
○ Immutable.js : facebook.github.io/immutable-js/
● Mais demande de la discipline !
● Avec un langage dédié
○ plus facile
○ plus optimisé
○ difficile, voire impossible de “tricher”
En résumé
● Fonctions, fonctions, fonctions et… fonctions
● On gère des valeurs et non pas des états
● Programmation par types
● Pas plus difficile, juste différent
Merci
Questions ?

Contenu connexe

Tendances

Natural Language Processing
Natural Language ProcessingNatural Language Processing
Natural Language Processing
Yasir Khan
 

Tendances (20)

PHP Tutorials
PHP TutorialsPHP Tutorials
PHP Tutorials
 
Text classification with fast text elena_meetup_milano_27_june
Text classification with fast text elena_meetup_milano_27_juneText classification with fast text elena_meetup_milano_27_june
Text classification with fast text elena_meetup_milano_27_june
 
Natural language processing (NLP) introduction
Natural language processing (NLP) introductionNatural language processing (NLP) introduction
Natural language processing (NLP) introduction
 
Word2 vec
Word2 vecWord2 vec
Word2 vec
 
rnn BASICS
rnn BASICSrnn BASICS
rnn BASICS
 
Keras and TensorFlow
Keras and TensorFlowKeras and TensorFlow
Keras and TensorFlow
 
Word embedding
Word embedding Word embedding
Word embedding
 
Explainable AI
Explainable AIExplainable AI
Explainable AI
 
Text summarization using deep learning
Text summarization using deep learningText summarization using deep learning
Text summarization using deep learning
 
Natural Language Processing
Natural Language ProcessingNatural Language Processing
Natural Language Processing
 
Modelling and evaluation
Modelling and evaluationModelling and evaluation
Modelling and evaluation
 
Important Classification and Regression Metrics.pptx
Important Classification and Regression Metrics.pptxImportant Classification and Regression Metrics.pptx
Important Classification and Regression Metrics.pptx
 
Machine Learning Landscape
Machine Learning LandscapeMachine Learning Landscape
Machine Learning Landscape
 
Natural lanaguage processing
Natural lanaguage processingNatural lanaguage processing
Natural lanaguage processing
 
Text similarity measures
Text similarity measuresText similarity measures
Text similarity measures
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
NLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language ModelNLP_KASHK:Evaluating Language Model
NLP_KASHK:Evaluating Language Model
 
Extraction Based automatic summarization
Extraction Based automatic summarizationExtraction Based automatic summarization
Extraction Based automatic summarization
 
Introduction to Autoencoders
Introduction to AutoencodersIntroduction to Autoencoders
Introduction to Autoencoders
 
Exception handling
Exception handlingException handling
Exception handling
 

En vedette

Les langages de programmation sont trop compliqués
Les langages de programmation sont trop compliquésLes langages de programmation sont trop compliqués
Les langages de programmation sont trop compliqués
mercury_wood
 

En vedette (6)

L'avenir de Java : Erlang, Haskell ou Ruby
L'avenir de Java : Erlang, Haskell ou RubyL'avenir de Java : Erlang, Haskell ou Ruby
L'avenir de Java : Erlang, Haskell ou Ruby
 
Initiation aux langages informatiques (1)
Initiation aux langages informatiques (1)Initiation aux langages informatiques (1)
Initiation aux langages informatiques (1)
 
Programmation Fonctionnelle
Programmation FonctionnelleProgrammation Fonctionnelle
Programmation Fonctionnelle
 
Les langages de programmation sont trop compliqués
Les langages de programmation sont trop compliquésLes langages de programmation sont trop compliqués
Les langages de programmation sont trop compliqués
 
Les langages de programmation
Les langages de programmationLes langages de programmation
Les langages de programmation
 
Programmation fonctionnelle
Programmation fonctionnelleProgrammation fonctionnelle
Programmation fonctionnelle
 

Similaire à La programmation fonctionnelle avec le langage OCaml

Ch8 correction exercices (1)
Ch8 correction exercices (1)Ch8 correction exercices (1)
Ch8 correction exercices (1)
abdellah12
 
Mat lab1
Mat lab1Mat lab1
Mat lab1
fouadDD
 

Similaire à La programmation fonctionnelle avec le langage OCaml (20)

Développement informatique : Programmation fonctionnelle, décorateur et génér...
Développement informatique : Programmation fonctionnelle, décorateur et génér...Développement informatique : Programmation fonctionnelle, décorateur et génér...
Développement informatique : Programmation fonctionnelle, décorateur et génér...
 
Ch8 correction exercices (1)
Ch8 correction exercices (1)Ch8 correction exercices (1)
Ch8 correction exercices (1)
 
Scala : programmation fonctionnelle
Scala : programmation fonctionnelleScala : programmation fonctionnelle
Scala : programmation fonctionnelle
 
Support programmation orientée objet c# .net version f8
Support programmation orientée objet c#  .net version f8Support programmation orientée objet c#  .net version f8
Support programmation orientée objet c# .net version f8
 
Theme 7
Theme 7Theme 7
Theme 7
 
Cours de Matlab
Cours de MatlabCours de Matlab
Cours de Matlab
 
Mat lab1
Mat lab1Mat lab1
Mat lab1
 
Python avancé : Ensemble, dictionnaire et base de données
Python avancé : Ensemble, dictionnaire et base de donnéesPython avancé : Ensemble, dictionnaire et base de données
Python avancé : Ensemble, dictionnaire et base de données
 
Cours de C++, en français, 2002 - Cours 2.1
Cours de C++, en français, 2002 - Cours 2.1Cours de C++, en français, 2002 - Cours 2.1
Cours de C++, en français, 2002 - Cours 2.1
 
cours python Chapitre 3- Les types de base.pptx
cours python Chapitre 3- Les types de base.pptxcours python Chapitre 3- Les types de base.pptx
cours python Chapitre 3- Les types de base.pptx
 
C++ 11/14
C++ 11/14C++ 11/14
C++ 11/14
 
Cours de C++ / Tronc commun deuxième année ISIMA
Cours de C++ / Tronc commun deuxième année ISIMACours de C++ / Tronc commun deuxième année ISIMA
Cours de C++ / Tronc commun deuxième année ISIMA
 
C++11
C++11C++11
C++11
 
C++11 en 12 exemples simples
C++11 en 12 exemples simplesC++11 en 12 exemples simples
C++11 en 12 exemples simples
 
Initiation r
Initiation rInitiation r
Initiation r
 
FormationPython2019.pptx
FormationPython2019.pptxFormationPython2019.pptx
FormationPython2019.pptx
 
C4 fonctions
C4 fonctionsC4 fonctions
C4 fonctions
 
COURS_PYTHON_22.ppt
COURS_PYTHON_22.pptCOURS_PYTHON_22.ppt
COURS_PYTHON_22.ppt
 
Chap 1 Initiation.pptx
Chap 1 Initiation.pptxChap 1 Initiation.pptx
Chap 1 Initiation.pptx
 
Presentation Csharp et winforms
Presentation Csharp et winformsPresentation Csharp et winforms
Presentation Csharp et winforms
 

Plus de Stéphane Legrand (7)

L’environnement de programmation fonctionnelle DrRacket
L’environnement de programmation fonctionnelle DrRacketL’environnement de programmation fonctionnelle DrRacket
L’environnement de programmation fonctionnelle DrRacket
 
Les modèles économiques du logiciel libre
Les modèles économiques du logiciel libreLes modèles économiques du logiciel libre
Les modèles économiques du logiciel libre
 
Linux et les systèmes embarqués
Linux et les systèmes embarquésLinux et les systèmes embarqués
Linux et les systèmes embarqués
 
Résolution de problèmes de classification par algorithmes évolutionnaires grâ...
Résolution de problèmes de classification par algorithmes évolutionnaires grâ...Résolution de problèmes de classification par algorithmes évolutionnaires grâ...
Résolution de problèmes de classification par algorithmes évolutionnaires grâ...
 
ZFS et BTRFS
ZFS et BTRFSZFS et BTRFS
ZFS et BTRFS
 
Les algorithmes évolutionnistes
Les algorithmes évolutionnistesLes algorithmes évolutionnistes
Les algorithmes évolutionnistes
 
Presentation langage go_19022015
Presentation langage go_19022015Presentation langage go_19022015
Presentation langage go_19022015
 

La programmation fonctionnelle avec le langage OCaml

  • 1. La programmation fonctionnelle Orleans Tech - Stéphane Legrand - 26 avril 2016
  • 2. Le langage OCaml ocaml.org try.ocamlpro.com ● INRIA (Institut National de Recherche en Informatique et en Automatique) ● Première version en 1996 ● Communauté restreinte mais active ● Compilé : natif, bytecode et Javascript ● Fortement typé ● Fonctionnel mais aussi impératif et objet
  • 3. Les bases ● Définition d’une variable let toto = 42 ● Définition d’une fonction let add x y = x + y ● Appel d’une fonction let seven = add 4 3
  • 4. Immutabilité : variables non modifiables let x = 10 let f y = x + y let x = 20 f 100 renvoie 110, et non pas 120 ● Ligne 3 : on a construit un nouveau x ● Ce second x “cache” le premier
  • 5. Immutabilité : listes non modifiables let l = [1; 2; 3] liste d’entiers aucun moyen de modifier directement un élément de l let l = 4 :: l [4; 1; 2; 3] let l = l @ [4; 5] [4; 1; 2; 3; 4; 5] ● A chaque fois, on construit une nouvelle liste ● Les listes l ne sont pas modifiées, elles sont juste “cachées”
  • 6. Immutabilité : enregistrements non modifiables type t = { name : string ; age : int } let person = { name = “titi” ; age = 42 } let older = { person with age = person.age * 2 } ● Nouvel enregistrement older à partir de person ● L’enregistrement person n’est pas modifié
  • 7. Récursivité let rec suml acc = function [] -> acc | e :: tail -> suml (acc + e) tail suml 0 [1; 2; 3] 1. suml (0 + 1) [2; 3] 2. suml (1 + 2) [3] 3. suml (3 + 3) [] renvoie acc = 6 ● Pas de boucle for ni de while
  • 8. Composition de fonctions les bases ● Fonction en paramètre let f g x = (g x) + (g 10) ● Fonction qui retourne une fonction let add10 x = x + 10 ou let add10 = fun x -> x + 10 ou let add x y = x + y let add10 = add 10 application partielle
  • 9. Composition de fonctions filter et map let l = [1; 2; 3; 4] let even v = v mod 2 = 0 vrai si v est pair, faux sinon List.filter even l renvoie liste des nb pairs = [2; 4] List.map (fun e -> e + 10) l renvoie [11; 12; 13; 14]
  • 10. Composition de fonctions fold_left List.fold_left (fun acc e -> acc + e) 0 [1; 2; 3] (fun acc e -> acc + e) fonction appliquée 0 valeur initiale acc(umulateur) [1; 2; 3] liste utilisée ⇔ f (f (f 0 1) 2) 3 = ((0 + 1) + 2) + 3 = 6
  • 11. Composition de fonctions opérateur |> let l = [1; 2; 3; 4] let x = List.filter even l liste nb pairs = [2; 4] List.map (fun e -> e * 2) x nombres * 2 = [4; 8] ⇔ List.filter even l liste nb pairs = [2; 4] |> List.map (fun e -> e * 2) nombres * 2 = [4; 8] x |> f ⇔ f x x |> f |> g ⇔ g (f x)
  • 12. Typage let x = 10 + "99" Error: This expression has type string but an expression was expected of type int let l = [1; "x"] Error: This expression has type string but an expression was expected of type int let f v = if v then (fun x y -> x + y) else (fun x -> x + 1) Error: This expression has type int but an expression was expected of type int -> int
  • 13. Typage Printf.printf "v = %s" 10 Error: This expression has type int but an expression was expected of type string let c = cm 1.0 let k = km 50.0 let total = c + k Error: This expression has type [ `Km ] Measure.t but an expression was expected of type [ `Cm ] Measure.t ...
  • 14. Exemple type data = { id : string ; identifiant client discount : float -> float fct calcule un rabais } type customer = | Individual of data | Company of data
  • 15. Exemple let c1 = Individual { id = “toto”; discount = fun v -> v *. 0.05 } let c2 = Company { id = “google”; discount = fun v -> v *. 0.15 }
  • 16. Exemple let l = [(c1, 60.25); (c2, 100.00)] (client, somme) let f (c, sum) = match c with | Individual d -> if d.id = “toto” then (c, sum *. 2.) $$$ else (c, sum -. d.discount sum) | Company d -> (c, sum -. d.discount sum) List.map f l [(c1, 120.5); (c2, 85)]
  • 17. Plein d’autres choses encore... ● Modules ○ paramétrés par d’autres modules ○ manipulables comme des valeurs ■ en paramètres d’une fonction ■ renvoyés par une fonction ● Interfaces ● Types génériques ● Gestion des packages ● ...
  • 18. Pour le web ● Projet Ocsigen : ocsigen.org applications web côté serveur et client démos : github.com/slegrand45/examples_ocsigen ● Webmachine : github.com/inhabitedtype/ocaml-webmachine API REST ● Elm : elm-lang.org langage fonctionnel dédié côté client
  • 19. Style de programmation ● Peut essayer en Javascript par exemple, avec complément ○ Immutable.js : facebook.github.io/immutable-js/ ● Mais demande de la discipline ! ● Avec un langage dédié ○ plus facile ○ plus optimisé ○ difficile, voire impossible de “tricher”
  • 20. En résumé ● Fonctions, fonctions, fonctions et… fonctions ● On gère des valeurs et non pas des états ● Programmation par types ● Pas plus difficile, juste différent