A Haskell Practice with Answer

Last updated on May 24, 2023 pm

A Haskell Practice with Answer

The problem sheet can be found here.

(a)

1
2
m2 :: Matrix
m2 = Row [1.2, -1.0] (Row [4.5, -0.9] (Row [2.3, 1.8] Null))

(b)

1
2
3
4
5
6
7
8
legitMatrix :: Matrix -> Bool
legitMatrix Null = True
legitMatrix (Row row rest) = sameLength (length row) rest
    where
        isEnd Null = True
        isEnd _ = False
        sameLength len Null = True
        sameLength len (Row row rest) = length row == len && sameLength len rest

(c)

1
2
3
4
5
6
7
8
sizeMatrix :: Matrix -> (Int, Int)
sizeMatrix Null = (0, 0)
sizeMatrix (Row row rest) = (x, y)
where
y = length row
x = 1 + columnSize rest
columnSize Null = 0
columnSize (Row row rest) = 1 + columnSize rest

(d)

1
2
3
insertColumn :: Matrix -> [Float] -> Matrix
insertColumn Null [] = Null
insertColumn (Row row rest) (x:xs) = Row ([x] ++ row) (insertColumn rest xs)

(e)

An empty matrix which have 3 empty row, each row is a empty list.

(f)

1
2
3
4
5
6
7
8
9
10
11
insertColumnRight :: Matrix -> [Float] -> Matrix
insertColumnRight Null [] = Null
insertColumnRight (Row row rest) (x:xs) = Row (row ++ [x]) (insertColumnRight rest xs)

transposeMatrix :: Matrix -> Matrix
transposeMatrix m = helper m e
    where
        (_, y) = sizeMatrix m
        e = emptyMatrix y
        helper Null new = new
        helper (Row row rest) new = helper rest (insertColumnRight new row)

Better one:

1
2
3
transposeMatrix :: Matrix -> Matrix
transposeMatrix (Row a Null) = insertColumn (emptyMatrix (length a)) a
transposeMatrix (Row a b) = insertColumn (transposeMatrix b) a

(g)

1
2
3
4
5
6
7
addRows :: [Float] -> [Float] -> [Float]
addRows xs ys = [fst item + snd item | item <- zip xs ys]

-- addRows xs ys = [xs !! i + ys !! i | i <- index]
-- where
-- len = length xs
-- index = take len [0..]

(h)

1
2
3
4
(+#+) :: Matrix -> Matrix -> Matrix
(+#+) x Null = x
(+#+) Null x = x
(+#+) (Row row1 rest1) (Row row2 rest2) = Row (addRows row1 row2) ((+#+) rest1 rest2)

(i)

1
2
3
4
5
(+##+) :: Matrix -> Matrix -> Maybe Matrix
(+##+) x y
    | not (legitMatrix x) || not (legitMatrix y) = Nothing
    | sizeMatrix x /= sizeMatrix y = Nothing
    | otherwise = Just ((+#+) x y)

(j)

1
2
3
4
5
6
7
8
9
10
11
12
showMatrix :: Matrix -> IO()
showMatrix Null = putStr ""
showMatrix (Row row rest) =
do
putStr "["
putStr (display row)
putStrLn "]"
showMatrix rest
where
display row
| length row == 1 = show (head row)
| otherwise = show (head row) ++ "\t" ++ display (tail row)

A Haskell Practice with Answer
https://lingkang.dev/2023/05/25/hs-practice/
Author
Lingkang
Posted on
May 24, 2023
Licensed under