seq< obj>与seq< float>在F#中 [英] seq<obj> versus seq<float> in F#

查看:90
本文介绍了seq< obj>与seq< float>在F#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

  member this.addColumnWithHeading heading column =
    this.addColumn (seq { yield heading; yield! (column |> Seq.map string)})

接受字符串标题和任何序列(在本例中为seq),创建一个字符串序列并使用此数据调用另一个方法.但是,它不适用于列为浮点数的列:

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. 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

如何定义方法addColumnWithHeading,使其也可以与浮点数一起使用?

How can I define the method addColumnWithHeading so that it works with floats as well?

推荐答案

内置的string函数是内联函数,它使用静态解析的泛型参数;由于您的addColumnWithHeading方法未声明为inline,因此F#类型推断必须假定序列中的值的类型为obj.

The built-in string function is an inline function which uses a statically-resolved generic parameter; since your addColumnWithHeading method is not declared inline, the F# type inference has to assume the values in the sequence are of type obj.

尽管有一个简单的解决方案-换出string函数,而有利于手动"调用序列中的值的.ToString().如果这样做,F#将能够为序列使用标准的通用参数类型,以便您可以传递所需的任何类型的序列.

There's a simple solution though -- swap out the string function in favor of "manually" calling .ToString() on the values in the sequence. 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.

member this.addColumnWithHeading heading column =
    seq {
        yield heading
        yield! Seq.map (fun x -> x.ToString()) column }
    |> this.addColumn

这篇关于seq< obj>与seq< float>在F#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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