0
votes

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.

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.mnoronha
I want to pattern match after the "=" . How can I do that ? :) TIAbill williams
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-functionsmnoronha

2 Answers

1
votes
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
1
votes

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