Arrays 如何在F中定义不同签名的函数数组#

Arrays 如何在F中定义不同签名的函数数组#,arrays,function,f#,Arrays,Function,F#,我希望能够使用以下一系列函数: type SomeFunc = | StringFunc of (int -> string) | DecimalFunc of (int -> decimal) let dataCols = Dict<string, SomeFunc>() dataCols["A"] <- fun x -> sprintf "%d" x dataCols["B"] <- fun x -> decimal x // would

我希望能够使用以下一系列函数:

type SomeFunc =
| StringFunc  of (int -> string)
| DecimalFunc of (int -> decimal)

let dataCols = Dict<string, SomeFunc>()
dataCols["A"] <- fun x -> sprintf "%d" x
dataCols["B"] <- fun x -> decimal x

// would want to have:
(dataCols["A"] 0) // "0"
(dataCols["B"] 0) // 0M
键入SomeFunc=
|(int->string)的StringFunc
|十进制数(整数->十进制)
设dataCols=Dict()
dataCols[“A”]sprintf“%d”x
数据列[“B”]十进制x
//我们希望:
(数据列[“A”]0)/“0”
(dataCols[“B”]0)//0M

我如何用有效的F#code来表达这个想法呢?

第一件事是,在将函数放入字典时,需要将它们包装在
StringFunc
DecimalFunc
中:

let dataCols = Dictionary<string, SomeFunc>()
dataCols["A"] <- StringFunc(fun x -> sprintf "%d" x)
dataCols["B"] <- DecimalFunc(fun x -> decimal x)
然后您可以使用
调用
帮助程序:

call (dataCols["A"]) 0
call (dataCols["B"]) 0

装箱意味着您将返回
obj
,但如果不了解您的具体情况,很难说什么是处理此问题的最佳方法。

从您的代码中,我得到的印象是输入类型总是相同的(示例中为int),以便能够调用任何列而不知道其类型

如果是这样,您可能希望将DU用于返回类型,而不是函数类型。这样,您将获得您想要的呼叫行为

type ColumnValue =
| StringValue of string
| DecimalValue of decimal

let dataCols = Dictionary<string, (int -> ColumnValue)>()
dataCols.["A"] <- fun x -> StringValue (sprintf "%d" x)
dataCols.["B"] <- fun x -> DecimalValue (decimal x)

// what you get
dataCols.["A"] 0 // (StringValue "0")

match (dataCols.["A"] 0) with
| StringValue s -> printf "%s" s
| DecimalValue d -> printf "%M" d
类型列值=
|字符串值
|十进制小数
让dataCols=字典列值)>()
dataCols。[“A”]StringValue(sprintf“%d”x)
数据列。[“B”]小数值(十进制x)
//你得到了什么
数据列。[“A”]0/(StringValue“0”)
将(数据列。[“A”]0)与
|字符串值s->printf“%s”s
|小数点d->printf“%M”d

这本质上是我的出发点,也是我想要隐藏在类似数组的语法(或任何更好的方法)后面的内容,因为它在我的用例中变得笨拙。
type ColumnValue =
| StringValue of string
| DecimalValue of decimal

let dataCols = Dictionary<string, (int -> ColumnValue)>()
dataCols.["A"] <- fun x -> StringValue (sprintf "%d" x)
dataCols.["B"] <- fun x -> DecimalValue (decimal x)

// what you get
dataCols.["A"] 0 // (StringValue "0")

match (dataCols.["A"] 0) with
| StringValue s -> printf "%s" s
| DecimalValue d -> printf "%M" d