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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With