comparison exercises/src/Exercise_2.hs @ 10:50f08a46ea10

week 2 homework
author Markus Kaiser <markus.kaiser@in.tum.de>
date Sun, 11 Nov 2012 20:01:54 +0100
parents f1a337c9f260
children
comparison
equal deleted inserted replaced
9:f4d71c6df64c 10:50f08a46ea10
82 82
83 83
84 84
85 {---------------------------------------------------------------------} 85 {---------------------------------------------------------------------}
86 {- Aufgabe H2.1 -} 86 {- Aufgabe H2.1 -}
87 factorial :: Integer -> Integer
88 factorial 0 = 1
89 factorial n = n * factorial (n - 1)
90
87 factorials :: [Integer] -> [Integer] 91 factorials :: [Integer] -> [Integer]
88 factorials ns = undefined 92 factorials ns = [factorial n | n <- ns, n >= 0]
93
94 prop_factorialsDistrib cs cs' =
95 factorials (cs ++ cs') == factorials cs ++ factorials cs'
96 prop_factorialsOne n = factorials [n] == (if n < 0 then [] else [factorial n])
97 prop_factorialsNil = factorials [] == []
89 98
90 99
91 count :: [Char] -> Char -> Integer 100 count :: [Char] -> Char -> Integer
92 count cs c = undefined 101 count cs c = genericLength [c' | c' <- cs, c' == c]
102
103 count' :: [Char] -> Char -> Integer
104 count' cs c = sum [1 | c' <- cs, c' == c]
93 105
94 106
95 107
96 {---------------------------------------------------------------------} 108 {---------------------------------------------------------------------}
97 {- Aufgabe H2.2 -} 109 {- Aufgabe H2.2 -}
98 lookupTab :: [Integer] -> [(Integer, [Char])] -> [[[Char]]] 110 lookupTab :: [Integer] -> [(Integer, [Char])] -> [[[Char]]]
99 lookupTab keys tab = undefined 111 lookupTab keys tab = [[v | (k,v) <- tab, key == k] | key <- keys]
100 112
101 113
102 114
103 {---------------------------------------------------------------------} 115 {---------------------------------------------------------------------}
104 {- Aufgabe H2.3 -} 116 {- Aufgabe H2.3 -}
105 wordsOfLength :: [Char] -> Integer -> [[Char]] 117 wordsOfLength :: [Char] -> Integer -> [[Char]]
106 wordsOfLength alphabet n = undefined 118 wordsOfLength alphabet 0 = [[]]
119 wordsOfLength alphabet n = [[a] ++ s | a <- alphabet, s <- wordsOfLength alphabet (n - 1)]
107 120
108 121
109 122
110 {---------------------------------------------------------------------} 123 {---------------------------------------------------------------------}
111 {- Aufgabe H2.4 -} 124 {- Aufgabe H2.4 -}
112 {-WETT-}
113 perms :: [Char] -> [[Char]] 125 perms :: [Char] -> [[Char]]
114 perms [] = undefined 126 perms xs | xs == "" = [""]
115 perms xs = undefined 127 | otherwise =
116 {-TTEW-} 128 reverse (sort (nub ([ys ++ [y] |
129 y <- xs, ys <- perms (delete y xs)])))
130
131 perms' :: [Char] -> [[Char]]
132 perms' "" = [""]
133 perms' xs = [ys ++ [y] | y <- sort $ nub xs, ys <- perms' $ delete y xs]
134
135 perms'' :: [Char] -> [[Char]]
136 perms'' "" = [""]
137 perms'' xs = reverse [y : ys | y <- sort $ nub xs, ys <- perms'' $ delete y xs]