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
.
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.
(//) : 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.