Reputation: 15
I have a really simple question, how to execute an operation of addition over each of the lists in a list of lists - containing integers.
So, if I would call this function like this:
add [[1;5] ; [4;3;7]];;
... it should return this:
-: int list = [6;14]
I thought of this code, but it doesn't exactly work right...
let rec add list = match list with
| [] -> []
| hd::tl -> (List.map(fun x -> x + List.hd) hd)::add(tl);;
But this one however, does:
let rec add list =
if (list = []) then []
else (List.map(fun x -> x+x) (List.hd list))::add(List.tl list);;
add [[1;3];[5;7]];;
... but it only performs an operation of addition over a single integer in a list of lists with the very
same integer and yeah, I know why; because I've put: fun x -> x+x ... but shouldn't the map function
also calculate the integers within the lists togheter?
I'm saying this, cause I've used it in a tail recursive manner with ::add(tl list)
By the way, this doesn't work properly even if I use pattern matching...
So to sum it all up, I demand of the function to give me this output:
-: int list = [6;14]
... with the input being this: add [[1;5] ; [4;3;7]];;
Can anyone help? I would be very grateful!
Upvotes: 1
Views: 80
Reputation: 35210
There are two basic operations over containers: folding (aka reducing) and mapping. The fold operation takes the list and applies some operation(s) on its consecutive elements. The map operation rebuilds the list applying the same operation to all its elements.
fold vs. map
x x x x x x x x x x x x x x
| | | |
\ / \ /
y y y y y y y y
For your task we can apply these operations together, i.e., fold the inner lists and map the outer, which could be expressed very concisely in OCaml:
let sums = List.map (List.fold_left (+) 0)
As an exercise, I would suggest implementing the same function without using the standard operations from the List module.
Upvotes: 3