elm-community / maybe-extra

Convenience functions for working with Maybe.

Home Page:http://package.elm-lang.org/packages/elm-community/maybe-extra/latest

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is there scope for a fold function?

NeilW opened this issue · comments

I'm noticing I'm doing a lot of

(a -> b -> b) -> b -> Maybe a -> b

when manipulating a couple of arrays. I'll get a value from array1 which is a Maybe value, and then apply it to array2 if it exists.

My code has lots of

case Array.get index1 array1 of
    Just value -> 
        Array.set index2 value array2

    Nothing -> 
        array2

given that's a signature for a fold, is it worth adding it? Which would give

Array.get index1 array1
|> Maybe.Extra.foldl (Array.set index2) array2 

I think this is a great idea, that really gets at how similar lists and maybes are. (Maybes are just a list with 0 or 1 elements.)

I only found one person defining a function like this: applyMaybe . Can you link to somewhere in real code that you would use this, so I have a better sense of how it'd be used?

I also looked to see if there are any other List functions that would be good to add to Maybe.Extra, and found one: any : (a -> Bool) -> Maybe a -> Bool. I've made an issue for it at #56. Do you happen to have any feedback on that?

There's loads here where I'm taking something from an array, updating it and putting it back.

For example:
https://github.com/newwayland/game/blob/master/src/model/Model/TaskManager.elm#L102

Thoughts on whether it should be

fold : (a -> b -> b) -> b -> Maybe a -> b

maybe
|> Maybe.Extra.fold update updateable

vs

fold : (a -> b -> b) -> Maybe a -> b -> b

updateable
|> Maybe.Extra.fold update maybe

?

And for that matter, thoughts on the argument order of the update function?

It should follow the pattern for List, Array, etc I would have thought.

If you put (a -> b -> b) -> b -> Maybe a -> b into elm search you get all the fold functions popping up.

Probably as well calling it foldl as well - and perhaps even aliasing a foldr just to keep the names consistent with the other Types.

Elm doesn't seem to reverse the accumulator and map in Elm like they do in Haskell between a left and right fold.

One point for the latter is that it can be quite nice to use it to conditionally add elements to lists:

[ some 
, list
]
   |> Maybe.Extra.fold (::) someMaybeValue

Seems reasonably nice... although perhaps a bit on the clever side.