Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a # before a type name mean in F#?

Tags:

f#

What does a # before a type name mean in F#?

For example here:

let getTestData (inner : int [] -> #seq<int>) (outer : #seq<int> [] -> #seq<'U>) =
    (testData |> Array.map inner) |> outer
like image 502
sdgfsdh Avatar asked Oct 18 '21 19:10

sdgfsdh


1 Answers

The syntax #type is called a "flexible type" and it is a shortcut for saying that the type can be any type that implements the given interface. This is useful in cases where the user of a function may want to specify a concrete type (like an array or a list).

For a very simple example, let's look at this:

let printAll (f: unit -> seq<int>) = 
  for v in f () do printfn "%d" v

The caller has to call printAll with a lambda that returns a sequence:

printAll (fun () -> [1; 2; 3]) // Type error
printAll (fun () -> [1; 2; 3] :> seq<int>) // Works, but tedious to write!

If you use flexible type, the return type of the function can be any implementation of seq<int>:

let printAll (f: unit -> #seq<int>) = 
  for v in f () do printfn "%d" v

printAll (fun () -> [1; 2; 3]) // No problem!

In reality, the syntax #typ is just a shortcut for saying 'T when 'T :> typ, so you can rewrite the function in my example as:

let printAll<'T when 'T :> seq<int>> (f: unit -> 'T) = 
  for v in f () do printfn "%d" v
like image 125
Tomas Petricek Avatar answered Sep 30 '22 16:09

Tomas Petricek