Tema 3: Tipos y clases

1 Conceptos básicos sobre tipos

¿Qué es un tipo?

ghci> :type True
True :: Bool
ghci> :type False
False :: Bool
ghci> :type not
not :: Bool -> Bool

Inferencia de tipos

  f :: A -> B, e :: A
  -------------------
       f e :: B
ghci> :type not True
not True :: Bool
ghci> :type not False
not False :: Bool
ghci> :type not (not False)
not (not False) :: Bool
ghci> :type not 3
Error: No instance for (Num Bool)
ghci> :type 1 + False
Error: No instance for (Num Bool)

Ventajas de los tipos

ghci> :type 1 `div` 0
1 `div` 0 :: (Integral t) => t
ghci> 1 `div` 0
*** Exception: divide by zero

2 Tipos básicos

3 Tipos compuestos

3.1 Tipos listas

[False, True]  :: [Bool]
['a','b','d']  :: [Char]
["uno","tres"] :: [String]
['a','b']     :: [Char]
['a','b','c'] :: [Char]
[['a','b'],['c']] :: [[Char]]

3.2 Tipos tuplas

(False,True)     :: (Bool,Bool)
(False,'a',True) :: (Bool,Char,Bool)
('a','b')     :: (Char,Char)
('a','b','c') :: (Char,Char,Char)
(('a','b'),['c','d']) :: ((Char,Char),[Char])

3.3 Tipos de funciones

Tipos de funciones

not     :: Bool -> Bool
isDigit :: Char -> Bool  

Funciones con múltiples argumentos o valores

suma :: (Int,Int) -> Int
suma (x,y) = x+y
deCeroA :: Int -> [Int]
deCeroA n = [0..n]

4 Parcialización

Parcialización

suma' :: Int -> (Int -> Int)
suma' x y = x+y  
ghci> :type suma' 2
suma' 2 :: Int -> Int
ghci> :type suma' 2 3
suma' 2 3 :: Int
mult :: Int -> (Int -> (Int -> Int))
mult x y z = x*y*z
ghci> :type mult 2
mult 2 :: Int -> (Int -> Int)
ghci> :type mult 2 3
mult 2 3 :: Int -> Int
ghci> :type mult 2 3 7
mult 2 3 7 :: Int

Aplicación parcial

ghci> (suma' 2) 3
5
suc :: Int -> Int
suc = suma' 1

Convenios para reducir paréntesis

5 Polimorfismo y sobrecarga

5.1 Tipos polimórficos

ghci> :type length
length :: [a] -> Int
length [1, 4, 7, 1]                   ==  4
length ["Lunes", "Martes", "Jueves"]  ==  3
length [reverse, tail]                ==  2

Ejemplos de funciones polimórficas

fst (1,'x')       ==  1
fst (True,"Hoy")  ==  True  
head [2,1,4]    ==  2
head ['b','c']  ==  'b'  
take 3 [3,5,7,9,4]        ==  [3,5,7]
take 2 ['l','o','l','a']  ==  "lo"
take 2 "lola"             ==  "lo"  
zip [3,5] "lo"  ==  [(3,'l'),(5,'o')]  

5.2 Tipos sobrecargados

ghci> :type sum
sum :: (Num a) => [a] -> a
sum [2, 3, 5]           ==  10
sum [2.1, 3.23, 5.345]  ==  10.675

Ejemplos de tipos sobrecargados

6 Clases básicas

Clase Descripción
Eq tipos comparables por igualdad
Ord tipos ordenados
Show tipos mostrables
Read tipos legibles
Num tipos numéricos
Integral tipos enteros
Fractional tipos fraccionarios

La clase Eq (tipos comparables por igualdad)

(==) :: a -> a -> Bool  
(/=) :: a -> a -> Bool  
False == True       ==  False
False /= True       ==  True
'a' == 'b'          ==  False
"aei" == "aei"      ==  True
[2,3] == [2,3,2]    ==  False
('a',5) == ('a',5)  ==  True  

La clase Ord (tipos ordenados)

(<), (<=), (>), (>=) :: a -> a -> Bool
min, max             :: a -> a -> a
False < True             ==  True
min 'a' 'b'              ==  'a'
"elegante" < "elefante"  ==  False
[1,2,3] < [1,2]          ==  False
('a',2) < ('a',1)        ==  False
('a',2) < ('b',1)        ==  True  

La clase Show (tipos mostrables)

show :: a -> String  
show False       ==  "False"
show 'a'         ==  "'a'"
show 123         ==  "123"
show [1,2,3]     ==  "[1,2,3]"
show ('a',True)  ==  "('a',True)"

La clase Read (tipos legibles)

read :: String -> a
read "False" :: Bool                 ==  False
read "'a'" :: Char                   ==  'a'
read "123" :: Int                    ==  123
read "[1,2,3]" :: [Int]              ==  [1,2,3]
read "('a',True)" :: (Char,Bool)     ==  ('a',True)

La clase Num (tipos numéricos)

(+), (*), (-)       :: a -> a -> a
negate, abs, signum :: a -> a
2+3          ==  5
2.3+4.2      ==  6.5
negate 2.7   ==  -2.7
abs (-5)     ==  5
signum (-5)  ==  -1

La clase Integral (tipos enteros)

div :: a -> a -> a
mod :: a -> a -> a
11 `div` 4  ==  2
11 `mod` 4  ==  3  

La clase Fractional (tipos fraccionarios)

(/)   :: a -> a -> a
recip :: a -> a  
7.0 / 2.0  ==  3.5
recip 0.2  ==  5.0  

7 Bibliografía



Universidad de Sevilla

José A. Alonso Jiménez
Grupo de Lógica Computacional
Dpto. de Ciencias de la Computación e I.A.
Universidad de Sevilla