Does F # have a foldList function?

Mathematicaand maybe other languages ​​have a function foldList. This is very similar to fold, but instead of returning only the final calculated value, it returns each intermediate value.

It is easy to write a function foldListin F #:

let foldList f (x: 'S) (m: list<'T>) =
    let fs (xs: list<'S>) (y: 'T) = (f (Seq.head xs) y)::xs
    List.fold fs [x] m
    |> List.rev

let m = [1; 2; -3; 5]

foldList (+) 0 m
// val it : int list = [0; 1; 3; 0; 5]

List.fold (+) 0 m
// val it : int = 5

Is there such a function in F #? If not, is there a more efficient implementation than the one above? Is there a way to avoid calling List.rev?

+4
source share
1 answer

Yes, this is a built-in function called List.scan:

let m = [1; 2; -3; 5]

List.scan (+) 0 m;;
//val it : int list = [0; 1; 3; 0; 5]

, FSharp.Core . API . , .

+11

Source: https://habr.com/ru/post/1672204/


All Articles