如何在类型参数中使用歧视联合分支?
问题描述:
假设我有在F#类型是这样的:如何在类型参数中使用歧视联合分支?
type public Expression =
| Identifier of string
| BooleanConstant of bool
| StringConstant of string
| IntegerConstant of int
| Vector of Expression list
// etc...
现在我想用这个类型,在地图:
definitions : Map<Identifier, Expression>
然而,这给出了错误:
The type 'identifier' is not defined
如何将我的类型用作类型参数?
答
Identifier
是案例构造函数,而不是一个类型。它实际上是一个类型为string -> Expression
的函数。该类型的情况下是string
,这样你就可以定义为definitions
type definitions : Map<string, Expression>
答
有你想要的关键是一个特定的类型(即)不只是一个字符串的情况下,另一种方式。您只需创建的StringID类型,或者进一步包装成一个表达式:
type StringId = Sid of string
type Expression =
| StringId of StringId
| BooleanConstant of bool
| StringConstant of string
| IntegerConstant of int
| Vector of Expression list
这将让你在以下任一方式创建地图:
let x = Sid "x"
[StringId x ,BooleanConstant true] |> Map.ofList
//val it : Map<Expression,Expression> = map [(StringId (Sid "x"), BooleanConstant true)]
[x,BooleanConstant true] |> Map.ofList
//val it : Map<StringId,Expression> = map [(Sid "x", BooleanConstant true)]
这就是说,保持关键作为一个简单的字符串肯定不那么复杂。