0

The below code sequence is generating a parse error on input |. If the input was a leaf node then call leafFunc with value If the input was a tree node then call TreeFunc with left Subtree,value,right Subtree

data Tree t = Leaf t
        | Node (Tree t) t (Tree t)

foldTree :: (t1 -> t -> t1 -> t1) -> (t -> t1) -> Tree t -> t1
foldTree treeFn leafFn tree= | foldTree (Leaf v) = leafFn(v)
                             | foldTree (Node left v right) = treeFn(left v right)


Input : foldTree (\t1 t t2->t1 + 5*t + t2) (\x->x+9) (Leaf 5)
Expected Output : 14

Input : foldTree (\t1 t t2->t1 + 3*t + t2) (\x->x+5) (Tree (Leaf 3) 2 (Leaf 4))
Expected Output : 23

I am a newbie in haskell.

3
  • 2
    The parse error results form your guard statement being incorrectly formatted. You shouldn't place an equal sign before |. You have some other things to deal fix after that, including applying foldTree with the correct number of arguments within the guards. Commented Nov 7, 2016 at 1:48
  • I want to pattern match after the "=" . How can I do that ? :) TIA Commented Nov 7, 2016 at 2:43
  • 1
    You're confusing function/guard syntax. To the right of the guard, you include predicates (functions that evaluation to True or False) and the corresponding value assignments. If you want to pattern match different cases (leaf vs. node), you can do so with a case statement or by manually matching several cases with function declarations. I recommend you read this: learnyouahaskell.com/syntax-in-functions Commented Nov 7, 2016 at 4:29

2 Answers 2

1
data Tree t = Leaf t
              | Node (Tree t) t (Tree t)

foldTree :: (Tree t -> t -> Tree t -> t1) -> (t -> t1) -> Tree t -> t1
foldTree treeFn leafFn (Leaf v) = leafFn v
foldTree treeFn leafFn (Node left v right) = treeFn left v right
Sign up to request clarification or add additional context in comments.

Comments

1

I'm guessing this is what you want

data Tree t = Leaf t | Node (Tree t) t (Tree t) deriving Show

foldTree :: (t1 -> t -> t1 -> t1) -> (t -> t1) -> Tree t -> t1
foldTree treeFn leafFn tree 
                | foldTree (Leaf v) = leafFn v
                | foldTree (Node left v right) = treeFn left v right

Comments

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.