6

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.

Dutts
  • 5,781
  • 3
  • 39
  • 61
  • 3
    You've been asking a couple of questions here that seem to push the envelope of the F# type system. Have you considered a more idiomatic approach? What are you really trying to do? – Mark Seemann Feb 16 '15 at 17:16
  • @MarkSeemann - We have a lot of mapping "glue" code between our established C# code base and newer F#. Our actual F# is functional but at the moment mapping C# types involves a lot of repeated code which is impacting our scalability so I've been looking at writing something more generic. – Dutts Feb 17 '15 at 09:22
  • In [your other question](http://stackoverflow.com/q/28538106/126014) you write that you want to be able to write `let testThings = toDomain doExternalThings`. How is that better that `let testThings = MyModule.MappedThings doExternalThings`? The native F# syntax is shorter that the function call you're after, and type-safe... – Mark Seemann Feb 17 '15 at 12:40
  • I can see your point. My real-world example is quite a bit more complicated, at the time I want to perform the mapping, I have an obj and so need to reflect over my union 'T to see which case takes that obj type. This has resulted in a lot of repeated mapping code everywhere. – Dutts Feb 17 '15 at 13:46

1 Answers1

6

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.

latkin
  • 16,402
  • 1
  • 47
  • 62