square x = x * x inf :: Int inf = 1 + inf three :: Int -> Int three x = 3 -- Determinar si dos arboles contienen los mismos valores -- en las hojas y en el mismo orden. data Btree a = Leaf a | Fork (Btree a) (Btree a) deriving Show t1 = Fork (Fork (Leaf 3) (Leaf 5)) (Fork (Leaf 6) (Fork (Leaf 8) (Leaf 9))) t2 = Fork (Leaf 4) (Fork (Fork (Leaf 5) (Leaf 6)) (Fork (Leaf 8) (Leaf 9))) eqleaves :: Ord a => Btree a -> Btree a -> Bool eqleaves t t' = leaves t == leaves t' leaves (Leaf a) = [a] leaves (Fork l r) = leaves l ++ leaves r -- version para lenguaje estricto eqleaves' t t' = comparestacks [t] [t'] comparestacks [] [] = True comparestacks [] (t:ts) = False comparestacks (t:ts) [] = False comparestacks (Fork l r:ts) ts' = comparestacks (l:r:ts) ts' comparestacks ts (Fork l r:ts') = comparestacks ts (l:r:ts') comparestacks (Leaf a:ts) (Leaf b:ts') | a == b = comparestacks ts ts' | otherwise = False -- Listas infinitas ones = 1 : ones pot2 = iterate (*2) 1 nats = iterate (+1) 0 from n = iterate (+1) n fromTo m n = takeWhile (<= n) (from m) -- Criba de Eratosthenes primos = criba [2..] criba xs = map head (iterate borrar xs) borrar (p:xs) = [x | x <- xs, x `mod` p /= 0] {- iterate borrar [2..] --> [2..] : iterate borrar (borrar [2..]) --> [2..] : iterate borrar [3,5,7,9,...] --> [2..] : [3,5,7,...] : iterate borrar (borrar [3,5,7,...]) --> [2..] : [3,5,7,...] : iterate borrar [5,7,11,...] --> [2..] : [5,7,...] : [5,7,11,...] : iterate borrar [7,11,...] -} -- version recursiva rprimos = rcriba [2..] rcriba (p:xs) = p : rcriba [x | x <- xs, x `mod` p /= 0] -- Definiciones circulares -- lista de naturales cnats = 0 : zipWith (+) cnats ones cnats' = 0 : map (+1) cnats' -- lista de factoriales facts = map fact nats where fact 0 = 1 fact n = n * fact (n-1) facts' = map fst $ iterate next (1,0) where next (f,n) = (f*(n+1),n+1) cfacts = 1 : zipWith (*) [1..] cfacts -- secuencia de fibonacci fibos = map fib [0..] where fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib(n-2) fibos' = map fst $ iterate next (0,1) where next (m,n) = (n,m+n) cfibos = 0 : 1 : zipWith (+) cfibos (tail cfibos) -- Arboles infinitos btree1 = Fork (Leaf 5) btree1 btree2 = Fork (Fork btree2 (Leaf 2)) (Fork (Leaf 3) btree1) {- bt1 = /\ 5 /\ 5 /\ 5 bt1 bt2 = /\ / \ /\ /\ bt2 2 3 bt1 -} leftmost (Leaf x) = x leftmost (Fork l r) = leftmost l ejemplo1 = leftmost btree1 ejemplo2 = leftmost btree2 ejemplo3 = take 5 $ map (*2) $ leaves btree1 ejemplo4 = take 5 $ map (*2) $ leaves btree2