Programmation Fonctionnelle

Polytech Paris Saclay
2024-2025

Adrien Durier

OCaml

II. Types - Partie 2

II. Types - Partie 2

OCaml

Types Simples

(suite)

Types Simples - Rappel

let z = 4 + 1 - 2 * 2
let x = 4.3e4 +. 1.2 *. -2.3
let x = false || true
let x = 3 <= 1
let x = not (0=2) && 1 >= 3
let x = if 2 < 0 then 2.0 else (4.6 *. 1.2)
  • Les int
  • Les float
  • Les bool

Types Simples

let z = 'a'
let x = "hello"
  • Les char
  • Les string

Types Simples - strings

let z = 'a'
  • Les char

On a les fonctions int_of_char et char_of_int:

# int_of_char 'a' ;;
- : int = 97
# char_of_int 100 ;;
- : char = 'd'

/!\ L'apostrophe ' indique un caractère

Le double apostrophe " une chaîne de caractères

Code ASCII

Types Simples

let z = 'a'
let x = "hello"
  • Les char
  • Les string

Types Simples

let x = "hello"
  • Les string
  • L'opérateur ^ concatène les chaînes 
  • .[i] accède au caractère i (commence à 0)
# "" ;;
- : string = ""
# "hello".[1] ;;
- : char = 'e'
# string_of_int 123 ;;
- : string = "123"

Types Simples

  • Printf est de type unit
  • unit sert pour les fonctions qui n'ont que des effets de bord:
    • Sinon ils n'auraient pas de type !
    • Un peu comme void
  • Une seule valeur de type unit, notée ()
  • Donc toutes les valeurs de type unit sont égales !!!
# () ;;
- : unit = ()
# Print.printf "bonjour\n" ;;
bonjour
- : unit = ()

Types Simples

  • (1,2) est de type int * int
  • (1,"WTF") est de type int * string
let u = (1, 2)
let uu = (1,"AAAAAAAAAh")
let f (x, y, z) w = if x + y < 0 then w^"NON" else z
let fst x = let (w,z) = x in w
let snd x = let (w,z) = x in w

Types Simples

  • (1,2) est de type int * int
  • (1,"WTF") est de type int * string
  • Quel est le type de f, fst, snd ?
let f (x, y, z) w = if x + y < 0 then w^"NON" else z
let fst x = let (w,z) = x in w
let snd x = let (w,z) = x in w

Types Simples

  • (1,2) est de type int * int
  • (1,"WTF") est de type int * string
  • Quel est le type de f, fst, snd ?
let f (x, y, z) w = if x + y < 0 then w^"NON" else z
let fst x = let (w,z) = x in w
let snd x = let (w,z) = x in z

Réponse:

  • f:(int * int * string) -> string -> string
  • fst est de type ('a * 'b) -> 'a
  • snd est de type ('a * 'b) -> 'b