f# 运行总计序列
好吧,这看起来应该很容易,但我就是不明白。如果我有一个数字序列,如何生成由运行总计组成的新序列?例如,对于序列 [1;2;3;4],我想将其映射到 [1;3;6;10]。以适当的功能方式。
Ok, this looks like it should be easy, but I'm just not getting it. If I have a sequence of numbers, how do I generate a new sequence made up of the running totals? eg for a sequence [1;2;3;4], I want to map it to [1;3;6;10]. In a suitably functional way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
List.scan
:基于
Seq.scan
的实现:Use
List.scan
:Seq.scan
-based implementation:另一种使用
Seq.scan
的变体(Seq.skip 1
去掉了前导零):Another variation using
Seq.scan
(Seq.skip 1
gets rid of the leading zero):使用列表:
编辑:序列的另一种方式:
是的,有一个可变变量,但我发现它更具可读性(如果你想去掉前导 0)。
With lists:
Edit: Another way with sequences:
Yes, there's a mutable variable, but I find it more readable (if you want to get rid of the leading 0).
我认为值得分享如何使用 记录类型< /a> 如果这也是您来这里寻找的东西。
下面是一个虚构的示例,使用跑步者绕跑道跑一圈来演示这一概念。
Figured it was worthwhile to share how to do this with Record Types in case that's also what you came here looking for.
Below is a fictitious example demonstrating the concept using runner laps around a track.
不确定这是最好的方法,但它应该可以解决问题
Not sure this is the best way but it should do the trick