sdgfsdh
sdgfsdh

Reputation: 37045

What does a # before a type name mean in 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

Upvotes: 10

Views: 196

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243041

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

Upvotes: 14

Related Questions