F#中的Seq.unfold解释 [英] Seq.unfold explanation in F#

查看:108
本文介绍了F#中的Seq.unfold解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过使用F#懒惰地创建一个序列.

I am trying to create a sequence lazily by using F#.

序列定义如下:

序列的第n个项 三角数由下式给出:tn = ½n(n + 1);所以前十个三角形 数字是:

The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:

1、3、6、10、15、21、28、36、45、55, ...

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

这是我到目前为止所拥有的,但似乎不起作用:

Here is what I have so far but it dosn't seem to work:

let tri_seq = 1.0 |> Seq.unfold (fun x -> match x with                                         
                                          | _ -> Some (x, 0.5*x*(x + 1.0)))

非常感谢谁能帮助我弄清楚展开的工作原理.谢谢

Thank you very much who can help me figure out how unfold works. Thanks

编辑:我将第一个答案标记为正确,但是没有用,但是我对其做了一些修改,就可以了.

I marked the first answer as correct but it dosnt work, however I slightly modified it and it worked.

let tri_seq = 1.0 |> Seq.unfold (fun x -> Some (0.5 * x * (x + 1.0),x + 1.0))

推荐答案

首先,如果只有一个案例,为什么要使用match?

First off, why do you use match if you've got only one case?

let tri_seq = 1.0 |> Seq.unfold (fun x -> Some (x, 0.5 * x * (x + 1.0)))

第二,似乎无效"是什么?您知道您产生了一个无限列表吗?

Second, what "doesn't seem to work"? Are you aware that you produce an infinite list?

/为完整起见,这是正确的解决方案,OP找到了自己的解决方案并将其发布为评论:

/ For completeness’ sake, here’s the correct solution, which the OP found himself and posted as a comment:

let tri_seq = 
    1.0 |> Seq.unfold (fun x -> Some (0.5 * x * (x + 1.0), x + 1.0))

这篇关于F#中的Seq.unfold解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆