Solve first few tasks
This commit is contained in:
parent
7260bae078
commit
67fbeab9a6
1 changed files with 56 additions and 0 deletions
56
Exercises/exercise-4/Solution.hs
Normal file
56
Exercises/exercise-4/Solution.hs
Normal file
|
@ -0,0 +1,56 @@
|
||||||
|
--------------------
|
||||||
|
-- Exercise 1
|
||||||
|
--------------------
|
||||||
|
prim c g 0 x = c x
|
||||||
|
prim c g n x = g (f (n - 1) x) (n - 1) x
|
||||||
|
where
|
||||||
|
f = prim c g
|
||||||
|
|
||||||
|
m2 :: Integer -> () -> Integer
|
||||||
|
m2 n x = prim (\_ -> 0) (\a -> \n -> \x -> a + 2) n x
|
||||||
|
|
||||||
|
-- >>> print (m2 8 ())
|
||||||
|
-- 16
|
||||||
|
--
|
||||||
|
|
||||||
|
e2 :: Integer -> () -> Integer
|
||||||
|
e2 n x = prim (\_ -> 1) (\a -> \n -> \x -> a * 2) n x
|
||||||
|
-- >>> print (e2 4 ())
|
||||||
|
-- 16
|
||||||
|
--
|
||||||
|
|
||||||
|
exp :: Integer -> Integer -> Integer
|
||||||
|
exp x n = prim (\_ -> 1) (\a -> \n -> \x -> a * x) n x
|
||||||
|
-- >>> print (Main.exp 2 3)
|
||||||
|
-- 8
|
||||||
|
--
|
||||||
|
|
||||||
|
fact :: Integer -> () -> Integer
|
||||||
|
fact n x = prim (\_ -> 1) (\a -> \n -> \x -> a * (n + 1)) n x
|
||||||
|
-- >>> print (fact 3 ())
|
||||||
|
-- 6
|
||||||
|
--
|
||||||
|
|
||||||
|
--------------------
|
||||||
|
-- Exercise 2
|
||||||
|
--------------------
|
||||||
|
f g x
|
||||||
|
| x == 0 = g x
|
||||||
|
| otherwise = g $ f g (x - 1)
|
||||||
|
-- Nicht endrekursiv
|
||||||
|
|
||||||
|
length xs = case xs of
|
||||||
|
[] -> 0
|
||||||
|
x : xs -> (+1) $ Main.length xs
|
||||||
|
-- ist endrekursiv
|
||||||
|
|
||||||
|
length' ls = aux
|
||||||
|
$ map ( const 1)
|
||||||
|
$ ls
|
||||||
|
where
|
||||||
|
aux ys = case ys of
|
||||||
|
[] -> 0
|
||||||
|
[x] -> x
|
||||||
|
x : xs -> aux $ map (\y -> (+1) x ) xs
|
||||||
|
-- length' und aux sind nicht endrekursiv
|
||||||
|
|
Loading…
Reference in a new issue