MrBear
MrBear

Reputation: 65

Can I use a type within its own type definition?

I'm trying to define the following type:

type lToken =
  LInt of int 
| LString of string 
| LList of lToken list
| LFunction of string * LList

but I'm getting an error 'LList' is not defined.

Is there a way to do what I'm trying to do - i.e. use the types I'm defining inside their own type definition?

Thanks

Upvotes: 4

Views: 281

Answers (3)

Tomas Petricek
Tomas Petricek

Reputation: 243096

As others pointed out, LList is not a name of a type, but just a name of discriminated union's constructor. In F#, cases of discriminated union happen to be compiled as .NET types, but that's just an implementation detail and you cannot refer to the generated types.

If you want to declare LFunction as a cast that consists of string and a LList then you can either expand the definition (as Brian and Marcelo suggest) or declare a new type (using type .. and to declare recursive types):

type List = Token list 
and Token = 
  | LInt of int  
  | LString of string  
  | LList of List
  | LFunction of string * List 

PS: If you're writing F# then I'd recommend following standard naming guidelines and using PascalCase with a more descriptive name for type names. What does "l" stand for? Could you expand it (thanks to type inference, you won't need to write the type name anyway).

Upvotes: 7

Marcelo Cantos
Marcelo Cantos

Reputation: 186118

LList is a constructor, not a type. Just use the associated type directly:

...
| LFunction of string * (lToken list)

(My ML is very rusty; I'm not sure whether the parentheses are right.)

Upvotes: 6

Brian
Brian

Reputation: 118935

LList is not the name of a type; lToken is. Perhaps you want lToken list there instead?

Upvotes: 4

Related Questions