Question
The following question is in OCMAL Suppose we represent vectors v = (vi) as lists of numbers, and matrices m = (mij) as lists of
The following question is in OCMAL
Suppose we represent vectors v = (vi) as lists of numbers, and matrices m = (mij) as lists of vectors (the rows of the matrix). For example, the 3x4 matrix:
+---------+ | 1 2 3 4 | | 4 5 6 6 | | 6 7 8 9 | +---------+
is represented as the list of lists [[1;2;3;4];[4;5;6;6];[6;7;8;9]]. With this representation, we can use list operations to concisely express the basic matrix and vector operations. These operations (which are described in any book on matrix algebra) are the following:
dot_product v w (* returns: the number d, where d = sum_i (v_i * w_i) *) matrix_times_vector m v (* returns: the vector t, where t_i = sum_j (m_ij * v_j) *) matrix_times_matrix m n (* returns: the matrix p, where p_ij = sum_k (m_ik * n_kj) *) transpose m (* returns: the matrix n, where n_ij = m_ji *)
We can define the dot product as:
let dot_product v w = accumulate (+) 0 (map2 ( * ) v w)
where map2 is a version of map which maps a two-argument function (or operator) over two lists of equal lengths, returning a list of that length.
Fill in the missing expressions in the following functions for computing map2 and the other matrix operations. (The function accumulate_n was defined in the previous problem.)
let rec map2 f x y = match (x, y) with | ([], []) -> [] | ([], _) -> failwith "unequal lists" | (_, []) -> failwith "unequal lists" | ?> let matrix_times_vector m v = map ?> m let transpose mat = accumulate_n ?> ?> mat let matrix_times_matrix m n = let cols = transpose n in map ?> m
Examples
# dot_product [] [] ;; - : int = 0 # dot_product [1;2;3] [4;5;6] ;; - : int = 32 # matrix_times_vector [[1;0];[0;1]] [10;20] ;; - : int list = [10; 20] # matrix_times_vector [[1;2];[3;4]] [-2;3] ;; - : int list = [4; 6] # transpose [[1;2];[3;4]] ;; - : int list list = [[1; 3]; [2; 4]] # transpose [[1;2;3];[4;5;6]] ;; - : int list list = [[1; 4]; [2; 5]; [3; 6]] # matrix_times_matrix [[1;0];[0;1]] [[1;2];[3;4]] ;; - : int list list = [[1; 2]; [3; 4]] # matrix_times_matrix [[1;2];[3;4]] [[1;2];[3;4]] ;; - : int list list = [[7; 10]; [15; 22]] # matrix_times_matrix [[1;2;3];[4;5;6]] [[1;2];[3;4];[5;6]] ;; - : int list list = [[22; 28]; [49; 64]]
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started