[Haskell] Ejemplos de funciones: tail, reverse, zip, etc.

Iniciado por GGZ, 24 Diciembre 2015, 03:33 AM

0 Miembros y 1 Visitante están viendo este tema.

GGZ

Hola a todos!

He creado estas funciones con el fin de entender como funcionan cada una de ellas.
Por eso algunas ya están definidas como por ejemplo tail,reverse, zip, ...

Código (diff) [Seleccionar]
fac 0 = 1
fac n = n * fac (n-1)

replicate' 0 n = [n]
replicate' x n = n:replicate (x-1) n

take' 0 xs = []
take' n [] = []
take' 1 xs = [head xs]
take' n xs = head xs:take (n-1) (tail xs)

reverse' [] = []
reverse' (x:xs)=last (x:xs):reverse'(init (x:xs))

haycero [] = False
haycero (x:xs) = (x==0) || haycero (xs)

todosceros [] = error "No está definido para una lista vacía"
todosceros [x] = (x==0)
todosceros (x':x:xs) = (x'==0) && todosceros(x:xs)


maximo n x = if (n>x) then n else x
minimo n x = if (n>x) then x else n

maximo' n x
 | n>=x = n
 | n<x = x

zip' xs []         = []
zip' [] ys         = []
zip' (x:xs) (y:ys) = [(x,y)]  ++  zip' xs ys

zip'' xs [] = []
zip'' [] ys = []
zip'' (x:xs) (y:ys) = (x,y) : zip'' xs ys

nth [] n = error "No está definida para lista vacía"
nth xs n = if (length xs > n) then xs !! n else error "No se puede acceder a esa posición ya que no existe"



{-
Comprueba si un elemento dado está en la lista
-}

elem' n []     = False
elem' n (x:xs) = (n==x) || elem' n xs

{-
ANALISIS POR CASOS
-}

elem'':: Eq a => a -> [a] -> Bool
elem'' n xs
 | length xs==0  = False
 | otherwise     = (n==head xs) || elem'' n (tail xs)

{-
quicksort [10,2,5,3,1,6,7,4,2,3,4,8,9] = [1,2,2,3,3,4,4,5,6,7,8,9,10]
-}


{-
zip [] []= []
zip [2] [5] = [(2,5)] ++ zip [] []
zip [1,2] [4,5] = [(1,4)] ++ zip[2][5]
-}

length' [] = 0
length' (x:xs) = 1 + length' xs

{-
repeat' 0
repeat'
-}

map' f [] = []
map' f (x:xs) = f x : map' f xs

tail' [] = []
tail' (x:xs) = xs

{-
filter (>3) [1,2,3,4,10,10,10,20,20,20] = [4,10,10,10,...]
-}

sumatoria [] = 0
sumatoria (x:xs) = x+sumatoria xs

multiplicar [] = 1
multiplicar (x:xs) = x*multiplicar xs

sumatoria' xs
 | length (xs) == 0 = 0
 | otherwise = head xs+sumatoria' (tail xs)

multidos [] = []
multidos (x:xs) = 2*x : multidos xs

multiPor n [] = []
multiPor n (x:xs) = n*x : multiPor n xs

h [] = [1]
h (x:xs) = (x+1) : h xs

test [] = []
test (5:[]) = error "Tu lista empieza por 5"

h' [] = [1]
h' (x:xs) = [(x+1)] ++ h xs

g 0 = error "El numero es cero"
g n = error "El numero no es cero"

multiplicar' xs
| length xs == 0 = 1
| length xs /= 0 = head xs*multiplicar'(tail xs)


filter' f [] = []
filter' f (x:xs)
     | f x =  x:filter' f xs
     | otherwise = filter' f xs


Ejecutan ghci y lo cargan con :l <nombre-del-archivo>
Después hagan los llamados que quieran.

Perdón como se ve, no hay una etiqueta para Haskell.

Saludos!
LET'S DO STUFF!!