Methods in Elm
Elm supports functions defined on custom types, which are similar to methods in other languages.
In Elm, we don’t have methods in the same way as in object-oriented languages. Instead, we define functions that take our custom type as their first argument. This is similar to how methods work in other languages, but it’s more explicit in Elm.
We define a Rect
type alias with width
and height
fields. Then we define two functions, area
and perim
, which operate on Rect
values.
In the main
function, we create a Rect
value and then call our functions with it. The results are then displayed using Elm’s HTML functions.
Elm doesn’t have the concept of pointers or references like some other languages. Instead, all values are immutable, and functions always receive copies of their arguments. This means we don’t need to worry about the difference between value and reference semantics when calling functions.
To run this Elm program, you would typically compile it to JavaScript and then run it in a web browser. The exact commands might vary depending on your setup, but it could look something like this:
Then open a web browser and navigate to http://localhost:8000/index.html
(assuming you have an index.html
file that includes the compiled JavaScript).
Next, we’ll look at Elm’s mechanism for defining interfaces between different parts of your program: custom types and type aliases.