11.07.2015 Views

Programmation fonctionnelle (Haskell)

Programmation fonctionnelle (Haskell)

Programmation fonctionnelle (Haskell)

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

La fonction zip prend 2 lists et retourne une liste comprenant les pairesd’éléments correspondants. On azip [0..4] ”hello” = [(0,’ h ’),(1,’ e ’),(2,’ l ’),(3,’ l ’),(4,’ o ’)]Quand les listes ont une longueur différente, la longueur du résultat est le minimumdes longueurs concernées :zip [0,1] ”hello” = [(0,’ h ’),(1,’ e ’)]zip : : [ a ] −> [ b ] −> [ ( a , b ) ]zip [ ] ys = [ ]zip ( x : xs ) [ ] = [ ]zip ( x : xs ) ( y : ys ) = ( x , y ) : zip xs ysLe pattern matching est fait d’abord sur le premier argument. On a donc zip⊥ [] = ⊥ et zip [] ⊥ = []. Considérons par exemple le produit scalaire d’unvecteur x et d’un vecteur y, défini comme sp x y = ∑ x i ∗ y i .sp : : (Num a ) => [ a ] −> [ a ] −> asp xs ys = sum (map times ( zip xs ys ) )where times ( x , y ) = x ∗ yPour déterminer si une séquence [x 0 , . . . , x n−1 ] est non-décroissante (càd. x k ≤x k+1 , ∀k : 0 ≤ k ≤ n − 2), on pourrait utiliser la fonctionnondec : : (Ord a ) => [ a ] −> Boolnondec xs = and (map l e q ( zip xs ( t a i l xs ) ) )where l e q ( x , y ) = ( x Booland [ ] = Trueand ( x : xs ) = x && and xsOn observe que ces deux exemples comprennent une version décurifiée d’unopérateur bien connue. En faite, on aoùtimes = uncurry (∗)leq = uncurry ( b −> c ) −> ( ( a , b ) −> c )uncurry f ( x , y ) = f x yL’inverse de la fonction zip est la fonction unzip qui prend une liste depaires et retourne une paire de deux listes.unzip : : [ ( a , b ) ] −> ( [ a ] , [ b ] )unzip = p a i r (map fst , map snd)20

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!