[英]seq<obj> versus seq<float> in F#
I have the following method: 我有以下方法:
member this.addColumnWithHeading heading column =
this.addColumn (seq { yield heading; yield! (column |> Seq.map string)})
which takes a string heading and any sequence (which is compiled to seq in this case), creates a sequence of strings and calls another method with this data. 它采用字符串标题和任何序列(在本例中为seq),创建一个字符串序列并使用此数据调用另一个方法。 However, it doesn't work with column being a sequence of floats:
但是,它不适用于列为浮点数的列:
Error 1 The type 'obj' does not match the type 'float' C:\Users\ga1009\Documents\PhD\cpp\pmi\fsharp\pmi\Program.fs 138
How can I define the method addColumnWithHeading
so that it works with floats as well? 如何定义方法
addColumnWithHeading
,使其也可以与浮点数一起使用?
The built-in string
function is an inline function which uses a statically-resolved generic parameter; 内置
string
函数是一个内联函数,它使用静态解析的泛型参数; since your addColumnWithHeading
method is not declared inline
, the F# type inference has to assume the values in the sequence are of type obj
. 由于您的
addColumnWithHeading
方法未声明为inline
,因此F#类型推断必须假定序列中的值是obj
类型。
There's a simple solution though -- swap out the string
function in favor of "manually" calling .ToString()
on the values in the sequence. 不过,有一个简单的解决方案-换出
string
函数,而以“手动”方式对序列中的值调用.ToString()
。 If you do that, F# will be able to use a standard generic parameter type for the sequence so you can pass a sequence of any type you desire. 如果这样做,F#将能够为序列使用标准的通用参数类型,因此您可以传递所需的任何类型的序列。
member this.addColumnWithHeading heading column =
seq {
yield heading
yield! Seq.map (fun x -> x.ToString()) column }
|> this.addColumn
string
is inlined so its argument type has to be resolved at compile-time. string
是内联的,因此必须在编译时解析其参数类型。 Since your member is not inlined it picks the most general type it can ( obj
in this case). 由于您的成员未进行内联,因此会选择可以使用的最通用类型(在这种情况下为
obj
)。 Inlining your method will allow column
to remain generic. 内联方法将使
column
保持通用。
member inline x.AddColumnWithHeading(heading, column) =
x.AddColumn(seq { yield heading; yield! Seq.map string column })
EDIT 编辑
Per the comments to Jack's answer, you might not need to inline your use of string
. 根据对杰克答案的评论,您可能不需要内联使用
string
。 Certainly, if column
will always be seq<float>
you should just add a type annotation. 当然,如果
column
始终为seq<float>
,则只需添加类型注释。 Passing seq<string>
and moving the string conversion outside the function is another option. 传递
seq<string>
并将字符串转换移到函数之外是另一种选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.