I feel something uncomfortable with Haskell record syntax

haskellsyntax

Most of Haskell syntax has beauty of purity. But the record syntax looks ugly. It's uncomfortable. It feels some kind of mixture with C. It requires comma and braces. Haskell has tab,line based separation. So it looks too verbose than originally it requires. Why is it designed in that way?

Best Answer

While I wasn't on the design commitee, I reckon that record syntax was shaped to be consistent with list syntax. Module export syntax uses commas, too, the only real place where layout is used is top-level declarations, where clauses and do-notation.

On top of that, given

data Foo = Foo {bar :: Int, baz :: Int}

writing

fnord x = x { bar = 4 }

without the braces would clash with the rest of the syntax, and using layout, like

fnord x = x
    bar = 4

would make the syntax quite brittle. Add a "where" in the wrong place and your code means something completely different.

If you're not happy with the state of records in Haskell (and you wouldn't be alone with that), I recommend you have a look at fclabels or even elaborate typeclass hackery like HList or grapefruit-records (the latter two not being for the faint of heart, but also insanely powerful)

fclabels would allow you to write (yay pointfree)

fnord = setL bar 4

as well as

getBar = getL bar

on top of it's actual raison d'etre, which is composing labels:

 data Person = Person { _place  :: Place, ... }
 data Place = Place { _city :: String, ... }

 moveToAmsterdam :: Person -> Person
 moveToAmsterdam = setL (city . place) "Amsterdam"
Related Topic