[Haskell-cafe] simple parsing
S. Doaitse Swierstra
doaitse at swierstra.net
Wed Oct 28 17:33:41 EDT 2009
Ok,
I think this is a weird problem, but let us start. You want to parse a
sequence of operands separated by an operator (we assume the ops are
left associative):
import Text.ParserCombinators.UU.Parsing
pWeird = pChainl pOperator pOperand
An operand is apparently a non-empty list of digits, and the result
should be the last of these digits:
pOperand = toList.last <$> pList1 (pSym ('0', '9'))
toList x = [x]
An operator is a sequence of "+-/*" symbols, and it is the first
element in which you are interested:
pOperator = intoOp.head <$> pList1 (pSym '+' <|> pSym '-' ...)
The function intoOp now builds the function which constructs the final
list given the operator and the left and right operands:
intoOp op = \leftop rightop -> leftop ++ [op] ++ rightop
Doaitse
On 27 okt 2009, at 23:38, satorisanitarium wrote:
> I'm trying to parse a list of numbers plus four diferent signs (+-*/)
> in this way:
>
> Lets say the list is "32+5/46" result would be "2+5/4"
> I get:
>
> "2+5/4*** Exception: geneticSimple.hs:(55,0)-(65,35): Non-exhaustive
> patterns in function chromoResult
>
> If the list is "32+5**6" result would be "2+5*6"
> I get:
> "2+5/*** Exception: geneticSimple.hs:(55,0)-(65,35): Non-exhaustive
> patterns in function chromoResult
>
> If the list is "32+-72" resoult would be "2+7"
> I get:
> "2+*** Exception: geneticSimple.hs:(55,0)-(65,35): Non-exhaustive
> patterns in function chromoResult
>
> code:
>
> chromoResult [] = []
> chromoResult (a:b:c:xs)
> | elem a "0123456789" && elem b "0123456789" && elem c "0123456789" =
> chromoResult (c:xs)
> | elem a "0123456789" && elem b "0123456789" && elem c "+-*/" = b:c:
> chromoResult xs
> | elem a "0123456789" && elem b "+-*/" && elem c "0123456789" =
> a:b:c : chromoResult xs
> | elem a "0123456789" && elem b "+-*/" && elem c "+-*/" = a:b :
> chromoResult (c:xs)
> | elem a "+-*/" && elem b "0123456789" && elem c "0123456789" =
> chromoResult (b:c:xs)
> | elem a "+-*/" && elem b "0123456789" && elem c "+-*/" = b:c :
> chromoResult xs
> | elem a "+-*/" && elem b "+-*/" && elem c "0123456789" =
> chromoResult (c:xs)
> | elem a "+-*/" && elem b "+-*/" && elem c "+-*/" = chromoResult xs
> | otherwise = chromoResult (b:c:xs)
>
> I suspect my approach is flawed but i have exausted my ideas.
> I need a fresh approach so if anybody would be kind enough and just
> give me a hint how to approach the problem.
> Thx in advance.
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
More information about the Haskell-Cafe
mailing list