2016-11-09 13 views
5

Załóżmy, że mam typ takiego w F #:Jak używać urozmaiconego oddziału w parametrze typu?

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

Teraz chcę korzystać z tego typu zbudować mapę:

definitions : Map<Identifier, Expression> 

Jednak daje to błąd:

The type 'identifier' is not defined

Jak mogę użyć mojego typu jako parametru?

Odpowiedz

5

Identifier jest konstruktorem walizek , nie jest typem. W rzeczywistości jest to funkcja typu string -> Expression. Typ przypadku jest string, więc można zdefiniować definitions jak

type definitions : Map<string, Expression> 
3

Jest jeszcze inny sposób, w przypadku, gdy chcesz być kluczem do konkretnego typu (tj) nie tylko kolejny ciąg. Można po prostu utworzyć typ stringID i alternatywnie zawinąć że głębiej się wyrażeniem:

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

To pozwoli Ci stworzyć mapę w jeden z następujących sposobów:

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

To powiedziawszy, utrzymując klucz jako prosty ciąg jest z pewnością mniej skomplikowany.

Powiązane problemy