[Haskell-cafe] MonadPlus and Alternative folds

Danny Navarro j at dannynavarro.net
Sat Sep 19 08:47:50 UTC 2015


Sorry, you are right, I was thinking about folding `Alt` as a
`Monoid`, but what you need is different.

On Sat, Sep 19, 2015 at 10:37 AM, David Feuer <david.feuer at gmail.com> wrote:
> Alt doesn't have a Foldable instance; these "folds" don't have quite
> the right types for that. I don't understand how the reducers relate
> to what I'm asking.
>
> On Sat, Sep 19, 2015 at 3:22 AM, Danny Navarro <j at dannynavarro.net> wrote:
>> Not sure about performance, but you could wrap the `Alternative` with
>> an `Alt`[1] and use the `Foldable` instance.
>>
>> There is also `Alternative` folding in the `reducers` package.
>>
>> [1]: https://hackage.haskell.org/package/base-4.8.1.0/docs/Data-Monoid.html#t:Alt
>> [2]: https://hackage.haskell.org/package/reducers-3.12.1/docs/Data-Semigroup-Alternative.html
>>
>> On Sat, Sep 19, 2015 at 7:25 AM, David Feuer <david.feuer at gmail.com> wrote:
>>> It kind of seems like there should be fold-like things to match some and
>>> many.
>>>
>>> foldrAlt :: Alternative f => (a -> b -> b) -> b -> f a -> f b
>>> foldrAlt c n m = foldr1Alt c n m <|> pure n
>>>
>>> foldr1Alt :: Alternative f => (a -> b -> b) -> b -> f a -> f b
>>> foldr1Alt c n m = c <$> m <*> foldrAlt c n m
>>>
>>> foldlMP' :: MonadPlus f => (b -> a -> b) -> b -> f a -> f b
>>> foldlMP' f b m = foldl1MP' f b m <|> pure b
>>>
>>> foldl1MP' :: MonadPlus f => (b -> a -> b) -> b -> f a -> f b
>>> foldl1MP' f b m = m >>= \r -> let !b' = f b r in foldlMP' f b' m
>>>
>>> --These look a bit iffy
>>> foldlAlt :: Alternative f => (b -> a -> b) -> b -> f a -> f b
>>> foldlAlt f b m = ($ b) <$> foldrAlt (\x r acc -> r (f acc x)) id m
>>>
>>> foldl1Alt :: Alternative f => (b -> a -> b) -> b -> f a -> f b
>>> foldl1Alt f b m = ($ b) <$> foldr1Alt (\x r acc -> r (f acc x)) id m
>>>
>>> Do these or similar exist somewhere? If not, should they exist somewhere?
>>> I'm particularly interested in whether either of these will be fast, or will
>>> admit a fast implementation, for attoparsec parsers.
>>>
>>> Thanks,
>>>
>>> David Feuer
>>>
>>>
>>> _______________________________________________
>>> Haskell-Cafe mailing list
>>> Haskell-Cafe at haskell.org
>>> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
>>>
>>
>>
>>
>> --
>> Danny Navarro  |  http://dannynavarro.net



-- 
Danny Navarro  |  http://dannynavarro.net


More information about the Haskell-Cafe mailing list