开发者

Looking for F# library function similar to map that will pass to f the current state of the computation

开发者 https://www.devze.com 2023-04-02 01:02 出处:网络
I wonder if there is some function in the F# libraries similar to this one? let map_acc (f:int->int) (list:int list) =

I wonder if there is some function in the F# libraries similar to this one?

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

Usage:

let xxx = map_acc id [1.开发者_开发知识库.10]

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

Its purpose is quite similar to map's but it passes the current state (in the given case, an accumulator) to each element of the list.


Yes, List.scan is the missing key you seek:

[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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号