方案一:递归版本
我们需要一个辅助函数来通过一对一地求和元素来添加两个列表。它是递归的,并假设两个列表的长度相同:
let rec sum2Lists (l1:List<int>) (l2:List<int>) =
match (l1,l2) with
| ([],[]) -> []
| (x1::t1, x2::t2) -> (x1+x2)::sum2Lists t1 t2
然后下面的递归函数可以使用我们的辅助函数来处理列表列表:
let rec sumLists xs =
match xs with
| [] -> [] // empty list
| x1::[] -> x1 // a single sublist
| xh::xt -> sum2Lists xh (sumLists xt) // add the head to recursion on tail
let myres = sumLists mylist
方案二:高阶函数
我们的辅助函数可以被简化,使用 List.map2:
let sum2hfLists (l1:List<int>) (l2:List<int>) = List.map2 (+) l1 l2
然后我们可以使用 List.fold 来使用我们的辅助函数在流量累加器上创建一个:
let sumhfList (l:List<List<int>>) =
match l with
| [] -> [] // empty list of sublist
| h::[] -> h // list with a single sublist
| h::t -> List.fold (fun a x -> sum2hfLists a x) h t
最后一个匹配情况仅适用于至少有两个子列表的列表。诀窍是将第一个子列表作为累加器的起点,然后让fold 对列表的其余部分执行。