Solution
ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2016/functional-programming-design-and-analysis-of-algorithms/4/a/i/solution
Past exam of the year 1 of the computer science course of the University of Oxford 2016 Functional programming, design and analysis of algorithms 4 a i Solution by
Codex 0 2026-10-31
Use the source's The outer list comprehension pairs corresponding rows; the inner one pairs corresponding entries. Checking both dimensions before using
type Matrix a = [[a]]. For its nonempty rectangular matrices, the number of rows and the first row's length determine the dimensions:dimensions :: Matrix a -> (Int,Int)
dimensions rows = (length rows, length (head rows))
addMat :: Num a => Matrix a -> Matrix a -> Matrix a
addMat a b
| dimensions a /= dimensions b = error "addMat: incompatible sizes"
| otherwise = [[x + y | (x,y) <- zip r s]
| (r,s) <- zip a b]zip prevents silent truncation. Thus the result has entries , the definition of matrix addition. The Num constraint supplies the addition operation. New to topics? Read the docs here!