【问题标题】:F# adding listsF# 添加列表
【发布时间】:2018-03-03 23:30:03
【问题描述】:

我将如何添加子列表。

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

【问题讨论】:

  • 我看到你已经改变了你的问题,不再需要第二个元素的总和,而是整个子列表的总和。你能确认预期的结果是[20; 52; 20] ?
  • 是的,没错。谢谢,
  • 好的!我已经编辑了我的答案来处理这个问题

标签: recursion f# sum higher-order-functions


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    方案一:递归版本

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      相关资源
      最近更新 更多