Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constraining an F# generic function to a union type?

As per the title, is there any way to constrain an F# generic function to a union type? So far I am using:

let toDomain<'T> external: 'T option =
    assert FSharpType.IsUnion(typeof<'T>)
    ...

Which fails at runtime with a System.ArgumentException if I attempt to use a non-union, but I would prefer the check earlier.

like image 834
Dutts Avatar asked Feb 16 '15 16:02

Dutts


1 Answers

No.

If you peek at the implementation of IsUnion and follow the code a bit, it boils down to checking for the presence of the attribute/argument [<CompilationMapping(SourceConstructFlags.SumType)>].

For now there is no support for purely attribute-based constraints, either in F# or in .NET.

like image 84
latkin Avatar answered Oct 02 '22 12:10

latkin