0
votes
data BB a = L | K (BB a) a (BB a) deriving (Show)
foldrpBB :: (a -> b -> b) -> b -> BB a -> b 
foldrpBB f b L = b 
foldrpBB f b (K l r a) = foldrpBB f (f r (foldrpBB f b a)) l
foldrprBB :: (a -> b -> b) -> b -> BB a -> b 
foldrprBB f b L = b 
foldrprBB f b (K a l r) = foldrprBB f (f l (foldrpBB f b r)) a 

I'm trying to create two different fold functions which would print post- and infix expressions of a given binary tree such as K (K L 2 L) 1 (K (K L 4 L) 3 L) when coupled with an anonymous function like (\x xs -> concat ["(", show x, xs, ")"]).

I'm getting an error basically telling me that my function is expecting a String, but it's supposed to be expecting a function and a binary tree(BB):

  • Couldn't match expected type: [Char] with actual type: BB a0 -> a0 -> BB a0 -> BB a0
    • Probable cause: K' is applied to too few arguments In the second argument of foldrpBB', namely `K' In the expression: foldrpBB (\ x xs -> concat ["(", show x, xs, ....]) K (K L 2 L) 1 (K (K L 4 L) 3 L)

How can I solve this issue?

1

1 Answers

3
votes

You made two separate mistakes. First, you forgot the base case b parameter when you called the function. I assume you wanted this to be "". Second, you need to use either parentheses or $ with the structure that you want to fold. You'll get "(2(1(4(3))))" from either of these two fixed expressions:

  • foldrpBB (\x xs -> concat ["(", show x, xs, ")"]) "" $ K (K L 2 L) 1 (K (K L 4 L) 3 L)
  • foldrpBB (\x xs -> concat ["(", show x, xs, ")"]) "" (K (K L 2 L) 1 (K (K L 4 L) 3 L))