【发布时间】:2017-10-23 14:16:48
【问题描述】:
我有一个有区别的联合类型的表单
type ParameterName = string
type ParameterValues =
| String of string[]
| Float of float[]
| Int of int[]
type Parameter = Parameter of ParameterName * ParameterValues
我想将 ParameterValues 部分传递给采用通用参数返回单元的函数,例如
let func1 (name:string) (data:'a) = printfn "%s" name
要解构Parameter,我可以像这样包装func1
let func2 (Parameter (name, values)) =
match values with
| String s -> func1 name s
| Float s -> func1 name s
| Int s -> func1 name s
但是,如果我必须为多个功能执行此操作,这很不方便。相反,我想定义一个更灵活的包装器,如下所示:
let func3 (fn: ('a -> 'b -> unit)) (Parameter (name, values)) =
match values with
| String s -> fn name s
| Float s -> fn name s
| Int s -> fn name s
但是这失败了,因为b 的类型在匹配表达式的第一个选项中被限制为string[];因此匹配表达式失败并出现错误Type string does not match type float.
这是预期的吗?我该如何解决这个问题?
【问题讨论】:
-
是的,预计 F# 不支持更高级别的多态性。您可以将
data的类型更改为obj。 -
除了@Tomas 的回答,您还可以收到三倍相同的功能:
let func3 fn1 fn2 fn3 (Parameter (name, values))否则有another compile-time solution
标签: f#