简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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