繁体   English   中英

F#添加列表

[英]F# adding lists

我该如何添加子列表?

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

折叠是一个更高阶函数:

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

val it : int = 52

解决方案1:递归版本

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

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

解决方案2:更高阶函数

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM