F#有foldList函数吗?

Sol*_*lma 4 f# fold

Mathematica也许其他语言也有foldList功能.它非常像fold但不是只返回最终的计算值而是返回每个中间值.

foldList在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
Run Code Online (Sandbox Code Playgroud)

F#中有这样的功能吗?如果没有,是否有比上述更有效的实施?有没有办法避免调用List.rev?

The*_*ght 11

是的,这是一个内置函数,它被称为List.scan:

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

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

要回答有关反转列表的问题,FSharp.Core中的实现可以避免使用突变来反转列表.此可变API未公开公开.如果您有兴趣,可以在这里找到源代码.