maybe-extra icon indicating copy to clipboard operation
maybe-extra copied to clipboard

Is there scope for a fold function?

Open NeilW opened this issue 5 years ago • 5 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 

NeilW avatar May 17 '20 16:05 NeilW

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?

skyqrose avatar May 23 '20 15:05 skyqrose

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

NeilW avatar May 23 '20 16:05 NeilW

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?

skyqrose avatar May 24 '20 14:05 skyqrose

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.

NeilW avatar May 24 '20 14:05 NeilW

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.

gampleman avatar Nov 23 '22 15:11 gampleman