sdgfsdh
sdgfsdh

Reputation: 37045

Can I use the special generic syntax for my own types?

In F# some types have a special generic syntax (I'm not sure what it is called) so that you can do:

int list // instead of List<int>
int option // instead of Option<int>

Upvotes: 5

Views: 134

Answers (2)

DaveShaw
DaveShaw

Reputation: 52798

It is covered in the MSDN on F# Types

Under "generic type":

generic type

type-parameter generic-type-name | 'a list

Or

generic-type-name<type-parameter-list> | list<'a>

And "constructed types":

constructed type (a generic type that has a specific type argument supplied)

type-argument generic-type-name

or

generic-type-name<type-argument-list>

type dave<'a> = {
    V : 'a
};;

let stringDave: dave<string> = { V = "string" };;
//val stringDave : dave<string> = {V = "string";}

let intDave : int dave = { V = 123 };;
//val intDave : dave<int> = {V = 123;}

Upvotes: 6

TheQuickBrownFox
TheQuickBrownFox

Reputation: 10624

Firstly, it's important to note that the difference between list and List isn't directly related to the prefix and postfix syntax. The type 'T list is simply an alias of the type List<'T>. From the F# core source code:

type List<'T> = 
   | ([])  :                  'T list
   | (::)  : Head: 'T * Tail: 'T list -> 'T list
   interface System.Collections.Generic.IEnumerable<'T>
   interface System.Collections.IEnumerable
   interface System.Collections.Generic.IReadOnlyCollection<'T>
   interface System.Collections.Generic.IReadOnlyList<'T>

and 'T list = List<'T>

And separate to this we have the ability to express any generic types prefix or postfix.

With these two things combined, that means that all of these types are valid and equivalent.

int list
int List
list<int>
List<int>

This works with any other .NET types, e.g. int System.Collections.Generic.HashSet, and your own types:

type MyCoolType<'a> = A | B

let x : int MyCoolType = A
// compiles ✔

Both the lower-case type annotations and the postfix syntax seem to exist for compatibility with OCaml, which was the language that F# was originally based on.

Upvotes: 3

Related Questions