Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a type within its own type definition?

Tags:

f#

ocaml

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

like image 779
MrBear Avatar asked Dec 04 '22 10:12

MrBear


1 Answers

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

like image 155
Tomas Petricek Avatar answered Dec 29 '22 21:12

Tomas Petricek