How to use discriminating union branch in type parameter?

Suppose I have this type in F #:

type public Expression = | Identifier of string | BooleanConstant of bool | StringConstant of string | IntegerConstant of int | Vector of Expression list // etc... 

Now I want to use this type to build a map:

 definitions : Map<Identifier, Expression> 

However, this gives an error:

ID type not defined

How can I use my type-type as a type parameter?

+5
source share
2 answers

Identifier is a case constructor, not a type. This is actually a function of type string -> Expression . The case type is string , so you can define definitions as

 type definitions : Map<string, Expression> 
+5
source

There is another way if you want the key to be a specific type (i.e.), and not just another string. You can simply create a StringID type and also wrap it further in an expression:

 type StringId = Sid of string type Expression = | StringId of StringId | BooleanConstant of bool | StringConstant of string | IntegerConstant of int | Vector of Expression list 

This will allow you to create a map in one of the following ways:

 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)] 

However, saving the key as a simple string is certainly less difficult.

+3
source

Source: https://habr.com/ru/post/1259490/


All Articles