21

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.

Mauricio Scheffer
  • 96,120
  • 20
  • 187
  • 273
Alexander Galkin
  • 10,800
  • 9
  • 56
  • 111
  • 2
    Might be helpful: http://stackoverflow.com/questions/44961/what-are-the-primary-differences-between-haskell-and-f – Daniel Nov 16 '11 at 17:25
  • In response to your second question, [this answer](http://stackoverflow.com/questions/159356/why-is-f-so-special/159414#159414) lists some F# distinctives. – Daniel Nov 16 '11 at 21:26

2 Answers2

9

(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.

newacct
  • 110,405
  • 27
  • 152
  • 217
  • 2
    Case identifiers/constructors are first-class functions in F# too: `List.zip [1;2;3] ['a';'b';'c'] |> List.map Foo` – Daniel Nov 16 '11 at 21:54
  • F# is an ML variant, so you're correct that it's very similar to O'Caml. – John L Nov 17 '11 at 18:47
5

I'm not very familiar with Haskell (I've only read Learn You a Haskell) but I haven't yet come across a basic difference between DUs and Haskell's algebraic data types--they're both attempts to model the same concept. Having said that, F# and Haskell have very different type systems (e.g., Haskell has type classes/higher-kinded types; F# is deeply grounded in OOP, etc.) so there is asymmetry, but nothing limited to these data types.

Daniel
  • 46,089
  • 10
  • 89
  • 172