Functions in Elm

Functions are central in Elm. We’ll learn about functions with a few different examples.

module Main exposing (main)

import Html exposing (Html, div, text)


-- Here's a function that takes two Int's and returns
-- their sum as an Int.
plus : Int -> Int -> Int
plus a b =
    -- Elm has implicit returns, so we don't need to use a return keyword.
    a + b


-- In Elm, all functions are curried by default, so we can define
-- a function that takes three parameters like this:
plusPlus : Int -> Int -> Int -> Int
plusPlus a b c =
    a + b + c


main : Html msg
main =
    let
        -- Call a function just as you'd expect, with name args.
        res1 =
            plus 1 2

        res2 =
            plusPlus 1 2 3
    in
    div []
        [ text ("1+2 = " ++ String.fromInt res1)
        , Html.br [] []
        , text ("1+2+3 = " ++ String.fromInt res2)
        ]

To run this Elm program, you would typically compile it to JavaScript and then run it in a web browser. Here’s what the output would look like:

1+2 = 3
1+2+3 = 6

In Elm, functions are first-class citizens and are a fundamental part of the language. They are always curried, meaning that a function that takes multiple arguments is actually a series of functions that each take a single argument.

Elm has a strong static type system, so the types of function parameters and return values are explicitly defined. This helps catch errors at compile-time and makes the code more self-documenting.

Unlike some other functional languages, Elm doesn’t require explicit return statements. The last expression in a function is automatically returned.

There are several other features to Elm functions. One is partial application, which allows you to create new functions by providing only some of the arguments to an existing function. We’ll explore more of these concepts in later examples.