1

Being a beginner in Haskell I am currently trying to get my head around BST. Currently I am trying to perform a fold on a tree inorder.

This is what I got so far, but it produces an error.

inorder' :: (b -> a -> b) -> b -> BinaryTree a -> b
inorder' _ a myTree = a
inorder' fun a (Node left root right) = inorder' fun (fun root (inorder' fun a left)) right

I am really dumbfounded now because I worked for quite some time now to figure out what exactly the problem is but I simply do not seem to come up with a solution.

2
  • 2
    What error does it produce? Commented Jun 19, 2017 at 15:27
  • Furthermore please include the definition of BinaryTree a. Commented Jun 19, 2017 at 15:29

1 Answer 1

3

Inorder means that you (1) first process the left subtree, (2) then process the node itself, and (3) finally process the right subtree.

Leaves without values

Based on your function, the definition of BinaryTree a, is probably:

data BinaryTree a = Leaf | Node (BinaryTree a) a (BinaryTree a)

So that means that there are two cases: in case of a leaf, there is no data, so we simply return the given value:

inorder' _ a Leaf = a -- with an uppercase, otherwise it does match all

And for the Node case, we above already stated how that works:

inorder' f a (Node left val right) = inorder' f c right
    where b = inorder' f a left
          c = f b val

Or in full:

inorder' :: (b -> a -> b) -> b -> BinaryTree a -> b
inorder' _ a Leaf = a
inorder' f a (Node left val right) = inorder' f c right
    where b = inorder' f a left
          c = f b val

Leaves with values

In that case the BinaryTree is defined like:

data BinaryTree a = Leaf a | Node (BinaryTree a) a (BinaryTree a)

In case the leaves have a value, we simply need to fix the first clause:

inorder' :: (b -> a -> b) -> b -> BinaryTree a -> b
inorder' f b (Leaf a) = f b a
inorder' f a (Node left val right) = inorder' f c right
    where b = inorder' f a left
          c = f b val
Sign up to request clarification or add additional context in comments.

2 Comments

myTree is a pattern that matches anything, not a constructor.
@amalloy: yeah, somehow i did not notice the lowercase, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.