ejemplos haskell

12
1 -- 1.- FUNCIÓN RESTO. resto :: Int -> Int -> Int resto x y |x<y = x |otherwise = resto (x-y) y -- 2.- FUNCIÓN COCIENTE. cociente :: Int -> Int -> Int cociente x y |x<y = 0 |otherwise = 1 + cociente (x-y) y -- 3.- FUNCIÓN MCD. mcd :: Int -> Int -> Int mcd x y |x==y = x |x<y = mcd x (y-x) |otherwise = mcd (x-y) y -- 4.- FUNCIÓN FACTORIAL. fact :: Int -> Int fact 0 = 1 fact (n+1) = (n+1) * fact n -- 5.- VARIACIONES DE n ELEMENTOS TOMADOS DE r EN r. var :: Int -> Int -> Int var n 1 = n var n r = n * var (n-1) (r-1) -- 6.- COMBINACIONES DE n ELEMENTOS TOMADOS DE r EN r. comb :: Int -> Int -> Int comb n 1 = 1 comb n r |n==r = 1 |otherwise = comb (n-1) (r-1) + comb (n-1) r -- 7.- FUNCIÓN QUE ADJUNTA UN DÍGITO A LA DERECHA DE UN ENTERO. adj :: Int -> Int -> Int adj x y = (x * 10) + y -- 8.- SEPARACIÓN DEL ÚLTIMO DÍGITO DE UN NÚMERO. sep :: Int -> (Int,Int) sep x |x<10 = (0,x) |otherwise = (x/10,rem x 10) -- 9.- CONCATENACIÓN DE DOS NÚMEROS ENTEROS IGNORANDO EL CERO. enlaza :: Int -> Int -> Int enlaza x 0 = x enlaza x y = adj (enlaza x u) v where (u,v) = sep y -- 10.- BINARIO a DECIMAL y VICEVERSA. binario :: Int -> Int binario 0 = 0 binario 1 = 1 binario n = adj u v where v = rem n 2 u = binario (n/2) decimal :: Int -> Int decimal n = dec n 0 where dec :: Int -> Int -> Int dec 0 _ = 0 dec 1 i = 1*2^i dec n i = x + y

Upload: santiago-albo

Post on 26-Oct-2014

1.056 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Ejemplos Haskell

1 -- 1.- FUNCIÓN RESTO.

resto :: Int -> Int -> Int

resto x y |x<y = x

|otherwise = resto (x-y) y

-- 2.- FUNCIÓN COCIENTE.

cociente :: Int -> Int -> Int

cociente x y |x<y = 0

|otherwise = 1 + cociente (x-y) y

-- 3.- FUNCIÓN MCD.

mcd :: Int -> Int -> Int

mcd x y |x==y = x

|x<y = mcd x (y-x)

|otherwise = mcd (x-y) y

-- 4.- FUNCIÓN FACTORIAL.

fact :: Int -> Int

fact 0 = 1

fact (n+1) = (n+1) * fact n

-- 5.- VARIACIONES DE n ELEMENTOS TOMADOS DE r EN r.

var :: Int -> Int -> Int

var n 1 = n

var n r = n * var (n-1) (r-1)

-- 6.- COMBINACIONES DE n ELEMENTOS TOMADOS DE r EN r.

comb :: Int -> Int -> Int

comb n 1 = 1

comb n r |n==r = 1

|otherwise = comb (n-1) (r-1) + comb (n-1) r

-- 7.- FUNCIÓN QUE ADJUNTA UN DÍGITO A LA DERECHA DE UN ENTERO.

adj :: Int -> Int -> Int

adj x y = (x * 10) + y

-- 8.- SEPARACIÓN DEL ÚLTIMO DÍGITO DE UN NÚMERO.

sep :: Int -> (Int,Int)

sep x |x<10 = (0,x)

|otherwise = (x/10,rem x 10)

-- 9.- CONCATENACIÓN DE DOS NÚMEROS ENTEROS IGNORANDO EL CERO.

enlaza :: Int -> Int -> Int

enlaza x 0 = x

enlaza x y = adj (enlaza x u) v

where (u,v) = sep y

-- 10.- BINARIO a DECIMAL y VICEVERSA.

binario :: Int -> Int

binario 0 = 0

binario 1 = 1

binario n = adj u v

where v = rem n 2

u = binario (n/2)

decimal :: Int -> Int

decimal n = dec n 0

where dec :: Int -> Int -> Int

dec 0 _ = 0

dec 1 i = 1*2^i

dec n i = x + y

Page 2: Ejemplos Haskell

2 where (x,y) = (dec u (i+1) , v*2^i)

where (u,v) = sep n

-- 11.- CAMBIO DE A UNA BASE<10.

cambioAbase :: Int -> Int -> Int

cambioAbase b n |n<b = n

|otherwise = adj u v

where (u,v) = (cambioAbase b (n/b), rem n b)

-- 12.- FUNCIÓN QUE PASE DE DÍGITO a CARACTER Y VICEVERSA.

valorCar :: Int -> Char

valorCar n |n<10 = chr (n+48)

|otherwise = error "Fuera de rango."

valorNum :: Char -> Int

valorNum x = (ord x)-48

-- 13.- PASO DE UN CARACTER A MAYÚSCULA Y A MINÚSCULA.

may :: Char -> Char

may x |(ord x)<97 = x

|(ord x)>122 = x

|otherwise = chr ((ord x)-32)

minus :: Char -> Char

minus x |(ord x)<65 = x

|(ord x)>90 = x

|otherwise = chr ((ord x)+32)

-- 14.- PASO DE PALABRAS A MAYÚSCULAS Y A MINÚSCULAS.

mayuscula :: [Char] -> [Char]

mayuscula [] = []

mayuscula (x:xs) = (may x: mayuscula xs)

minuscula :: [Char] -> [Char]

minuscula [] = []

minuscula (x:xs) = (minus x: minuscula xs)

-- 15.- PRECEDENCIA LEXICOGRAFICA.

precede :: [Char] -> [Char] -> Bool

precede cadena1 cadena2 = precede2 (mayuscula cadena1) (mayuscula cadena2)

where precede2 :: [Char] -> [Char] -> Bool

precede2 ys [] = False

precede2 [] ys = True

precede2 (x:xs) (y:ys) | (ord x) > (ord y) = False

| (ord x) < (ord y) = True

| otherwise = precede2 xs ys

-- 16.- FUNCION QUE DEVUELVE LA POSICIÓN DE UN CARACTER DADO EN UNA CADENA Y

OTRA QUE

-- DEVUELVA EL CARACTER QUE ESTÁ EN UNA POSICIÓN DADA DE UNA CADENA.

carPos :: Int -> [Char] -> Char

carPos 0 (x:xs) = x

carPos _ [] = error "Posicion no valida"

carPos (n+1) (x:xs) = carPos n xs

Page 3: Ejemplos Haskell

3 posCar :: Char -> [Char] -> Int

posCar x [] = error "El caracter no esta en la cadena"

posCar x (y:ys) |x==y = 0

|otherwise = 1 + posCar x ys

-- 17.- FUNCIÓN QUE DEVUELVE LA POSICIÓN DE LA PRIMERA APARICIÓN DEL CARACTER

DE UNA CADENA EN LA OTRA.

posSubCad :: [Char] -> [Char] -> Int

posSubCad [] _ = error "No hay coincidencias"

posSubCad (x:xs) ys | esta x ys = posCar x ys

| otherwise = posSubCad xs ys

esta x [] = False

esta x (y:ys) | x==y = True

| otherwise = esta x ys

-- 18.- FUNCIÓN QUE AÑADE UN CARACTER A LA DERECHA DE UNA CADENA.

adjCar :: Char -> [Char] -> [Char]

adjCar x xs = xs ++ [x]

-- 19.- FUNCIÓN INVERSA PARA INVERTIR CADENAS DE CARACTERES.

inversa :: [Char] -> [Char]

inversa [] = []

inversa (x:xs) = (inversa xs) ++ [x]

-- 20.- FUNCIÓN CAPICUA QUE DETERMINE SI UNA CADENA ES SIMETRICA.

capicua :: [Char] -> Bool

capicua xs = inversa xs == xs

-- 21.- FUNCIÓN PARA PERMUTAR LOS ELEMENTOS DE UNA CADENA SEGÚN LA DISPOSICIÓN

DE LOS ELEMENTOS DE OTRAS DOS.

-- EJEMPLO: permutada "AMOR" "abcd" "dabc" = "RAMO"

permutada :: [Char] -> [Char] -> [Char] -> [Char]

permutada _ _ [] = []

permutada xs ys (z:zs) = (u:us)

where u = carPos (posCar z ys) xs

us = permutada xs ys zs

-- 22.- CÁLCULO DEL n-ésimo término de la sucesión de Fibonacci.

fib :: Int -> Int

fib 0 = 1

fib 1 = 1

fib (n+2) = fib (n+1) + fib n

-- 23.- CÁLCULO DE LA RAIZ CUADRADA DE UN NÚMERO REAL r APLICANDO EL ALGORITMO

DE NEWTON-RAPHSON.

raiz :: Float -> Float

raiz r = raiz2 r 0

raiz2 :: Float -> Int -> Float

raiz2 r i | ((suc r i) - (suc r (i+1))) == 0.0 = suc r i

| otherwise = raiz2 r (i+1)

suc r 0 = r/2.0

suc r (i+1) = (1.0/2.0) * ( anterior + (r / anterior ) )

Page 4: Ejemplos Haskell

4 where anterior = suc r i

-- 24.- TIPO DE DATOS TEMPERATURA Y FUNCIÓN PARA EL PASO DE GRADOS CEL. A FAH. Y

VICEVERSA.

data Temperatura = C Float | F Float

conversion :: Temperatura -> Temperatura

conversion (F x) = C (((x-32.0) * 5.0) / 9.0)

conversion (C x) = F ((5.0*x)/9.0 + 32.0)

-- 25.- TIPO DE DATOS RACIONAL CON REPRESENTACION BINOMICA (numerador, denominador).

FUNCION raNormal

-- QUE SIMPLIFIQUE LA REPRESENTACIÓN DE UN RACIONAL. OPERACIONES:

SUMA,RESTA,PRODUCTO Y DIVISION

-- CON OPERADORES INFIJO Y CUYO RESULTADO ESTE SIMPLIFICADO POR LA FUNCION raNormal.

type Racional = (Int,Int)

raNormal :: Racional -> Racional

raNormal (num,den) = (a,b) where a = num / mcd num den

b = den / mcd num den

mcd :: Int -> Int -> Int

mcd x y |x==y = x

|x<y = mcd x (y-x)

|otherwise = mcd (x-y) y

(num1,den1) +: (num2,den2) = raNormal (a,b)

where a = (num1 * den2) + (num2 * den1)

b = den1 * den2

(num1,den1) -: (num2,den2) = raNormal (a,b)

where a = (num1 * den2) - (num2 * den1)

b = den1 * den2

(num1,den1) *: (num2,den2) = raNormal (a,b)

where a = (num1 * num2)

b = (den1 * den2)

(num1,den1) /: (num2,den2) = raNormal (a,b)

where a = (num1 * den2)

b = (den1 * num2)

-- 26.- TIPO DE DATOS REAL CON REPRESENTACION (MANTISA, EXPONENTE) Y UNA FUNCION

rNormal QUE LOS SIMPLIFIQUE

-- AJUSTANDOSE A LA SIGUIENTE RESTRICCION: 3276 =< m =< 32768

type Real = (Float,Int)

rNormal :: Real -> Real

rNormal (m,e) | m<3276.0 = rNormal (m*10.0,e-1)

| m>32760.0 = rNormal (m/10.0,e+1)

| otherwise = (m,e)

(m1,e1) +*: (m2,e2) = rNormal (suma (m1,e1) (m2,e2))

Page 5: Ejemplos Haskell

5 suma :: Real -> Real -> Real

suma (m1,e1) (m2,e2) | e1>e2 = suma (m1*10.0,e1-1) (m2,e2)

| e1<e2 = suma (m1,e1) (m2*10.0,e2+1)

| otherwise = (m1+m2,e1)

(m1,e1) -*: (m2,e2) = rNormal (resta (m1,e1) (m2,e2))

resta :: Real -> Real -> Real

resta (m1,e1) (m2,e2) | e1>e2 = resta (m1*10.0,e1-1) (m2,e2)

| e1<e2 = resta (m1,e1) (m2*10.0,e2+1)

| otherwise = (m1-m2,e1)

(m1,e1) **: (m2,e2) = rNormal (m1*m2,e1+e2)

(m1,e1) /*: (m2,e2) = rNormal (m1/m2,e1-e2)

-- 27.- DEFINIR EL TIPO COMPLEJO CON REPRESENTACIONES POLAR Y BINOMICA Y

ESCRIBIR LAS OPERACIONES

-- CORRESPONDIENTES USANDO OPERADORES INFIJOS.

data Complejo = Rect Float Float | Pol Float Float

sumac :: Complejo -> Complejo -> Complejo

sumac (Rect real1 imag1) (Rect real2 imag2) = Rect (real1+real2) (imag1+imag2)

sumac (Pol mod1 arg1) (Pol mod2 arg2) = Pol (mod1+mod2) (arg1+arg2)

restac :: Complejo -> Complejo -> Complejo

restac (Rect real1 imag1) (Rect real2 imag2) = Rect (real1-real2) (imag1-imag2)

restac (Pol mod1 arg1) (Pol mod2 arg2) = Pol (mod1-mod2) (arg1-arg2)

productoc :: Complejo -> Complejo -> Complejo

productoc (Rect real1 imag1) (Rect real2 imag2) = Rect ((real1*real2)-(imag1*imag2))

((real1*imag2)+(imag1*real2))

productoc (Pol mod1 arg1) (Pol mod2 arg2) = Pol (mod1*mod2) (arg1-arg2)

cocientec (Rect real1 imag1) (Rect real2 imag2) = Rect ((a*c+b*d)/(c*c+d*d)) ((b*c-a*d)/(c*c+d*d))

where a = real1

b = imag1

c = real2

d = imag2

cocientec (Pol mod1 arg1) (Pol mod2 arg2) = Pol (mod1/mod2) (arg1-arg2)

-- 28.- HACER INSTANCIAS DE LA CLASE NUM A LOS TIPOS RACIONAL, REAL Y COMPLEJO

type Racional = (Int,Int)

raNormal :: Racional -> Racional

raNormal (num,den) = (a,b) where a = num / mcd num den

b = den / mcd num den

mcd :: Int -> Int -> Int

mcd x y |x==y = x

|x<y = mcd x (y-x)

|otherwise = mcd (x-y) y

instance Num Racional where

(num1,den1) + (num2,den2) = raNormal (a,b)

where a = (num1 * den2) + (num2 * den1)

b = den1 * den2

Page 6: Ejemplos Haskell

6

(num1,den1) - (num2,den2) = raNormal (a,b)

where a = (num1 * den2) - (num2 * den1)

b = den1 * den2

(num1,den1) * (num2,den2) = raNormal (a,b)

where a = (num1 * num2)

b = (den1 * den2)

(num1,den1) / (num2,den2) = raNormal (a,b)

where a = (num1 * den2)

b = (den1 * num2)

type Real = (Float,Int)

rNormal :: Real -> Real

rNormal (m,e) | m<3276.0 = rNormal (m*10.0,e-1)

| m>32760.0 = rNormal (m/10.0,e+1)

| otherwise = (m,e)

instance Num Real where

(m1,e1) + (m2,e2) = rNormal (suma (m1,e1) (m2,e2))

where suma (m1,e1) (m2,e2) | e1>e2 = suma (m1*10.0,e1-1) (m2,e2)

| e1<e2 = suma (m1,e1) (m2*10.0,e2+1)

| otherwise = (m1+m2,e1)

(m1,e1) - (m2,e2) = rNormal (resta (m1,e1) (m2,e2))

where resta (m1,e1) (m2,e2) | e1>e2 = resta (m1*10.0,e1-1) (m2,e2)

| e1<e2 = resta (m1,e1) (m2*10.0,e2+1)

| otherwise = (m1-m2,e1)

(m1,e1) * (m2,e2) = rNormal (m1*m2,e1+e2)

(m1,e1) / (m2,e2) = rNormal (m1/m2,e1-e2)

data Complejo = Rect Float Float | Pol Float Float

instance Num Complejo where

(Rect real1 imag1) + (Rect real2 imag2) = Rect (real1+real2) (imag1+imag2)

(Pol mod1 arg1) + (Pol mod2 arg2) = Pol (mod1+mod2) (arg1+arg2)

(Rect real1 imag1) - (Rect real2 imag2) = Rect (real1-real2) (imag1-imag2)

(Pol mod1 arg1) - (Pol mod2 arg2) = Pol (mod1-mod2) (arg1-arg2)

(Rect real1 imag1) * (Rect real2 imag2) = Rect ((real1*real2)-(imag1*imag2))

((real1*imag2)+(imag1*real2))

(Pol mod1 arg1) * (Pol mod2 arg2) = Pol (mod1*mod2) (arg1-arg2)

(Rect real1 imag1) / (Rect real2 imag2) = Rect ((a*c+b*d)/(c*c+d*d)) ((b*c-a*d)/(c*c+d*d))

where a = real1

b = imag1

c = real2

d = imag2

(Pol mod1 arg1) / (Pol mod2 arg2) = Pol (mod1/mod2) (arg1-arg2)

-- 30.- LONGITUD, ENCADENADO, INVERSION, PALINDROMO Y LISTA ORDENADA TANTO

CRECIENTE COMO DECRECIENTE

-- DE DOS SECUENCIAS DEL SIGUIENTE TIPO: data Seq a = Mo a | a :< Seq a

Page 7: Ejemplos Haskell

7 data Seq a = Mo a | a :< Seq a

lonSeq :: Seq a -> Int

lonSeq (Mo x) = 1

lonSeq (x :< xs) = 1 + lonSeq xs

catSeq :: Seq a -> Seq a -> Seq a

catSeq (Mo x) ys = x :< ys

catSeq (x :< xs) ys = x :< (catSeq xs ys)

revSeq :: Seq a -> Seq a

revSeq (Mo x) = (Mo x)

revSeq (x :< xs) = catSeq (revSeq xs) (Mo x)

palSeq :: Seq a -> Seq a

palSeq (Mo x) = (Mo x)

palSeq xs = catSeq xs (revSeq xs)

seqToList :: Seq a -> [a]

seqToList (Mo x) = [x]

seqToList (x :< xs) = x : seqToList xs

seqInvList :: Seq a -> [a]

seqInvList (Mo x) = [x]

seqInvList (x :< xs) = seqInvList xs ++ [x]

-- 33.- DADO EL SIGUIENTE TIPO, ESCRIBIR UNA FUNCION QUE CALCULE EL VALOR DE

CUALQUIERA DE ESTOS ARBOLES.

data Exp = Num Int|Op Exp Char Exp

valor :: Exp -> Int

valor (Num x) = x

valor (Op izq sig der) | sig=='+' = (valor izq) + (valor der)

| sig=='-' = (valor izq) - (valor der)

| sig=='*' = (valor izq) * (valor der)

| sig=='/' = (valor izq) / (valor der)

| otherwise = error "Error"

-- 34.- DADO EL SIGUIENTE TIPO DE ARBOL, CALCULAR EL NUMERO DE HOJAS, NODOS,

CAMINOS E IMAGEN ESPECTRAL.

data Tree a = Leaf a | Node (Tree a) (Tree a)

leaf :: Tree a -> Int

leaf (Leaf x) = 1

leaf (Node izq der) = (leaf izq) + (leaf der)

node :: Tree a -> Int

node (Leaf x) = 0

node (Node izq der) = 1 + (node izq) + (node der)

maxpath :: Tree a -> Int

maxpath (Leaf _) = 0

maxpath (Node izq der) = 1 + max (maxpath izq) (maxpath der)

minpath :: Tree a -> Int

minpath (Leaf _) = 0

minpath (Node izq der) = 1 + min (minpath izq) (minpath der)

Page 8: Ejemplos Haskell

8

twist :: Tree a -> Tree a

twist (Leaf x) = Leaf x

twist (Node izq der) = Node (twist der) (twist izq)

-- 35.- DADO EL SIGUIENTE TIPO DE ARBOL, CALCULAR SI ESTA ORDENADO, SI ESTA

EQUILIBRADO EN ALTURA, EN PESO,

-- INSERTAR EN EL ARBOL ORDENADO Y ELIMINAR DEL MISMO.

data Arbol a = V | Nodo (Arbol a) a (Arbol a)

es_ord :: (Ord a) => Arbol a -> Bool

es_ord V = True

es_ord (Nodo V x V) = True

es_ord (Nodo i x d) = (x >= (raiz i)) && (x <= (raiz d)) && (es_ord i) && (es_ord d)

where raiz :: Arbol a -> a

raiz (Nodo i x d) = x

es_Heq :: Arbol a -> Bool

es_Heq V = True

es_Heq (Nodo i x d) = (camino_max(i) == camino_max(d)) && (es_Heq i) && (es_Heq d)

where camino_max :: Arbol a -> Int

camino_max V = 0

camino_max (Nodo i x d) = 1 + (max (camino_max i) (camino_max d))

insertar :: (Ord a) => a -> Arbol a -> Arbol a

insertar elem V = Nodo V elem V

insertar elem (Nodo i x d) | elem<x = Nodo (insertar elem i) x d

| elem>x = Nodo i x (insertar elem d)

|otherwise = error "No es posible repetir elementos"

--NOTA: En los árboles binarios de búsqueda no se deben repetir los elementos.

eliminar :: (Ord a) => a -> Arbol a -> Arbol a

eliminar elem V = V

eliminar elem (Nodo V x V) | elem==x = V

| otherwise = Nodo V x V

eliminar elem (Nodo i x d) | elem<x = Nodo (eliminar elem i) x d

| elem>x = Nodo i x (eliminar elem d)

|otherwise = (Nodo i (menor d) (eliminar (menor d) d))

menor :: (Ord a) => Arbol a -> a

menor (Nodo V x _) = x

menor (Nodo i x d) = menor i

-- 36.- ARBOLES N-ARIOS NO VACIOS: CALCULAR EL NUMERO DE HOJAS, DE NODOS Y

CAMINOS MAXIMO Y MINIMO

data ArbolG a = NodoG a [ArbolG a]

leafG :: ArbolG a -> Int

leafG (NodoG x []) = 1

leafG (NodoG x (y:ys)) = leafG y + leafG2 ys

leafG2 [] = 0

leafG2 (y:ys) = (leafG y) + leafG2 ys

nodeG :: ArbolG a -> Int

nodeG (NodoG x []) = 0

nodeG (NodoG x (y:ys)) = nodeG y + nodeG2 ys

nodeG2 [] = 1

Page 9: Ejemplos Haskell

9 nodeG2 (y:ys) = (nodeG y) + nodeG2 ys

minpathG :: ArbolG a -> Int

minpathG (NodoG x []) = 0

minpathG (NodoG x (y:ys)) = 1 + min (minpathG y) (minpathG (NodoG x ys))

maxpathG :: ArbolG a -> Int

maxpathG (NodoG x []) = 0

maxpathG (NodoG x (y:ys)) = 1 + max (maxpathG y) (maxpathG (NodoG x ys))

-- 38.- FUNCION aplicaSeq PARA APLICAR UNA FUNCION A TODOS LOS ELEMENTOS DE UNA

SECUENCIA (TIPO EJERCICIO 30)

data (Seq a) = Mo a | a :< (Seq a)

aplicaSeq :: (a -> b) -> (Seq a) -> (Seq b)

aplicaSeq f (Mo x) = Mo (f x)

aplicaSeq f (x :< xs) = (f x) :< (aplicaSeq f xs)

-- 39.- DEFINIR UNA FUNCION filtrar Y UNA rechazar CONTRARIA A ESTA.

filtrar :: (a -> Bool) -> [a] -> [a]

filtrar p [] = []

filtrar p (x:xs) | p x = x: filtrar p xs

| otherwise = filtrar p xs

rechazar :: (a -> Bool) -> [a] -> [a]

rechazar p [] = []

rechazar p (x:xs) | p x = rechazar p xs

| otherwise = x: rechazar p xs

-- 40.- DEFINIR UNA FUNCION QUE OPERE ENTRE LOS ELEMENTOS DE DOS LISTAS DOS A

DOS.

-- EJEMPLO: parList (+) [3,4] [2,2,1] = [5,6]

parList :: (a -> b -> c) -> [a] -> [b] -> [c]

parList f [] _ = []

parList f _ [] = []

parList f (x:xs) (y:ys) = (f x y) : parList f xs ys

-- 41.- DEFINIR UNA FUNCION mapBtree PARA CONSTRUIR UN ARBOL DEL TIPO DEL

EJERCICIO 35, CON LA MISMA FORMA

-- QUE APARECE EN EL SEGUNDO ARGUMENTO, PERO CON LOS VALORES DEL TIPO a

CAMBIADOS POR SUS TRANSFORMADOS

-- POR LA FUNCION QUE APARECE COMO PRIMER ARGUMENTO.

data (BTree a) = Vac | Nod (BTree a) a (BTree a)

mapBtree :: (a -> b) -> (BTree a) -> (BTree b)

mapBtree f Vac = Vac

mapBtree f (Nod i x d) = Nod (mapBtree f i) (f x) (mapBtree f d)

-- IDEM A LA ANTERIOR PERO SOBRE ARBOLES DE HOJAS, EJERCICIO 34.

data (HTree a) = Leaf a | HNod (HTree a) (HTree a)

mapLtree :: (a -> b) -> (HTree a) -> (HTree b)

mapLtree f (Leaf x) = Leaf (f x)

mapLtree f (HNod i d) = HNod (mapLtree f i) (mapLtree f d)

Page 10: Ejemplos Haskell

10 -- 42.- IDEM AL EJERCICIO 40 PERO OPERANDO SOBRE ARBOLES DE HOJAS.

data (Arbol a) = Vacio | Nodo a (Arbol a) (Arbol a)

parLtree :: (a -> b -> c) -> Arbol a -> Arbol b -> Arbol c

parLtree f Vacio _ = Vacio

parLtree f _ Vacio = Vacio

parLtree f (Nodo x i d) (Nodo x2 i2 d2) = Nodo (f x x2) (parLtree f i i2) (parLtree f d d2)

-- 43.- FUNCION compress QUE APLICADA A f Y A UNA LISTA [a1,a2,...,an) PRODUZCA f a1 (f a2 (...(f

an-1 an)...)).

compress :: (a -> a -> a) -> [a] -> a

compress f [x] = x

compress f [x,y] = (f x y)

compress f (x:xs) = f x (compress f xs)

-- FUNCION condense QUE APLICADA A f Y A g Y A UNA LISTA [a1,a2,...,an] PRODUZCA

COMO RESULTADO EL VALOR

-- f a1 (f a2 (... (f an-1 (g an))...))

condense :: (a -> b -> b) -> (a -> b) -> [a] -> b

condense f g [x] = g x

condense f g [x,y] = f x (g y)

condense f g (x:xs) = f x (condense f g xs)

-- CONSTRUIR UNA FUNCION conSeq Y OTRA conTree QUE SE COMPORTE IGUAL QUE

condense PERO CON LOS

-- ELEMENTOS DE LOS TIPOS Seq a Y ArbolH a.

data Seq a = Mo a | a :< Seq a

data ArbolH a = H a | N (ArbolH a) (ArbolH a)

conSeq :: (a -> b -> b) -> (a -> b) -> Seq a -> b

conSeq f g (Mo x) = g x

conSeq f g (x :< Mo y) = f x (g y)

conSeq f g (x :< xs) = f x (conSeq f g xs)

conTree :: (a -> a -> a) -> (b -> a) -> ArbolH b -> a

conTree f g (H a) = g a

conTree f g (N (H x) (H y)) = f (g x) (g y)

conTree f g (N i d) = f (conTree f g i) (conTree f g d)

-- 44.- CON AYUDA DE LA FUNCION conSeq CONSTRUIR:

-- a) UNA FUNCION QUE TRANSFORME SECUENCIAS EN LISTAS.

alista :: Seq a -> [a]

alista (Mo x) = [x]

alista (x:<xs) = conSeq (:) alista (x:<xs)

-- 48.- DEFINIR UNA FUNCION listasuc QUE GENERE LA LISTA INFINITA DE LOS NUMEROS

SIGUIENTES A UNO DADO.

listasuc :: (Enum a) => a -> [a]

listasuc n = [n..]

Page 11: Ejemplos Haskell

11 -- CON LA FUNCION ANTERIOR Y LA FUNCION filtrar CONSTRUIR UNA LISTA CON LOS 10

PRIMEROS MULTIPLOS DE 7.

multiplos = take 10 [m |m <- listasuc 1, m `mod` 7 == 0]

-- 49.- DEFINIR UNA FUNCION QUE CONSTRUYA UNA LISTA CON LOS 100 PRIMEROS

NÚMEROS PRIMOS.

primos :: [Int]

primos = map head (iterate criba [2..])

where criba :: [Int] -> [Int]

criba (p:xs) = [x | x <- xs, x `rem` p /= 0]

-- ESCRIBIR UNA EXPRESION PARA CALCULAR EL MENOR PRIMO MAYOR QUE 10000.

menor_primo :: [Int]

menor_primo = take 1 [x | x <- primos, x > 10000]

-- 50.- DEFINIR UNA FUNCION rep QUE GENERE LA LISTA INFINITA RESULTANTE DE LA

APLICACIÓN SUCESIVA

-- DE UNA FUNCION DE UN ARGUMENTO A UN CIERTO VALOR, e.d. TAL QUE rep f x = [x, f x, f (f

x), ... ].

rep :: (a -> a) -> a -> [a]

rep f x = x: map f (rep f x)

-- CON AYUDA DE ESTA FUNCIÓN IMPLEMENTAR LAS LISTAS DE: LOS MULTIPLOS DE 5, LAS

POTENCIAS DE 2,

-- LA LISTA [True, False, True, False, ...] Y LA LISTA ['*', '**', '***', '****', ...].

mul5 :: [Int]

mul5 = rep (+5) 0

pot2 :: [Int]

pot2 = rep (*2) 1

bool :: [Bool]

bool = rep (not) True

aster :: [String]

aster = rep ('*':) "*"

-- 51.- ESCRIBIR UNA FUNCION EFICIENTE PARA GENERAR LA LISTA INFINITA DE LOS

NÚMEROS FACTORIALES.

listfact :: [Int]

listfact = map fact [1..]

where fact :: Int -> Int

fact 0 = 1

fact (n+1) = (n+1) * fact n

listfib :: [Int]

listfib = 1: map fib [1..]

where fib :: Int -> Int

fib 0 = 1

fib 1 = 1

fib (n+2) = fib (n+1) + fib n

-- 52.- ESCRIBIR UNA FUNCION QUE GENERE LA LISTA DE NUMEROS PERFECTOS (SON IGUAL

A LA SUMA DE SUS DIVISORES).

Page 12: Ejemplos Haskell

12

listaperfec :: [Int]

listaperfec = [x | x <- [2..], perfecto x]

where perfecto n = sum(divisores n) == n

where divisores n = [x | x <- [1..(n-1)], n `mod` x == 0]

-- 53.- ESCRIBIR UNA FUNCION QUE CALCULE LA LISTA DE FACTORIALES TENIENDO EN

CUENTA DE QUE ES IGUAL AL

-- PRODUCTO DE LAS SIGUIENTES COLUMNAS: 1 2 3 4 5 6 7 ...

-- 1 2 3 4 5 6 ...

-- 1 2 3 4 5 ...

listfact2 = fact0

where fact0 = 1: fact1

fact1 = zipWith (*) [1..] fact0

-- 54.- ESCRIBIR EXPRESIONES PARA GENERAR LAS LISTAS: [[1,4,9,...],[1,8,27,...],[1,16,81,...],...]

-- Y [(1,1)],[(2,1),(1,2)],[(3,1),(2,2),(1,3)],...]

lista1 = iterate f [1..]

where f xs = zipWith (*) xs [1..]