Skip to content
Why is a raven like a writing desk?

Thoughts both confusing and enlightening.

Why is a raven like a writing desk?

Thoughts both confusing and enlightening.

More on Tree Folds

elbeno, 17 July, 200729 July, 2007

After some thought, I think I have the definitions for left and right fold on a tree:

foldrTree :: (a -> b -> b) -> b -> InternalTree a -> b
foldrTree f z ILeaf = z
foldrTree f z (IBranch a x y) = foldrTree f (f a (foldrTree f z y)) x

foldlTree :: (a -> b -> a) -> a -> InternalTree b -> a
foldlTree f z ILeaf = z
foldlTree f z (IBranch a x y) = foldlTree f (f (foldlTree f z x) a) y

Of course, these folds are simplified: they don’t have a separate function for dealing with leaves and branches. This leads to things like flatten only working one way, i.e.
foldrTree (:) [] t
works because (:) will accumulate values onto a list properly from the right, but
foldlTree (:) [] t
gives a type error (because (:) cannot append a value onto a list working from the left).

Haskell

Post navigation

Previous post
Next post

Related Posts

Do-notation can be misleading

13 August, 201430 June, 2015

Consider the following function: oddness :: Maybe Int oddness = do let a = Just 1 :: Maybe Int b >= \b -> return b And recall the definition of (>>=) for Maybe: instance Monad Maybe where (Just x) >>= k = k x Nothing >>= _ = Nothing So…

Read More

Another Haskell question

10 July, 200729 July, 2007

Which pattern is more efficient? Pattern a: circleSumA :: [Int] -> Int circleSumA (i1 : is) = aux i1 is where aux i [] = i + i1 aux i is = i + aux (head is) (tail is) Pattern b: circleSumB :: [Int] -> Int circleSumB is = sum…

Read More

Haskell – the videos

9 August, 20071 February, 2015

If you’re one of the approx 3 people left in the world who: knows about functional programming has not yet seen Simon Peyton Jones‘ “A Taste of Haskell” talks from OSCON 2007 I suggest you get over there. It’s quite long, and it gets a bit difficult to follow without…

Read More

Comment

  1. Per Vognsen says:
    6 August, 2007 at 2:32 am

    The natural definition of folding would have this type signature:

    foldrT :: (a -> b -> b -> b) -> b -> Tree a -> b

    There’s a general cookbook method for deriving the fold for any so-called “polynomial data type” that generates both the above foldrT and the usual foldr for lists.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

©2026 Why is a raven like a writing desk? | WordPress Theme by SuperbThemes