F#添加列表

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了F#添加列表相关的知识,希望对你有一定的参考价值。

我该如何添加子列表?

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

答案

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

另一答案

折叠是一个更高阶函数:

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

val it : int = 52

以上是关于F#添加列表的主要内容,如果未能解决你的问题,请参考以下文章

从其他片段添加新的 RecyclerView 项

使用导航架构组件添加(而不是替换)片段

哈斯克尔。我很困惑这个代码片段是如何工作的

如何将本地存储中的 JSON 对象添加到 Android Studio 上的片段列表

添加片段后,前一个片段仍然可见

如何在列表视图中添加最近播放的歌曲?