Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accomplish inheritance in Elm

Tags:

elm

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.

like image 630
user2167582 Avatar asked Jan 23 '26 09:01

user2167582


2 Answers

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
like image 187
VGj. Avatar answered Jan 26 '26 23:01

VGj.


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
like image 35
Mark Bolusmjak Avatar answered Jan 27 '26 00:01

Mark Bolusmjak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!