Methods in Elm

Elm supports functions defined on custom types, which are similar to methods in other languages.

module Main exposing (..)

import Html exposing (Html, div, text)

type alias Rect =
    { width : Int
    , height : Int
    }

-- This `area` function takes a `Rect` as its first argument
area : Rect -> Int
area r =
    r.width * r.height

-- Here's another function that operates on `Rect`
perim : Rect -> Int
perim r =
    2 * r.width + 2 * r.height

main : Html msg
main =
    let
        r = Rect 10 5
        
        -- Here we call the 2 functions defined for our custom type
        areaResult = "area: " ++ String.fromInt (area r)
        perimResult = "perim: " ++ String.fromInt (perim r)
    in
    div []
        [ div [] [ text areaResult ]
        , div [] [ text perimResult ]
        ]

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:

$ elm make Main.elm --output=main.js
$ elm reactor

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.