【问题标题】:Looking for F# library function similar to map that will pass to f the current state of the computation寻找类似于 map 的 F# 库函数,它将传递给 f 计算的当前状态
【发布时间】:2011-09-04 06:09:52
【问题描述】:

不知道F#库中是否有类似这个的函数?

let map_acc (f:int->int) (list:int list) =
  let rec map_acc' f acc = function
    | []   -> []
    | h::t -> (f (h+acc))::(map_acc' f (h+acc) t)
  map_acc' f 0 list

用法:

let xxx = map_acc id [1..10]

val xxx : int list = [1; 3; 6; 10; 15; 21; 28; 36; 45; 55]

它的用途与map 非常相似,但它将当前状态(在给定的情况下,是一个累加器)传递给列表的每个元素。

【问题讨论】:

    标签: .net f# functional-programming


    【解决方案1】:

    是的,List.scan 是您寻找的缺失键:

    [1..10]
    |> List.scan (+) 0
    |> List.tail //skip the seed value, 0
    |> List.map id //of course, map id is not useful, but just illustration here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多