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
Best Answer
Text.Parsec
andText.Parsec.String
are modules in the parsec package from version 3 on. The oldparsec-2
interface is available from the compatibility modules with the traditional namesText.ParserCombinators.Parsec.*
, but there's no*.String
module, that's new inparsec-3
. If you haveparsec-2
or noparsec
at all installed, I recommend installingparsec-3
with the canonicalcabal install parsec
.Edit:
If you want to parse a less rigid syntax for the trees, supporting your example input,
defaults to two empty children if the letter is not followed by an opening parenthesis.