F# - 从序列中返回元素

时间:2016-05-10 08:57:49

标签: f# seq

尾翼-警报!您将看到projecteuler.net-Problem 7的解决方案。

如果这是重复的话,我很抱歉,但我在这里找不到问题。

我在函数中计算一系列数字,并希望返回第n个数字。

let isPrime x = 
    {2..x/2}
    |> Seq.exists (fun e -> x%e=0)
    |> not

let PrimeNumber nth = 
    let unfolder a =
        a
        |> Seq.unfold (fun e -> Some(e, e+1))
        |> Seq.find isPrime
        |> fun e -> Some(e, e)

    2
    |> Seq.unfold unfolder
    |> Seq.skip (nth-1) 
    |> Seq.head

let ans = PrimeNumber 10001

ans永远是2,但为什么?

当我使用PrimeNumber评估nth=10001中的最后一个表达式时,会返回正确的项目。我错过了什么吗?

2 个答案:

答案 0 :(得分:2)

问题在于您使用Seq.find。

Seq.find,从文档中返回条件为true的第一个元素。在这种情况下,那就是2.

因此,你的unfolder表达式只会生成一个2s的无限序列,所以无论你采用什么元素,它总是2。

要查看此内容,请运行代码片段:

2
|> Seq.unfold unfolder

//output: val it : seq<int> = seq [2; 2; 2; 2; ...]

答案 1 :(得分:2)

如果你需要坚持这个解决方案,你需要Seq.filter:

let isPrime x = 
{2..x/2}
|> Seq.exists (fun e -> x%e=0)
|> not

let PrimeNumber nth = 
    let unfolder a =
       a
       |> Seq.unfold (fun e -> Some(e, e+1))
       |> Seq.filter isPrime

    2
    |> unfolder
    |> Seq.skip (nth-1) 
    |> Seq.item 0

let ans = PrimeNumber 100会给你541 但是在评论中没有提到其他更有效的解决方案。