F#添加列表

问题描述 投票:1回答:2

我该如何添加子列表?

例如,[ [10;2;10]; [10;50;10]] ----> [20;52;20]为10 + 10,2 + 50和10 + 10。不知道如何开始这个。

recursion f# sum higher-order-functions
2个回答
1
投票

Solution 1: Recursive version

我们需要一个辅助函数来通过一对一求和元素来添加两个列表。它是递归的,并假设两个列表具有相同的长度:

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

Solution 2: higher order function

使用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在列表的其余部分执行。


2
投票

折叠是一个更高阶函数:

let input = [[10;2;10]; [10;50;10]]
input |> Seq.fold (fun acc elem -> acc + (List.nth elem 1)) 0

val it : int = 52
© www.soinside.com 2019 - 2024. All rights reserved.