Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
syntax gripes with Elm
{-
There's two ways to create a record in Elm: with the "type constructor" and with the "record syntax".
The fact that there's two ways to do the same thing is already a bit disconcerting, but the worst
part is that there's no way to do it and have the best of both worlds regarding naming (which is
great for clarity, maintenance and refactoring: think about grepping on names for example).
-}
type alias Person = {
firstName: String,
lastName: String,
age: Int,
isAdmin: Bool
}
{- the "type constructor" method: you have a list of "params" that may no sense without the context
(what is the last "True" here, how would I find this line by grepping on "age" if I want to refactor
and change the name of that field?
-}
john : Person
john = Person "John" "Smith" 39 True
{- the "record syntax" method: if you omit the type definition you don't have a way to grep on "Person",
or even know that it is a record of that type when you read the following code.
-}
jane : Person
jane = {firstName = "Jane", lastName = "Smith", age = 38, isAdmin = False}
{- Is there a way to have the best of both worlds?
At the moment I'm using the "record syntax" method everywhere, but I can't have the type definition
above the record if I'm declaring the record inline (think about the `init` function that takes a
`Model` which can have nested records
-}
@magopian
Copy link
Author

magopian commented Feb 9, 2018

It seems we have a winner:

type Person = Person {
    firstName: String,
    lastName: String,
    age: Int,
    isAdmin: Bool
}

john : Person
john = Person {firstName = "John", lastName = "Smith", age = 39, isAdmin = True}

jane : Person
jane = Person {firstName = "Jane", lastName = "Smith", age = 38, isAdmin = False}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment