solutions block 2

main
Jonathan Seltmann 2025-02-06 11:02:53 +01:00
parent 0238f3ca3c
commit babff7d797
3 changed files with 86 additions and 0 deletions

View File

@ -0,0 +1,31 @@
-- Lösung: Fibonacci-Funktion mit Tail-Rekursion
fibonacciTail :: Integer -> Integer -> Integer -> Integer
fibonacciTail 0 a _ = a
fibonacciTail n a b = fibonacciTail (n - 1) b (a + b)
fibonacci :: Integer -> Integer
fibonacci n = fibonacciTail n 0 1
-- Testfälle
test1 = fibonacci 0 == 0
test2 = fibonacci 1 == 1
test3 = fibonacci 2 == 1
test4 = fibonacci 3 == 2
test5 = fibonacci 5 == 5
test6 = fibonacci 10 == 55
test7 = fibonacci 15 == 610
test8 = fibonacci 20 == 6765
-- Hauptfunktion zum Testen
main :: IO ()
main = do
putStrLn "Teste Fibonacci-Funktion mit Tail-Rekursion..."
print test1
print test2
print test3
print test4
print test5
print test6
print test7
print test8

View File

@ -0,0 +1,24 @@
-- Lösung: Rekursive Implementierung der map-Funktion
-- Funktionssignatur
-- Lösung: Rekursive Implementierung der map-Funktion
-- Funktionssignatur
myMap :: (a -> b) -> [a] -> [b]
myMap _ [] = []
myMap f (x:xs) = f x : map f xs
-- Testfälle
test1 = myMap (*2) [1,2,3] == [2,4,6]
test2 = myMap show [1,2,3] == ["1", "2", "3"]
test3 = myMap (+1) [] == []
test4 = myMap (const "a") [1,2,3] == ["a", "a", "a"]
-- Hauptfunktion zum Testen
main :: IO ()
main = do
putStrLn "Teste map-Funktion..."
print test1
print test2
print test3
print test4

View File

@ -0,0 +1,31 @@
-- Rekursive Funktion myZip
myZip :: [a] -> [b] -> [(a, b)]
myZip [] _ = []
myZip _ [] = []
myZip (x:xs) (y:ys) = (x, y) : myZip xs ys
-- Testfälle mit `null` und expliziten Typannotationen
test1 :: Bool
test1 = myZip [1,2,3] ['a', 'b', 'c'] == [(1, 'a'), (2, 'b'), (3, 'c')]
test2 :: Bool
test2 = myZip [1,2] ["eins", "zwei", "drei"] == [(1, "eins"), (2, "zwei")]
test3 :: Bool
test3 = myZip [True, False] [1,2,3] == [(True,1), (False,2)]
test4 :: Bool
test4 = null (myZip [] [1,2,3])
test5 :: Bool
test5 = null (myZip [1,2,3] [])
-- Hauptfunktion zum Testen
main :: IO ()
main = do
putStrLn "Teste zip-Funktion..."
print test1
print test2
print test3
print test4
print test5