[Haskell-beginners] foldr, Foldable and right-side folding

Tony Morris tonymorris at gmail.com
Mon Dec 7 01:11:28 UTC 2015


The foldr function does not start from the right. It associates to the
right.

This talk specifically addresses this common mistake.

http://functionaltalks.org/2013/06/19/tony-morris-explain-list-folds-to-yourself/
On 06/12/2015 10:21 AM, "Raja" <rajasharan at gmail.com> wrote:

> foldr is supposed to start folding from the right side (as the name
> suggests).
> and this is why it is synonymous to "list construction" as I'm told
>
> for e.g:
> > foldr (:) [ ] [1,2,3,4,5]
> [1,2,3,4,5]
>
> In the same spirit I'm trying to construct a Foldable instance of my own
> type:
>
> data Li a = Nil | Cons a (Li a)
>     deriving (Show)
>
> instance Foldable Li where
>     foldr f b Nil = b
>     foldr f b (Cons a y) = foldr f (f a b) y
>
> So I'm trying out foldr for my type:
> > foldr Cons Nil (Cons 1 (Cons 2 Nil))
> Cons 2 (Cons 1 Nil)
>
> This shows my foldr implementation i'm not folding from right side,
> but how can I possibly do that - the data could have been an infinite
> stream.
> It feels like I will never be able to truly write a foldr implementation
> with "right" folding mechanism.
>
> Any thoughts?
>
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20151207/57824399/attachment.html>


More information about the Beginners mailing list