Tema 4: Definición d funciones

1 Definiciones por composición

isDigit :: Char -> Bool
isDigit c = c >= '0' && c <= '9'
even :: Integral a => a -> Bool
even n =  n `rem` 2 == 0
splitAt :: Int -> [a] -> ([a],[a])
splitAt n xs = (take n xs, drop n xs)  

2 Definiciones con condicionales

abs :: Int -> Int
abs n = if n >= 0 then n else -n  
signum :: Int -> Int
signum n = if n < 0 then (-1) else 
              if n == 0 then 0 else 1  

3 Definiciones con ecuaciones con guardas

abs n | n >= 0    = n
      | otherwise = -n
signum n | n < 0     = -1
         | n == 0    = 0
         | otherwise = 1

4 Definiciones con equiparación de patrones

4.1 Constantes como patrones

not :: Bool -> Bool
not True  =  False
not False =  True
(&&)  :: Bool -> Bool -> Bool
True  && True  = True
True  && False = False
False && True  = False
False && False = False

4.2 Variables como patrones

(&&) :: Bool -> Bool -> Bool
True  && True =  True
_     && _    =  False
(&&) :: Bool -> Bool -> Bool
True  && x =  x
False && _ =  False

4.3 Tuplas como patrones

fst :: (a,b) -> a
fst (x,_) = x
snd :: (a,b) -> b
snd (_,y) = y  

4.4 Listas como patrones

test1 :: [Char ] -> Bool
test1 ['a',_,_] = True
test1 _         = False
[1,2,3] = 1:[2,3] = 1:(2:[3]) = 1:(2:(3:[]))  
test2 :: [Char ] -> Bool
test2 ('a':_) = True
test2 _       = False
null :: [a] -> Bool
null []    = True
null (_:_) = False
head :: [a] -> a
head (x:_) =  x
tail :: [a] -> [a]
tail (_:xs) = xs

5 Expresiones lambda

ghci> (\x -> x+x) 3
6

Uso de las expresiones lambda para resaltar la parcialización

suma x y = x+y 
suma' = \x -> (\y -> x+y)

Uso de las expresiones lambda en funciones como resultados

const :: a -> b -> a
const x = x
const' :: a -> (b -> a)
const' x = \_ -> x

Uso de las expresiones lambda en funciones con sólo un uso

impares n = map f [0..n-1]
    where f x = 2*x+1
impares' n = map (\x -> 2*x+1) [0..n-1]

6 Secciones

ghci> 2 + 3
5
ghci> (+) 2 3
5
ghci> (2+) 3
5
ghci> (+3) 2
5

Expresión de secciones mediante lambdas

Sea * un operador. Entonces

Aplicaciones de secciones

suma''    = (+)
siguiente = (1+)
inverso   = (1/)
doble     = (2*)
mitad     = (/2)  
(&&) :: Bool -> Bool -> Bool  
ghci> map (2*) [1..5]
[2,4,6,8,10]

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