Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# type definition syntax

Tags:

f#

I'm working on the '99 problems of F#', and saw the following definition of NestedList:

type 'a NestedList = List of 'a NestedList list | Elem of 'a

I'm a little confused by the syntax here, as normally there is only a type name after the type. Can someone clarify it? Thanks!

like image 739
zhengbli Avatar asked Jan 30 '26 21:01

zhengbli


1 Answers

This is a discriminated union in a condensed syntax. You can also write it as:

type 'a NestedList =
    | List of 'a NestedList list
    | Elem of 'a

or

type NestedList<'a> =
    | List of NestedList<'a> list
    | Elem of 'a

This is using generics, where the type itself is taking another type as an argument.

like image 59
Christopher Stevenson Avatar answered Feb 01 '26 16:02

Christopher Stevenson