[Haskell-cafe] Haskell - convert postfix expression to binary tree

Martin Studna martin.studna2 at gmail.com
Mon Aug 21 16:10:26 UTC 2017


Hello,

I am trying to convert postfix expression to binary tree. My function takes
as argument a list of tokens (strings).

Everytime I give the function any input, debugger writes a message:
Non-exhaustive patterns in function "add".

My idea was: read a token after token and determine, if it is an operator
or an operand. If it is operand, don't save any node to the tree and store
the number to the stack. Otherwise I create a node with an operator, pop
symbols from stack, set them as children of new node and push the operator
to stack.

If the list of strings is empty, functions print the binary tree.

Would someone explain to me, why the function gives non-exhaustive patterns
error and how can I fix the function?

data Tree = Leaf String | Empty | Node Tree String Tree deriving (Show)

add :: Tree -> [String] -> [Tree] -> Tree
add (Node l v p) [] stack = (Node l v p)
add Empty (x:xs) []
        | x `elem` ["*","-","+"] = add (Leaf x) xs [Leaf x]
        | otherwise = add Empty xs [Leaf x]
add Empty (x:xs) (a:b:bs)
        | x `elem` ["*","-","+"] = add (Node b x a) xs (Leaf x:a:b:bs)
        | otherwise = add Empty xs (Leaf x:a:b:bs)
add (Leaf x) token (a:b:bs)
        | x `elem` ["*","-","+"] = add (Node b x a) token (Leaf x:bs)
        | otherwise = Leaf x
add (Node l v p) (x:xs) (a:b:bs)
        | x `elem` ["*","-","+"] = add (Node b x a) xs (Leaf x:bs)
        | otherwise = add (Node l v p) xs (Leaf x:a:b:bs)

parse :: String -> Tree
parse input = add Empty (words (toPostfix input)) []
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20170821/f651519f/attachment.html>


More information about the Haskell-Cafe mailing list