gpt4 book ai didi

f# - F# 有foldList 函数吗?

转载 作者:行者123 更新时间:2023-12-02 09:06:56 25 4
gpt4 key购买 nike

Mathematica 或许其他语言也有 foldList 函数。它非常类似于fold,但它不只返回最终计算值,而是返回每个中间值。

在 F# 中编写 foldList 函数并不难:

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

F#中有这样的函数吗?如果没有,是否有比上面更有效的实现?有没有办法避免调用 List.rev?

最佳答案

是的,这是一个内置函数,它的名字叫List.scan:

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

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

为了回答有关反转列表的问题,FSharp.Core 中的实现避免使用突变来反转列表。这个可变 API 不公开。可以找到源码here如果你有兴趣。

关于f# - F# 有foldList 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42773779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com