Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append Maybe to List in Elm

Tags:

list

elm

maybe

I have a List a and a Maybe a. I want to append the maybe value if it is Just a but do nothing if it is Nothing.

This is what I am currently using:

aList ++ case maybeValue of
           Just value ->
             [ value ]
           Nothing ->
             []

Is there a better (more idiomatic) way of doing this?

Note that prepending is fine too if there is a cleaner way of doing that instead. The list order does not matter.

like image 574
Ralph Avatar asked Aug 09 '17 18:08

Ralph


3 Answers

From Chad's suggestion that prepending is cheaper:

prependMaybe : List a -> Maybe a -> List a
prependMaybe list maybe =
   case maybe of
           Just value ->
             value :: list
           Nothing ->
             list
like image 175
genthaler Avatar answered Sep 28 '22 01:09

genthaler


I think you can use Maybe.map List.singleton yourMaybe |> Maybe.withDefault [].

Here you have a complete example:

appendMaybe : List a -> Maybe a -> List a
appendMaybe list maybe =
    Maybe.map List.singleton maybe
        |> Maybe.withDefault []
        |> (++) list

You can try it on Ellie

like image 40
gabrielperales Avatar answered Sep 28 '22 00:09

gabrielperales


If you're going for conciseness, you could use Maybe.Extra.unwrap from the elm-community/maybe-extra package:

import Maybe.Extra exposing (unwrap)

consMaybe : List a -> Maybe a -> List a            
consMaybe list =
    unwrap list (flip (::) list)

appendMaybe : List a -> Maybe a -> List a            
appendMaybe list =
    unwrap list ((++) list << List.singleton)

If you really want to go crazy, you can create your own infix operators:

infixr 5 ::?
(::?) = flip consMaybe

infixr 5 ++?
(++?) = appendMaybe

This allows the following:

Nothing ::? [2, 3, 4] == [2, 3, 4]
Just 1  ::? [2, 3, 4] == [1, 2, 3, 4]

[2, 3, 4] ++? Nothing == [2, 3, 4]
[2, 3, 4] ++? Just 5  == [2, 3, 4, 5]

Now, whether the infix versions are idiomatic Elm, that's up for debate. If it's something you use a lot, perhaps it's worth it, but most Elm guides urge you to avoid infix operators because they hinder discoverability.

In the end, your original example has the benefit of being readable and probably more readily understandable, since fewer people will be familiar with unwrap. The only suggestion would be that if order truly doesn't matter, then prepending an item to a list is going to be faster than concatenating lists.

like image 39
Chad Gilbert Avatar answered Sep 28 '22 02:09

Chad Gilbert