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)
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
abs n | n >= 0 = n
| otherwise = -n
signum n | n < 0 = -1
| n == 0 = 0
| otherwise = 1
not :: Bool -> Bool
not True = False
not False = True
(&&) :: Bool -> Bool -> Bool
True && True = True
True && False = False
False && True = False
False && False = False
(&&) :: Bool -> Bool -> Bool
True && True = True
_ && _ = False
(&&) :: Bool -> Bool -> Bool
True && x = x
False && _ = False
fst :: (a,b) -> a
fst (x,_) = x
snd :: (a,b) -> b
snd (_,y) = y
(test1 xs)
se verifica si xs
es una lista de 3 caracteres que empieza por 'a'
.test1 :: [Char ] -> Bool
test1 ['a',_,_] = True
test1 _ = False
(:)
[1,2,3] = 1:[2,3] = 1:(2:[3]) = 1:(2:(3:[]))
(test2 xs)
se verifica si xs
es una lista de caracteres que empieza por 'a'
.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
Las funciones pueden construirse sin nombrarlas mediante las expresiones lambda.
Ejemplo de evaluación de expresiones lambda:
ghci> (\x -> x+x) 3
6
Uso de las expresiones lambda para resaltar la parcialización
(suma x y)
es la suma de x
e y
.
Definición sin lambda:
suma x y = x+y
suma' = \x -> (\y -> x+y)
Uso de las expresiones lambda en funciones como resultados
(const x y)
es x
.
Definición sin lambda:
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)
es la lista de los n
primeros números impares.
Definición sin lambda:
impares n = map f [0..n-1]
where f x = 2*x+1
impares' n = map (\x -> 2*x+1) [0..n-1]
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
(*) = \x -> (\y -> x*y)
(x*) = \y -> x*y
(*y) = \x -> x*y
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]