From 93cca003c90a1447aaa6c98be33ca770582aaf72 Mon Sep 17 00:00:00 2001 From: Manuel Thalmann Date: Sun, 16 Jun 2024 18:00:56 +0200 Subject: [PATCH] Implement a tribonacci sequence --- Exercises/exercise-4/Solution.hs | 45 ++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/Exercises/exercise-4/Solution.hs b/Exercises/exercise-4/Solution.hs index d282b82..365dedd 100644 --- a/Exercises/exercise-4/Solution.hs +++ b/Exercises/exercise-4/Solution.hs @@ -92,3 +92,48 @@ sieveC pred xs = realSieve id xs -- >>> (\ n -> sieve (\ x -> \ y -> (y `mod` x) > 0) [2..n]) 100 -- [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97] -- + +-------------------- +-- Exercise 4 +-------------------- +data Tree a = Tree a [Tree a] +depth :: Tree a -> Integer + +-- depth (Tree _ subtrees) = +-- 1 + (maximum $ 0 : (map depth subtrees)) +depth tree = realDepth [tree] 0 + where + realDepth [] x = x + realDepth trees x = realDepth (concatMap (\ (Tree _ subtrees) -> subtrees) trees) (x + 1) + +-- >>> depth (Tree 1 [Tree 1 []]) +-- 2 +-- + +-- Notes +-- realDepth [(Tree 1 [Tree 1 []])] 0 +-- realDepth (concatMap (\ (Tree _ subtrees) -> subtrees) [Tree 1 [Tree 1 []]]) (0 + 1) +-- realDepth [Tree 1 []] 1 +-- realDepth (concatMap (\ (Tree _ subtrees) -> subtrees) [Tree 1 []]) ((0 + 1) + 1) +-- realDepth [] 2 +-- 2 + +fibonacci :: Integer -> Integer +fibonacci = fib 0 1 + where + fib acc b 0 = acc + fib acc b x = fib b (acc + b) (x - 1) + +-- >>> fibonacci 6 +-- 8 +-- + +tribonacci :: Integer -> Integer +tribonacci = trib 0 0 1 + where + trib acc b c 0 = acc + trib acc b c x = trib b c (acc + b + c) (x - 1) + +-- >>> tribonacci 7 +-- 13 +--