zhaw-fup/Exercises/exercise-4/Slides.hs

42 lines
No EOL
935 B
Haskell

myMap :: (a -> b) -> [a] -> [b]
-- myMap f [] = []
-- myMap f (x : xs) = (f x) : (myMap f xs)
-- inputs: [a, b, c]
-- desired output: [a', b', c']
-- non end recursive result:
-- myMap f [a, b, c]
-- (f a) : (myMap f [b, c])
-- (f a) : ((f b) : (myMap f [c]))
-- (f a) : ((f b) : ((f c) : myMap f []))
-- (f a) : ((f b) : ((f c) : myMap f []))
-- (f a) : ((f b) : ((f c) : []))
-- a' : (b' : (c' : []))
-- [a', b', c']
-- ((a' : b') : c')
-- ((f a) : (f b)) : f c
myMap f = realMap []
where
realMap acc [] = acc
realMap acc (x : xs) = realMap (acc ++ [f x]) xs
-- >>> myMap ((+1)) [0, 2, 2, 6]
-- [1,3,3,7]
--
fakTR :: Integer -> Integer
fakTR = fakTR_ 1
where
fakTR_ :: Integer -> Integer -> Integer
fakTR_ acc 0 = acc
fakTR_ acc n = fakTR_ (n * acc) (n -1)
fakC :: Integer -> Integer
fakC = fakC_ (const 1)
where
fakC_ f n
| n == 0 = f n
| otherwise = fakC_ (\ x -> n * (f x)) $ n - 1