Search code examples
typesf#setdiscriminated-union

Why doesn't this Discriminated Union accept a Set type case?


I am trying to create a new Set type:

type MySet<'t> = | List of list<'t>
                 | Sequence of seq<'t>
                 | Array of 't []

This works, but if I try to add a case for the Set type itself I get a message: a type parameter is missing a constraint 'when t: comparison'

type MySet<'t> = | List of list<'t>
                 | Sequence of seq<'t>
                 | Array of 't []
                 | Set of Set<'T>

My guess is this should be easy to fix, but I could not do it even though I tried a couple of things.


Solution

  • The implementation of the Set<'t> data structure requires that its values can be compared, so if your type contains values that can be put into a set, you must provide the same type constraint:

    type MySet<'t when 't : comparison> =
        | List of list<'t>
        | Sequence of seq<'t>
        | Array of 't []
        | Set of Set<'t>