I've been working on Question 67A of 99 Haskell Questions. The question is constructing a tree from a given string: "x(y,a(,b))" => Branch 'x' (Branch 'y' Empty Empty) (Branch 'a' Empty (Branch 'b' Empty Empty))
One solution using Parsec
is as below:
import Text.Parsec.String
import Text.Parsec hiding (Empty)
pTree :: Parser (Tree Char)
pTree = do
pBranch <|> pEmpty
pBranch = do
a <- letter
char '('
t0 <- pTree
char ','
t1 <- pTree
char ')'
return $ Branch a t0 t1
pEmpty =
return Empty
stringToTree str =
case parse pTree "" str of
Right t -> t
Left e -> error (show e)
However, my GHCi could neither find Text.Parsec.String
nor Text.Parsec
. Are those modules obsolete? My GHCi version is 6.12.3
Text.Parsec
and Text.Parsec.String
are modules in the parsec package from version 3 on. The old parsec-2
interface is available from the compatibility modules with the traditional names Text.ParserCombinators.Parsec.*
, but there's no *.String
module, that's new in parsec-3
. If you have parsec-2
or no parsec
at all installed, I recommend installing parsec-3
with the canonical cabal install parsec
.
Edit:
If you want to parse a less rigid syntax for the trees, supporting your example input,
pBranch = do
a <- letter
do char '('
t0 <- pTree
char ','
t1 <- pTree
char ')'
return $ Branch a t0 t1
<|> return (Branch a Empty Empty)
defaults to two empty children if the letter is not followed by an opening parenthesis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With