首页 > 解决方案 > f# 中的 'seq<'a>' 类型是什么?

问题描述

我是 F#(python 程序员)的新手,对我遇到的错误感到非常困惑。我有一个练习来计算 Nilakantha 系列的无限序列(pi 估计)。到目前为止,这是我的代码:

   let piSeq x =
      let sum = 0m
      let bool = true
      let calculation x = (4m / (2m*x*(2m*x+1m)*(2m*x+2m)))
      seq {
         for b in 0..x do
            let x = x |> decimal
            if b=0 then let sum = sum + 3m
                        yield sum
            else if bool = true
                 then let sum = sum + (calculation x)
                      let bool = false
                      yield sum
                 else let sum = sum - (calculation x)
                      let bool = true
                      yield sum

      }

    Seq.iter (printf "%A ") (Seq.take 1000 piSeq)

这段代码给了我以下错误:

error FS0001: The type 'int -> seq<int>' is not compatible with the type 'seq<'a>'

我的问题是,什么是'seq<'a>'?我怎样才能将 int 转换为 'a,所以这段代码不会失败?

谢谢!

标签: typesf#

解决方案


seq<'a>System.Collections.Generic.IEnumerable<T>. 您可能会找到更多面向 C# 的文档。请参阅https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.ienumerable-1?view=netcore-3.1

这表示可以是任何类型'a的类型值序列。'a这意味着您可以迭代这些值,但您不能对集合做出其他假设。所有其他 .NET 集合都继承自seq. Aseq可以是“物化”列表或数组,也可以是从某处获取值的“惰性”生成器。您甚至可以使用它来创建无限序列。

您看到的错误消息是说接受int参数并返回 a seq<int>( int -> seq<int>) 的函数与 a 不同seq<'a>


推荐阅读