2

Say I have a DU , which I cannot (or do not want to) change:

type OrDU =
    | A
    | B
    | C

Now in another program I need a DU, which is identical to the above except it needs a few additional cases.

type ExtraDU = 
    inherit OrDU
    | D
    | E

However, DU's cannot be extended. What is the best solution for this? Ideally I want easy interop, that is a OrDu can be used as a ExtraDU, and an ExtraDU without the extra cases can be converted back to a OrDU.

dtech
  • 13,741
  • 11
  • 48
  • 73
  • Have you seen this article on extending discriminated unions using marker interfaces? http://theburningmonk.com/2012/03/f-extending-discriminated-unions-using-marker-interfaces/ – Patrick McDonald Feb 16 '15 at 16:22
  • I've seen it, but it seems so... *inelegant*, compared to e.g. scala case classes. I guess its the best F# can do. – dtech Feb 16 '15 at 16:50
  • possible duplicate of [Shared cases in F# discriminated unions](http://stackoverflow.com/questions/3194791/shared-cases-in-f-discriminated-unions) – dtech Feb 16 '15 at 16:51

1 Answers1

5

You could extend it like so:

type ExtraDU =
| OrDU of OrDU
| D
| E

An alternative approach, from http://theburningmonk.com/2012/03/f-extending-discriminated-unions-using-marker-interfaces, looks like the following:

type IMessage = interface end

type OrDU =
    | A | B | C
    interface IMessage

type ExtraDU =
    | D | E
    interface IMessage


let f1 = function
    | A -> "A"
    | B -> "B"
    | C -> "C"

let f2 = function
    | D -> "D"
    | E -> "E"

let f (msg : IMessage) =
    match msg with
    | :? OrDU    as a -> f1 a
    | :? ExtraDU as b -> f2 b
    | _ -> failwith "Invalid type"

This however requires that you change the OrDU by adding an interface

Patrick McDonald
  • 64,141
  • 14
  • 108
  • 120
  • That would bloat the pattern matches though (minor), and wouldn't allow a function that accepts `ExtraDU` to also accept `OrDU`'s (more of an inconvenience). – dtech Feb 16 '15 at 16:16
  • 1
    I see what you're saying, unfortunately I don't know of any way to extend a discriminated union like you're asking – Patrick McDonald Feb 16 '15 at 16:20