type alias Car = { model : Model, year: Int }
type Model = Crv | Enzo | Mustang | Viper
-- I can do this
enzo = Car Enzo -- partial Contructor
> myE<function> : Int -> Repl.Car
myEnzo = enzo 2018
> { model = Enzo, year = 2018 } : Repl.Car
-- but i CANNOT do this
enzo2017 = Car { year: 2017 } -- INVALID
How can i make a simple constructor that doesn't force me to list the attributes in a defined order.
When it comes to functional programming we need to "start over" with some concepts. In this case the confusion seems to be with the word constructor. The record constructor in Elm is different than the object constructor in object oriented language.
The record constructor does not create a record, it only creates a function that can create records. It does this by partial application.
In partial application you can only give the arguments in their order. This is defined in lambda calculus and I believe it is not specific to Elm. In the case of creating records with record constructor changing the order of the argument doesn't make changes in the result.
We can use this handy function flip that returns the same function with reverse order of the arguments:
enzo2017 = flip Car 2017
myEnzo2017 = enzo2017 Viper
Consider, when you define this:
type alias Car = { model : Model, year: Int, notes: String}
what you really get, is a function Car like this:
> Car
> <function> : Repl.Model -> Int -> String -> Repl.Car
It's easy to define another constructor:
> f notes model year = Car model year notes
> <function> : String -> Repl.Model -> Int -> Repl.Car
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With