F# - 使用原语的类型约束
F# - Type Constraints with primitives
我想添加类型约束,如下所示。当我这样做时,我得到错误
错误 FS0698:无效约束:用于约束的类型是密封的,这意味着约束最多只能被一个解决方案满足
type PropertyValue<'T when 'T :> System.Int16 and 'T :> System.String> =
| Single of 'T
| Array of 'T[]
这就是我想要做的。
type PropertyValueInfo =
| String of string
| Int of int
| StringArray of string[]
| IntArray of int[]
在我们的域中,用户可以定义属性,属性可以是字符串、整数或字符串和整数的数组版本。我试图在一般意义上对此进行建模,以便将来我可以添加双类型。
不可能使用“或”作为类型约束,而且它真的没有意义 - 常见类型是什么?
另一种建模方法是使用两个 DU:
type PropertyValue<'T> =
| Single of 'T
| Multiple of 'T list
type PropertyType =
| Int of PropertyValue<int>
| String of PropertyValue<string>
let singleString = String (Single "hello")
let multInt = Int (Multiple [41; 42])
我想添加类型约束,如下所示。当我这样做时,我得到错误
错误 FS0698:无效约束:用于约束的类型是密封的,这意味着约束最多只能被一个解决方案满足
type PropertyValue<'T when 'T :> System.Int16 and 'T :> System.String> =
| Single of 'T
| Array of 'T[]
这就是我想要做的。
type PropertyValueInfo =
| String of string
| Int of int
| StringArray of string[]
| IntArray of int[]
在我们的域中,用户可以定义属性,属性可以是字符串、整数或字符串和整数的数组版本。我试图在一般意义上对此进行建模,以便将来我可以添加双类型。
不可能使用“或”作为类型约束,而且它真的没有意义 - 常见类型是什么?
另一种建模方法是使用两个 DU:
type PropertyValue<'T> =
| Single of 'T
| Multiple of 'T list
type PropertyType =
| Int of PropertyValue<int>
| String of PropertyValue<string>
let singleString = String (Single "hello")
let multInt = Int (Multiple [41; 42])