Skip to content

Instantly share code, notes, and snippets.

@cscalfani
Last active August 10, 2016 14:33
Show Gist options
  • Save cscalfani/3dd61c9d3bf6bfd5b8c24fd9d109bbfa to your computer and use it in GitHub Desktop.
Save cscalfani/3dd61c9d3bf6bfd5b8c24fd9d109bbfa to your computer and use it in GitHub Desktop.

Default Values in Elm

Using Maybe

In Elm, optional values are handled with Maybe. The following functions show a simple implementation of optional parameters:

combineOpts : Maybe String -> Maybe String -> String -> String -> String
combineOpts = prefix suffix s1 s2 =
    (Maybe.withDefault "" prefix) ++ s1 ++ s2 ++ (Maybe.withDefault "" suffix)

combine : String -> String -> String
combine =
    combineOpts Nothing Nothing

combineOpts is a general version of combine with prefix and suffix as optional parameters. combine is the same as combineOpts except with the optional parameters defined as Nothing.

A more concise approach

While the code in combineOpts works, it's a bit verbose and difficult to read. So let's create an operator, defined-or, like the one used in Perl, //, which will do the same as Maybe.withDefault.

We want to be able to use it like:

combineOpts : Maybe String -> Maybe String -> String -> String -> String
combineOpts = prefix suffix s1 s2 =
    (prefix // "") ++ s1 ++ s2 ++ (suffix // "")

That's far more concise. Now all we have to do is write the code for the // operator.

But before we do, let's rewrite a code fragment in prefix order:

    (//) prefix ""

Contrast this with using withDefault:

    Maybe.withDefault "" prefix

Notice how the first 2 parameters are swapped or flipped. So all we have to do is flip the parameters on withDefault and we're done.

Defined-or operator implementation

(//) : Maybe a -> a -> a
(//) =
    flip Maybe.withDefault

Now all you have to do is add this function to your projects and you can have concise default values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment