7-Dec

Elm

Simplify your code with ad hoc tuples

With Elm's strong types, we must be precise when writing our business code. Precision is a good thing, but it often has the drawback of being verbose. Ad hoc tuples can save the day with clear and precise syntax!

1 min read

·

By Holger Ludvigsen

·

December 7, 2020

A typical case is when you need to check multiple values. Let's say the user has chosen a size and optional color name for their product:

type Size
    = Small
    | Large

size : Size
color : Maybe String

And we want to put a suitable text in their confirmation dialogue:

case size of
    Small ->
        case color of
            Just colorName ->
                "A modest " ++ colorName

            Nothing ->
                "Don't worry! We will find a color for you"

    Large ->
        case color of
            Just colorName ->
                "A big great " ++ colorName

            Nothing ->
                "Don't worry! We will find a color for you" -- Oh no, duplication!

Instead of indenting away into these nested case-expressions, a common trick is to use an ad hoc tuple combining the two values into ( size, color ). Notice how clear this make the outcomes of each case:

case ( size, color ) of
    ( Small, Just colorName ) ->
        "A modest " ++ colorName

    ( Large, Just colorName ) ->
        "A big great " ++ colorName

    ( _ , Nothing ) ->
        "Don't worry! We will find a color for you"

Or consider if this if .. else expression for the email adress of a fictional company:

email =
    if (userDepartment == Technology && reportTitle == "Incident") then
        "brent@phoenix.com"

    else if userDepartment == Operations then
        "office@phoenix.com"

    else if (userDepartment == Sales && reportTitle == "Big sales lead") then
        "yuppie@phoenix.com"

    else
        "mail@phoenix.com"

This can be more consisely expressed with case .. of on a tuple:

email =
    case (userDepartment, reportTitle) of
        (Technology, "Critical incident") ->
            "brent@phoenix.com"

        (Operations, _) ->
            "office@phoenix.com"

        (Sales, "Big sales lead") ->
            "yuppie@phoenix.com"

        _ ->
            "mail@phoenix.com"

Don't topple the tuple

Before we run off with our newly acquired hammer and see a world of nails, beware that tuples in Elm are intentionally restricted to maximum three members.

The reasoning is that if you combine more values than this, you are probably better off with a proper data structure like a record where the fields are named. This is a strong restriction, but all the good kids will get the gift of clean readable code.

Up next...

Loading…