Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Functional Programming
diff options
context:
space:
mode:
Commit7f49623f30288f7995335fc257f0496052a4d819 (patch)
Author
 Syndamia <kamen@syndamia.com>
2023-01-13 18:14:40 +0200
Committer
 Syndamia <kamen@syndamia.com>
2023-01-13 18:14:40 +0200
Files04187fc7431e3bdbeeebbdb351e0372c5ea29433 /Year 2/Functional Programming
uni-projects-7f49623f30288f7995335fc257f0496052a4d819.tar
uni-projects-7f49623f30288f7995335fc257f0496052a4d819.tar.gz
uni-projects-7f49623f30288f7995335fc257f0496052a4d819.zip
Parent4f813adb042926e2bd87213a7d5939328dbadce8 (diff)
[FP] Solved second exam from 2022
1 files changed, 64 insertions, 0 deletions
-rw-r--r--Year 2/Functional Programming/Exam2-2022.hs64
diff --git a/Year 2/Functional Programming/Exam2-2022.hs b/Year 2/Functional Programming/Exam2-2022.hs
new file mode 100644
index 0000000..5f18783
--- /dev/null
+++ b/Year 2/Functional Programming/Exam2-2022.hs
@@ -0,0 +1,64 @@
+import Data.Char
+import Data.List
+
+-- Exercise 1
+
+squareDigits :: Int -> Int
+squareDigits n = read (foldr (++) "" (map (\c -> if not (c == '-') then show ((digitToInt c)^2) else c : "") (show n)))
+
+-- Exercise 2
+
+data Stock = Stock String Int
+
+stocklist :: [Stock] -> [Char] -> [(Char,Int)]
+stocklist [] _ = []
+stocklist _ [] = []
+stocklist l m = map (\cat -> (cat, foldr (\(Stock c n) acc -> if cat == head c then acc + n else acc) 0 l)) m
+
+-- Exercise 3
+
+matching :: String -> [(Int, Int)]
+matching s = calc s 0 []
+ where
+ calc [] _ _ = []
+ calc s i stack
+ | head s == '[' = calc (tail s) (i + 1) (i : stack)
+ | head s == ']' = (head stack, i) : (calc (tail s) (i + 1) (tail stack))
+ | otherwise = calc (tail s) (i + 1) stack
+
+-- Exercise 4
+
+data BTree a = Nil | Node a (BTree a) (BTree a)
+
+nodeCount :: BTree a -> Int
+nodeCount Nil = 0
+nodeCount (Node _ t1 t2) = 1 + nodeCount t1 + nodeCount t2
+
+treeHeight :: BTree a -> Int
+treeHeight Nil = 0
+treeHeight (Node _ t1 t2) = 1 + max (treeHeight t1) (treeHeight t2)
+
+isPerfectlyBalanced :: BTree a -> Bool
+isPerfectlyBalanced t = nodeCount t == (2^treeHeight t) - 1
+
+main :: IO()
+main = do
+ print(squareDigits 9119)
+ print(squareDigits (-9119))
+
+ let stocks = [Stock "ABAR" 200, Stock "CDXE" 500, Stock "BKWR" 250, Stock "BTSQ" 890, Stock "DRTY" 600]
+ print(stocklist stocks ['A','B']) -- ➝ [('A',200),('B',1140)]
+ print(stocklist stocks ['C','X']) -- ➝ [('C',500),('X',0)]
+ print(stocklist stocks ['Y','X']) -- ➝ [('Y',0),('X',0)]
+ print(stocklist stocks ['C']) -- ➝ [('C', 500)]
+
+ print(matching "1234") -- ➝ []
+ print(matching ",[.[-],]") -- ➝ [(3,5),(1,7)]
+ print(matching ",+[-.,+]") -- ➝ [(2,7)]
+ print(matching "[][]") -- ➝ [(0,1),(2,3)]
+
+ let t1 = Node 'H' (Node 'a' (Node 'k' Nil Nil)
+ (Node 'e' Nil Nil))
+ (Node 's' (Node 'l' Nil Nil)
+ (Node 'I' Nil Nil))
+ print(isPerfectlyBalanced t1) -- == True