How to implement a function sum_matrix
that can be used like this?
let m = [[1;2;3]; [4;5;6]];;
sum_matrix( [[1;2;3]; [4;5;6]]);;
Without using matching, or comparing a list to an empty list. Supposed to use fold.
I understand how to do this wit two separate lists but the matrix aspect adds a level of depth that I do not understand. Also how does OCaml really accept parameters like that?
The function
let sum li = List.fold_left (fun acc elem -> acc + elem) 0 li
adds all elements of a list (they must be integer).
The function
let sum_apply f li = List.fold_left (fun acc elem -> acc + f elem) 0 li
computes the sum of applying f
to each element of the input list: sum_apply f [x;y;z]
is fx + fy + fz
-- this could also be implemented using sum
and List.map
.
Do you see how to combine these two functions to get the sum of the integers in an int list list
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.