[Haskell-cafe] Generic parser without GADTs

Huong Nguyen hiperfume at gmail.com
Sun Oct 16 22:57:27 EDT 2005


Hi all,

You are talking about parsing and data type, so I want to ask you a question
relating to my data type. I have a data types and a function as follows:

\begin{code}

data Type a = C1
{ x :: [String]
,y :: Type a}
| C2 {x1 :: String}
| C3 {y1 :: Bool} deriving Show

showType :: Type a -> String
showType (C2 a) = show a
showType (C3 a) = show a
showType (C1 a b) = show "(" ++ (show a) ++ (showType b) ++ (show ")")

r1 = C1 {
x = ["x","y"]
, y = C2{x1 = "x^2 + y^2 < 20"}
}

r2=C3{y1=False}

r3=C2{x1="x+y=z"}

\end{code}

--Result:

Main>showType r1

"\"(\"[\"x\",\"y\"]\"x^2 + y^2 < 20\"\")\""

Main>showType r2
"False"

Main>showType r3
"\"x+y=z\""

Now, I want to write a function to see the result in its original type, for
example :
input: "False"
output: False

input:"\"x+y=z\""
output:"x+y=z"

input:"\"(\"[\"x\",\"y\"]\"x^2 + y^2 < 20\"\")\""
output:(["x","y"]x^2 + y^2 < 20")

So, how I should write the function ? Do you have any idea about this ?
Thanks.


From: oleg at pobox.com <oleg at pobox.com >
Date: Oct 16, 2005 8:50 PM
Subject: [Haskell-cafe] Generic parser without GADTs
To: haskell-cafe at haskell.org
Cc: ralf at informatik.uni-bonn.de



Also inspired by Ralf Hinze's post, I thought of removing GADTs from
that code. The result is Haskell98! code, which works well in
Hugs. The code seems to be a bit simpler too. Like the original code,
the function 'parseAny' correctly discriminates between the list of
characters (i.e., strings) and the list of other things.

{-- Haskell98! --}

class Type a where
parse :: ReadS a


> hugs /tmp/h.hs
Haskell 98 mode: Restart with command line option -98 to enable extensions

Main> parseAny "4711"
[(ValInt 4711,"")]
Main> parseAny "\"4711\""
[(ValString "4711","")]
Main> parseAny "[4711, 0]"
[(ValList [ValInt 4711,ValInt 0],"")]
Main> parseAny "[4711, 'a']"
[(ValList [ValInt 4711,ValChar 'a'],"")]
Main> parseAny "[\"hello world\"] x"
[(ValList [ValString "hello world"]," x")]
______________________________ _________________
Haskell-Cafe mailing list
Haskell-Cafe at haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org//pipermail/haskell-cafe/attachments/20051016/31edb6ea/attachment.htm


More information about the Haskell-Cafe mailing list