Multiple Return Values in Elm

Elm has built-in support for multiple return values through tuples. This feature is commonly used in functional programming languages to return multiple values from a function.

module Main exposing (..)

import Html exposing (Html, div, text)

-- The (Int, Int) in this function signature shows that
-- the function returns a tuple of 2 Ints.
vals : () -> (Int, Int)
vals () =
    (3, 7)

main : Html msg
main =
    let
        -- Here we use tuple destructuring to get the 2 different 
        -- return values from the function call.
        (a, b) = vals ()
        
        -- If you only want a subset of the returned values,
        -- you can use the underscore (_) as a wildcard.
        (_, c) = vals ()
    in
    div []
        [ text (String.fromInt a)
        , text "\n"
        , text (String.fromInt b)
        , text "\n"
        , text (String.fromInt c)
        ]

To run this Elm program:

  1. Save the code in a file named MultipleReturnValues.elm.
  2. Use the Elm compiler to compile and run the program:
$ elm make MultipleReturnValues.elm --output=index.html
$ elm reactor

Then open a web browser and navigate to http://localhost:8000/index.html. You should see the following output:

3
7
7

In Elm, functions always return a single value, but we can use tuples to effectively return multiple values. Tuple destructuring allows us to easily work with these multiple return values.

Elm’s type system and functional programming paradigm make it easy to work with multiple return values in a type-safe manner. This approach is idiomatic in Elm and other functional programming languages.