Search code examples
haskellf#functional-programmingalgebraic-data-typesdiscriminated-union

Do algebraic datatypes in Haskell equal discriminated unions in F#?


I am learning Haskell and would like to know whether the constructs known in Haskell as algebraic datatypes are the same that discriminated unions in F# or there are some subtle differences between them.

I would also appreciate much a good comparison between F# (my first functional language) and other functional languages, especially as regards similar concepts but with substantial but important differences.


Solution

  • (I come from OCaml, but I looked over the relevant F# stuff and it seems the same. Correct me if I'm wrong.) They are the same, just different terminology for the same thing, but there are a few syntactical differences. For example, to define a constructor with multiple data elements, in OCaml and F# you write the type as if they were stuffed in a tuple:

    Haskell:

    data Whatever = Foo TypeA TypeB
    

    OCaml / F#:

    type whatever = Foo of typeA * typeB
    

    Similarly, to pattern match on it, you similarly act like a single argument that is a tuple with all the data members stuffed inside:

    Haskell:

    case x of Foo a b -> ...
    

    OCaml / F#:

    match x with Foo (a, b) -> ...
    

    Edit: apparently the following does not apply in F#

    Also, in Haskell the constructor automatically becomes a function that you can use by itself like any other value:

    zipWith Foo xs ys
    

    OCaml/F# don't do this. You could manually define your own functions for each constructor.