Juan Pablo Yamamoto
jpyamamoto[at]ciencias.unam.mx
Lógica Computacional II. Semestre 2025-1.
lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
lookup _key [] = Nothing
lookup key ((x,y):xys)
| key == x = Just y
| otherwise = lookup key xys
:i lookup
:i Eq
import Data.List (sort)
:i sort
:i Ord
:i Ordering
:i foldr
:i Foldable
El compilador proveé instanciación automática de algunas clases sobre algunos tipos (con algunas restricciones):
data Point = Point (Double, Double) deriving (Eq, Read, Show)
show $ Point (0, 1)
"Point (0.0,1.0)"
Point (9, 9) == Point (3, 4)
False
read "Point (9.3, 5.7)" :: Point
Point (9.3,5.7)
read "hola"
Prelude.read: no parse
Las partes que constituyen al tipo deben ser en si mismas instancias de la clase que se busca derivar.
data ArregloInt = ArregloVacio | ArregloInt (Int -> Int) deriving Show
<interactive>:1:67: error: • No instance for (Show (Int -> Int)) arising from the first field of ‘ArregloInt’ (type ‘Int -> Int’) (maybe you haven't applied a function to enough arguments?) Possible fix: use a standalone 'deriving instance' declaration, so you can specify the instance context yourself • When deriving the instance for (Show ArregloInt)
¿Qué sucede cuando no están definidas todas las partes de la instancia?
data Lista a = Vacia | Cons a (Lista a) deriving Show
:i Lista
show (Cons 1 (Cons 2 Vacia))
"Cons 1 (Cons 2 Vacia)"
show (Cons id Vacia)
<interactive>:1:1: error: • No instance for (Show (a0 -> a0)) arising from a use of ‘show’ (maybe you haven't applied a function to enough arguments?) • In the expression: show (Cons id Vacia) In an equation for ‘it’: it = show (Cons id Vacia)
newtypes
para asociarles sus
instancias de clase, pero se eliminan datos innecesarios.
newtype Booleano = Booleano Bool
instance Show Booleano where
show (Booleano True) = "Si"
show (Booleano False) = "No"
show True
show (Booleano True)
show False
show (Booleano False)
"True"
"Si"
"False"
"No"
newtype Reversa = Reversa Int deriving (Eq, Show)
-- compare :: Reversa -> Reversa -> Ordering
-- data Ordering = LT | EQ | GT
instance Ord Reversa where
compare (Reversa a) (Reversa b)
| a < b = GT
| a > b = LT
| otherwise = EQ
ordenada :: Ord a => [a] -> Bool
ordenada [] = True
ordenada [_] = True
ordenada (x:xs) = x <= head xs && ordenada xs
ordenada [Reversa 1, Reversa 1, Reversa 1, Reversa 1, Reversa 1]
ordenada (map Reversa [1..10])
ordenada [Reversa 0,Reversa (-4),Reversa 2, Reversa 3, Reversa 4]
ordenada [Reversa 3, Reversa 2, Reversa 1]
True
False
False
True
:i Monad