Grundlagen der Funktionalen Programmierung: Rekursive Funktionen |
|
|
|
1module RecFct where
2
3import Prelude hiding ( length
4 , product
5 , reverse
6 , zip
7 , even
8 , odd
9 )
10
11import qualified Prelude as P
12
13factorial :: Integer -> Integer
14factorial n
15 | n == 0 = 1
16 | n > 0 = n * factorial (n - 1)
17
18
19(.*.) :: Int -> Int -> Int
20m .*. n
21 | n == 0 = 0
22 | n > 0 = m + (m .*. (n - 1))
23
24product :: Num a => [a] -> a
25product [] = 1
26product (n : ns) = n * product ns
27
28length :: [a] -> Int
29length [] = 0
30length (x : xs) = 1 + length xs
31
32reverse :: [a] -> [a]
33reverse [] = []
34reverse (x : xs) = reverse xs ++ [x]
35
36(.++.) :: [a] -> [a] -> [a]
37[] .++. ys = ys
38(x : xs) .++. ys = x : (xs .++. ys)
39
40insert :: Ord a => a -> [a] -> [a]
41insert x [] = [x]
42insert x (y : ys)
43 | x <= y = x : y : ys
44 | otherwise = y : insert x ys
45
46isort :: Ord a => [a] -> [a]
47isort [] = []
48isort (x : xs) = insert x (isort xs)
49
50zip :: [a] -> [b] -> [(a, b)]
51zip [] _ = []
52zip _ [] = []
53zip (x : xs) (y : ys) = (x,y) : zip xs ys
54
55numberLines :: [b] -> [(Int, b)]
56numberLines xs = zip [1..length xs] xs
57
58fib :: Integer -> Integer
59fib 0 = 0
60fib 1 = 1
61fib n = fib (n - 1) + fib (n - 2)
62
63even :: Integer -> Bool
64even 0 = True
65even n = odd (n - 1)
66
67odd :: Integer -> Bool
68odd 0 = False
69odd n = even (n - 1)
70
71-- --------------------
72
73type Coins = [Int]
74
75change :: Int -> Coins -> [Coins]
76change n cs
77 | n < 0 = []
78 | n == 0 = [[]]
79 | n > 0 = change' cs
80 where
81 change' [] = []
82 change' (c : cs1) = [c : xs | xs <- change (n - c) cs]
83 ++
84 change n cs1
85
86numChanges :: Int -> Coins -> Int
87numChanges n cs = length (change n cs)
88
89change1cent :: [Coins]
90change1cent = change 1 [50, 20, 10, 5, 2, 1]
91
92change2cent :: [Coins]
93change2cent = change 2 [50, 20, 10, 5, 2, 1]
94
95change10cent :: [Coins]
96change10cent = change 10 [50, 20, 10, 5, 2, 1]
97
98change1euro :: Int
99change1euro = numChanges 100 [50, 20, 10, 5, 2, 1]
100
101-- tests
102
103test1 :: Int -> Coins -> Bool
104test1 n cs = all sumEqualsN (change n cs)
105 where
106 sumEqualsN xs = sum xs == n
107
108test2 :: Int -> Coins -> Bool
109test2 n cs = all legalCoins (change n cs)
110 where
111 legalCoins xs = all (`elem` cs) xs
|
Letzte Änderung: 24.11.2020 | © Prof. Dr. Uwe Schmidt |