SlideShare une entreprise Scribd logo
1  sur  34
Télécharger pour lire hors ligne
´
Programacion funcional en Haskell

              Roberto Bonvallet
             Departamento de Inform´ tica
                                      a
       Universidad T´ cnica Federico Santa Mar´a
                    e                         ı


                 Mayo de 2009
Programas y diapositivas
git clone git:/
              /github.com/rbonvall/charla-haskell.git
¿Qu´ hace esto?
   e
    float z = 0.0;
    f o r ( i = 0 ; i < n ; ++ i )
          z = z + a[ i ];
¿Qu´ hace esto?
   e
    float z = 0.0;
    f o r ( i = 0 ; i < n ; ++ i )
          z = z + a[ i ];


¿Y esto?
    unsigned i n t z = 0 ;
    f o r ( i = 0 ; i < n ; ++ i )
          z = MAX( z , a [ i ] ) ;
¿Y esto otro?
    bool z = f a l s e ;
    f o r ( i = 0 ; i < n ; ++ i )
          z = z | | ( a [ i ] % 2 == 0 ) ;
¿Y esto otro?
    bool z = f a l s e ;
    f o r ( i = 0 ; i < n ; ++ i )
          z = z | | ( a [ i ] % 2 == 0 ) ;


¿Y esto de ac´ ?
             a
     s t r i n g z ( ”” ) ;
     f o r ( i = 0 ; i < n ; ++ i )
             z . append ( a [ i ] ) ;
´     ´
El patron comun

z = z0 ;
f o r ( i = 0 ; i < n ; ++ i )
      z = f(z , a [ i ] ) ;
En “funcional”
sum ’ [ ]        = 0.0
sum ’ ( x : xs ) = x + sum ’ xs

maximum’ [ ]        = 0
maximum’ ( x : xs ) = max x (maximum’ xs )

any even ’ [ ]        = False
any even ’ ( x : xs ) = ( x ‘mod‘ 2 == 0 ) | |
                        ( any even ’ xs )

concat ’ [ ]        = ””
concat ’ ( x : xs ) = x ++ ( concat ’ xs )
´
Funcion foldl
sum ’ ’        =   foldl   (+) 0.0
maximum’ ’     =   foldl   max 0
concat ’ ’     =   foldl   ( + + ) ””
any even ’ ’   =   foldl   (λ x y →
                           x | | even y ) F a l s e
´
Definicion de foldl
foldl : : ( a → b → a ) → a → [b] → a
f o l d l f z0 [ ]        = z0
f o l d l f z0 ( x : xs ) = f o l d l f ( f z0 x ) xs
´
Definicion de funciones
fact 0 = 1
f a c t x = x ∗ f a c t ( x − 1)
´
Definicion de funciones
fact 0 = 1
f a c t x = x ∗ f a c t ( x − 1)


Operadores son funciones

41 ∗ 200
( ∗ ) 41 200
´
Definicion de funciones
fact 0 = 1
f a c t x = x ∗ f a c t ( x − 1)


Operadores son funciones

41 ∗ 200
( ∗ ) 41 200


Funciones son operadores

elem 2 [ 1 . . 1 0 ]
2 ‘ elem ‘ [ 1 . . 1 0 ]
Quicksort

                 p

            <p       p   ≥p
Quicksort

                         p

               <p             p         ≥p

En Haskell
qs [ ] = [ ]
qs ( x : xs ) = qs ( f i l t e r (<x ) xs ) ++
                [ x ] ++
                qs ( f i l t e r (≥x ) xs )
D´gito verificador como si estuviera en primero
 ı

      1   4   2    3   0    1   2    4
D´gito verificador como si estuviera en primero
 ı

      1   4   2    3   0    1   2   4
      3   2   7    6   5    4   3   2
D´gito verificador como si estuviera en primero
 ı

   1      4 2 3 0           1   2   4
 × 3      2 7 6 5           4   3   2
   3      8 14 18 0         4   6   8
D´gito verificador como si estuviera en primero
 ı

   1        4 2 3 0         1   2   4
 × 3        2 7 6 5         4   3   2
   3        8 14 18 0       4   6   8
        +
    − − → 61
     −−
D´gito verificador como si estuviera en primero
 ı

   1        4 2 3 0         1   2   4
 × 3        2 7 6 5         4   3   2
   3        8 14 18 0       4   6   8
        +         11−x
    − − → 61 − − −50
     −−      −→
D´gito verificador como si estuviera en primero
 ı

   1        4 2 3 0         1   2   4
 × 3        2 7 6 5         4   3   2
   3        8 14 18 0       4   6   8
        +         11−x           mod 11
    − − → 61 − − −50 − − − 5
     −−      −→       − −→
Fibonacci vieja escuela

fib 0 = 1
fib 1 = 1
fib x = fib ( x − 1) + fib ( x − 2)
Fibonacci vieja escuela

fib 0 = 1
fib 1 = 1
fib x = fib ( x − 1) + fib ( x − 2)


Fibonacci perezoso

f i b = 1 : 1 : ( zipWith ( + ) f i b $ t a i l f i b )
´
D´gito verificador, version 1
 ı

dv1 : : S t r i n g → Char
dv1 r u t =
  l e t revRut = r e v e r s e r u t
        r e v D i g i t s = map d i g i t T o I n t revRut
        factors = cycle [ 2 . . 7 ]
        products =
                zipWith ( ∗ ) f a c t o r s r e v D i g i t s
        sumOfProducts = sum products
        d i g i t = ( 1 1 − sumOfProducts ) ‘mod‘ 11
  in digitToChar d i g i t
  where digitToChar 10 = ’ k ’
            digitToChar x = chr $ x + ord ’ 0 ’
D´gito verificador, algunas simplificaciones
 ı

dv2 : : S t r i n g → Char
dv2 r u t =
  let revDigits =
           map d i g i t T o I n t $ r e v e r s e r u t
       products =
           zipWith ( ∗ ) ( c y c l e [ 2 . . 7 ] ) r e v D i g i t s
        d i g i t = ( 1 1 − sum products ) ‘mod‘ 11
  in ” 0123456789 k” ! ! d i g i t
D´gito verificador, m´ s astuto de la cuenta
 ı                  a

dv3 : : S t r i n g → Char
dv3 r u t = ” 0 k987654321 ” ! ! ( ( sum $
                   zipWith ( ∗ ) ( c y c l e [ 2 . . 7 ] ) $
                   map d i g i t T o I n t $
                   r e v e r s e r u t ) ‘mod‘ 1 1 )
´
Composicion

f :: a → b
g :: b → c
( f ◦ g) : : a → c
´
Composicion

f :: a → b
g :: b → c
( f ◦ g) : : a → c


Currying

zipWith : : ( a → b → c ) → [ a ] → [ b ] → [ c ]
zipWith ( + ) : : (Num a ) ⇒
                    [a] → [a] → [a]
zipWith ( + ) [ 1 . . 1 0 ] : : (Enum a , Num a ) ⇒
                                [a] → [a]
´
D´gito verificador, composicion + currying
 ı

dv4 : : S t r i n g → Char
dv4 r u t = ” 0 k987654321 ” ! ! ( (
    (sum ◦ zipWith ( ∗ ) ( c y c l e [ 2 . . 7 ] )
      ◦ map d i g i t T o I n t ◦ r e v e r s e ) r u t )
    ‘mod‘ 1 1 )
D´gito verificador, propiedades de mod 11
 ı

dv5 : : S t r i n g → Char
dv5 r u t = ( c y c l e ”0 k987654321 ” ) ! ! (
    (sum ◦ zipWith ( ∗ ) ( c y c l e [ 2 . . 7 ] )
      ◦ map d i g i t T o I n t ◦ r e v e r s e ) r u t )
D´gito verificador point-free
 ı

dv6 : : S t r i n g → Char
dv6 = ( ! ! ) ( c y c l e ”0 k987654321 ” )
       ◦ sum ◦ zipWith ( ∗ ) ( c y c l e [ 2 . . 7 ] )
       ◦ map d i g i t T o I n t ◦ r e v e r s e
Tipos de datos algebraicos

data P o i n t = P o i n t F l o a t F l o a t
data Shape = C i r c l e P o i n t F l o a t
               | Rectangle Point Point

s u r f a c e : : Shape → F l o a t
surface ( Circle                 r ) = pi ∗ r ˆ 2
s u r f a c e ( R e c t a n g l e ( P o i n t x1 y1 )
                                   ( P o i n t x2 y2 ) ) =
             ( abs $ x2 − x1 ) ∗ ( abs $ y2 − y1 )
Tipos parametrizados

data Tree a = EmptyTree
            | Node a ( Tree a ) ( Tree a )
            d e r i v i n g (Show , Read , Eq )

s i n g l e t o n : : a → Tree a
s i n g l e t o n x = Node x EmptyTree EmptyTree

t r e e I n s e r t : : ( Ord a ) ⇒ a → Tree a → Tree a
t r e e I n s e r t x EmptyTree = s i n g l e t o n x
t r e e I n s e r t x ( Node a l e f t r i g h t )
  | x == a = Node x l e f t r i g h t
  | x < a = Node a ( t r e e I n s e r t x l e f t ) r i g h t
  | x > a = Node a l e f t ( t r e e I n s e r t x r i g h t )
Recursos


    Haskell Wiki
    http://www.haskell.org/haskellwiki/
    Learn You a Haskell For Great Good!
    http://learnyouahaskell.com/
    Real World Haskell
    http://book.realworldhaskell.org/read/
    Haskell Cafe
    http://news.gmane.org/gmane.comp.lang.
    haskell.cafe

Contenu connexe

Tendances

Tendances (19)

Practica 10
Practica 10Practica 10
Practica 10
 
Exponencial y logaritmica
Exponencial y logaritmicaExponencial y logaritmica
Exponencial y logaritmica
 
Dsa 1
Dsa 1Dsa 1
Dsa 1
 
Info clasa
Info clasaInfo clasa
Info clasa
 
Virapix-ClassDiagram
Virapix-ClassDiagramVirapix-ClassDiagram
Virapix-ClassDiagram
 
python-geohex
python-geohexpython-geohex
python-geohex
 
Python codigo graficas
Python codigo graficasPython codigo graficas
Python codigo graficas
 
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
 
c ++ informe Nº5 ucsm
c ++ informe Nº5 ucsmc ++ informe Nº5 ucsm
c ++ informe Nº5 ucsm
 
Manual de practicas
Manual de practicasManual de practicas
Manual de practicas
 
12X1 T02 02 integrating exponentials
12X1 T02 02 integrating exponentials12X1 T02 02 integrating exponentials
12X1 T02 02 integrating exponentials
 
Programs
ProgramsPrograms
Programs
 
Practica de matlab
Practica de matlabPractica de matlab
Practica de matlab
 
EJEMPLOS DESARROLLADOS
EJEMPLOS DESARROLLADOSEJEMPLOS DESARROLLADOS
EJEMPLOS DESARROLLADOS
 
Kruskal algorithm
Kruskal algorithmKruskal algorithm
Kruskal algorithm
 
EV1LSHA - Misadventures in the land of Lua
EV1LSHA - Misadventures in the land of LuaEV1LSHA - Misadventures in the land of Lua
EV1LSHA - Misadventures in the land of Lua
 
Vcs21
Vcs21Vcs21
Vcs21
 
Como crear una matriz de 3x3 con c++ con menu
Como crear una matriz de 3x3 con c++ con menu Como crear una matriz de 3x3 con c++ con menu
Como crear una matriz de 3x3 con c++ con menu
 
Monads
MonadsMonads
Monads
 

En vedette

Imabo Nobel BMG
Imabo Nobel BMGImabo Nobel BMG
Imabo Nobel BMGTomw1987
 
Edición eficiente de texto con Vim
Edición eficiente de texto con VimEdición eficiente de texto con Vim
Edición eficiente de texto con VimRoberto Bonvallet
 
TecnologíA Educativa Ii
TecnologíA Educativa IiTecnologíA Educativa Ii
TecnologíA Educativa Iiguest120b84
 
Lindaflora Project, Bel Air
Lindaflora Project, Bel AirLindaflora Project, Bel Air
Lindaflora Project, Bel Airsilviaelizondo
 
Austin Xmas 2008
Austin Xmas 2008Austin Xmas 2008
Austin Xmas 2008dbranigan
 
Test 101
Test 101Test 101
Test 101Oli
 

En vedette (7)

Imabo Nobel BMG
Imabo Nobel BMGImabo Nobel BMG
Imabo Nobel BMG
 
Edición eficiente de texto con Vim
Edición eficiente de texto con VimEdición eficiente de texto con Vim
Edición eficiente de texto con Vim
 
TecnologíA Educativa Ii
TecnologíA Educativa IiTecnologíA Educativa Ii
TecnologíA Educativa Ii
 
Tobacco Use
Tobacco UseTobacco Use
Tobacco Use
 
Lindaflora Project, Bel Air
Lindaflora Project, Bel AirLindaflora Project, Bel Air
Lindaflora Project, Bel Air
 
Austin Xmas 2008
Austin Xmas 2008Austin Xmas 2008
Austin Xmas 2008
 
Test 101
Test 101Test 101
Test 101
 

Programación funcional en Haskell

  • 1. ´ Programacion funcional en Haskell Roberto Bonvallet Departamento de Inform´ tica a Universidad T´ cnica Federico Santa Mar´a e ı Mayo de 2009
  • 2. Programas y diapositivas git clone git:/ /github.com/rbonvall/charla-haskell.git
  • 3. ¿Qu´ hace esto? e float z = 0.0; f o r ( i = 0 ; i < n ; ++ i ) z = z + a[ i ];
  • 4. ¿Qu´ hace esto? e float z = 0.0; f o r ( i = 0 ; i < n ; ++ i ) z = z + a[ i ]; ¿Y esto? unsigned i n t z = 0 ; f o r ( i = 0 ; i < n ; ++ i ) z = MAX( z , a [ i ] ) ;
  • 5. ¿Y esto otro? bool z = f a l s e ; f o r ( i = 0 ; i < n ; ++ i ) z = z | | ( a [ i ] % 2 == 0 ) ;
  • 6. ¿Y esto otro? bool z = f a l s e ; f o r ( i = 0 ; i < n ; ++ i ) z = z | | ( a [ i ] % 2 == 0 ) ; ¿Y esto de ac´ ? a s t r i n g z ( ”” ) ; f o r ( i = 0 ; i < n ; ++ i ) z . append ( a [ i ] ) ;
  • 7. ´ ´ El patron comun z = z0 ; f o r ( i = 0 ; i < n ; ++ i ) z = f(z , a [ i ] ) ;
  • 8. En “funcional” sum ’ [ ] = 0.0 sum ’ ( x : xs ) = x + sum ’ xs maximum’ [ ] = 0 maximum’ ( x : xs ) = max x (maximum’ xs ) any even ’ [ ] = False any even ’ ( x : xs ) = ( x ‘mod‘ 2 == 0 ) | | ( any even ’ xs ) concat ’ [ ] = ”” concat ’ ( x : xs ) = x ++ ( concat ’ xs )
  • 9. ´ Funcion foldl sum ’ ’ = foldl (+) 0.0 maximum’ ’ = foldl max 0 concat ’ ’ = foldl ( + + ) ”” any even ’ ’ = foldl (λ x y → x | | even y ) F a l s e
  • 10. ´ Definicion de foldl foldl : : ( a → b → a ) → a → [b] → a f o l d l f z0 [ ] = z0 f o l d l f z0 ( x : xs ) = f o l d l f ( f z0 x ) xs
  • 11. ´ Definicion de funciones fact 0 = 1 f a c t x = x ∗ f a c t ( x − 1)
  • 12. ´ Definicion de funciones fact 0 = 1 f a c t x = x ∗ f a c t ( x − 1) Operadores son funciones 41 ∗ 200 ( ∗ ) 41 200
  • 13. ´ Definicion de funciones fact 0 = 1 f a c t x = x ∗ f a c t ( x − 1) Operadores son funciones 41 ∗ 200 ( ∗ ) 41 200 Funciones son operadores elem 2 [ 1 . . 1 0 ] 2 ‘ elem ‘ [ 1 . . 1 0 ]
  • 14. Quicksort p <p p ≥p
  • 15. Quicksort p <p p ≥p En Haskell qs [ ] = [ ] qs ( x : xs ) = qs ( f i l t e r (<x ) xs ) ++ [ x ] ++ qs ( f i l t e r (≥x ) xs )
  • 16. D´gito verificador como si estuviera en primero ı 1 4 2 3 0 1 2 4
  • 17. D´gito verificador como si estuviera en primero ı 1 4 2 3 0 1 2 4 3 2 7 6 5 4 3 2
  • 18. D´gito verificador como si estuviera en primero ı 1 4 2 3 0 1 2 4 × 3 2 7 6 5 4 3 2 3 8 14 18 0 4 6 8
  • 19. D´gito verificador como si estuviera en primero ı 1 4 2 3 0 1 2 4 × 3 2 7 6 5 4 3 2 3 8 14 18 0 4 6 8 + − − → 61 −−
  • 20. D´gito verificador como si estuviera en primero ı 1 4 2 3 0 1 2 4 × 3 2 7 6 5 4 3 2 3 8 14 18 0 4 6 8 + 11−x − − → 61 − − −50 −− −→
  • 21. D´gito verificador como si estuviera en primero ı 1 4 2 3 0 1 2 4 × 3 2 7 6 5 4 3 2 3 8 14 18 0 4 6 8 + 11−x mod 11 − − → 61 − − −50 − − − 5 −− −→ − −→
  • 22. Fibonacci vieja escuela fib 0 = 1 fib 1 = 1 fib x = fib ( x − 1) + fib ( x − 2)
  • 23. Fibonacci vieja escuela fib 0 = 1 fib 1 = 1 fib x = fib ( x − 1) + fib ( x − 2) Fibonacci perezoso f i b = 1 : 1 : ( zipWith ( + ) f i b $ t a i l f i b )
  • 24. ´ D´gito verificador, version 1 ı dv1 : : S t r i n g → Char dv1 r u t = l e t revRut = r e v e r s e r u t r e v D i g i t s = map d i g i t T o I n t revRut factors = cycle [ 2 . . 7 ] products = zipWith ( ∗ ) f a c t o r s r e v D i g i t s sumOfProducts = sum products d i g i t = ( 1 1 − sumOfProducts ) ‘mod‘ 11 in digitToChar d i g i t where digitToChar 10 = ’ k ’ digitToChar x = chr $ x + ord ’ 0 ’
  • 25. D´gito verificador, algunas simplificaciones ı dv2 : : S t r i n g → Char dv2 r u t = let revDigits = map d i g i t T o I n t $ r e v e r s e r u t products = zipWith ( ∗ ) ( c y c l e [ 2 . . 7 ] ) r e v D i g i t s d i g i t = ( 1 1 − sum products ) ‘mod‘ 11 in ” 0123456789 k” ! ! d i g i t
  • 26. D´gito verificador, m´ s astuto de la cuenta ı a dv3 : : S t r i n g → Char dv3 r u t = ” 0 k987654321 ” ! ! ( ( sum $ zipWith ( ∗ ) ( c y c l e [ 2 . . 7 ] ) $ map d i g i t T o I n t $ r e v e r s e r u t ) ‘mod‘ 1 1 )
  • 27. ´ Composicion f :: a → b g :: b → c ( f ◦ g) : : a → c
  • 28. ´ Composicion f :: a → b g :: b → c ( f ◦ g) : : a → c Currying zipWith : : ( a → b → c ) → [ a ] → [ b ] → [ c ] zipWith ( + ) : : (Num a ) ⇒ [a] → [a] → [a] zipWith ( + ) [ 1 . . 1 0 ] : : (Enum a , Num a ) ⇒ [a] → [a]
  • 29. ´ D´gito verificador, composicion + currying ı dv4 : : S t r i n g → Char dv4 r u t = ” 0 k987654321 ” ! ! ( ( (sum ◦ zipWith ( ∗ ) ( c y c l e [ 2 . . 7 ] ) ◦ map d i g i t T o I n t ◦ r e v e r s e ) r u t ) ‘mod‘ 1 1 )
  • 30. D´gito verificador, propiedades de mod 11 ı dv5 : : S t r i n g → Char dv5 r u t = ( c y c l e ”0 k987654321 ” ) ! ! ( (sum ◦ zipWith ( ∗ ) ( c y c l e [ 2 . . 7 ] ) ◦ map d i g i t T o I n t ◦ r e v e r s e ) r u t )
  • 31. D´gito verificador point-free ı dv6 : : S t r i n g → Char dv6 = ( ! ! ) ( c y c l e ”0 k987654321 ” ) ◦ sum ◦ zipWith ( ∗ ) ( c y c l e [ 2 . . 7 ] ) ◦ map d i g i t T o I n t ◦ r e v e r s e
  • 32. Tipos de datos algebraicos data P o i n t = P o i n t F l o a t F l o a t data Shape = C i r c l e P o i n t F l o a t | Rectangle Point Point s u r f a c e : : Shape → F l o a t surface ( Circle r ) = pi ∗ r ˆ 2 s u r f a c e ( R e c t a n g l e ( P o i n t x1 y1 ) ( P o i n t x2 y2 ) ) = ( abs $ x2 − x1 ) ∗ ( abs $ y2 − y1 )
  • 33. Tipos parametrizados data Tree a = EmptyTree | Node a ( Tree a ) ( Tree a ) d e r i v i n g (Show , Read , Eq ) s i n g l e t o n : : a → Tree a s i n g l e t o n x = Node x EmptyTree EmptyTree t r e e I n s e r t : : ( Ord a ) ⇒ a → Tree a → Tree a t r e e I n s e r t x EmptyTree = s i n g l e t o n x t r e e I n s e r t x ( Node a l e f t r i g h t ) | x == a = Node x l e f t r i g h t | x < a = Node a ( t r e e I n s e r t x l e f t ) r i g h t | x > a = Node a l e f t ( t r e e I n s e r t x r i g h t )
  • 34. Recursos Haskell Wiki http://www.haskell.org/haskellwiki/ Learn You a Haskell For Great Good! http://learnyouahaskell.com/ Real World Haskell http://book.realworldhaskell.org/read/ Haskell Cafe http://news.gmane.org/gmane.comp.lang. haskell.cafe