[Haskell] Parsing Typed Data from a String
Ralf Laemmel
ralf at cwi.nl
Mon Mar 8 20:26:21 EST 2004
Hi,
with the boilerplate style one can build terms while exploring permutations.
This can accommodated as a generic program.
An illustrative code snippet follows.
Let's define a function that builds a datum "a" while reading constructor
strings via a monad. Hence the function is of the following type:
buildT :: forall a. Data a => ReadT a
The corresponding monad is easily defined for the following type:
newtype ReadT a = ReadT { unReadT :: [String] -> Maybe ([String],a) }
The function buildT goes essentially like this:
buildT =
do str <- readT -- 1
con <- string2constr str -- 2
ske <- return $ fromConstr con -- 3
fs <- return $ gmapQ buildT' ske -- 4
perm [] fs ske --5
In step 1, we read a constructor string from the input.
In step 2, we turn the string into a proper constructor.
In step 3, we compute a skeleton term (with bottoms).
In step 4, we compute a list of specialisations of buildT,
that only attempt to build subterms of the given type of kid.
In step 5, we repeatedly map the list of functions over the
skeleton until all functions have been applied once.
For more details, see [1,2]
There are other kinds of type reflection that come handy
in such a context; we really plan to release [3] very soon :-)
Ralf
[1] The boilerplate site: http://www.cs.vu.nl/boilerplate
[2] The code for this example:
http://www.cs.vu.nl/boilerplate/testsuite/perm.hs
[3] Scrap more boilerplate by SPJ and Ralf Laemmel, forthcoming.
Simon D. Foster wrote:
>I am currently trying to implement a method of allowing arbitrary record
>syntax data-types to be converted to and from an XML representation of
>them using the Read and Show class;
>
>i.e. simply derive either Show and then parse the given String to
>extract the name/value pairs which can then be converted to XML, or
>using the XML generate a representation of the data entity (e.g.
>"Person{name=\"Fred Smith\", age=47}") and read this back into an actual
>value.
>
>However I have one small problem; the order of the incoming parameters
>of the XML data-type representations is not guaranteed, but according to
>Haskell 98 report;
>
>"If the constructor is defined using record syntax...the fields must be
>given in the same order as the original declaration."
>
>So my question is, is there any method in GHC which allows you to
>extract the order of the constructors in a type or to parse a
>type-representation in such a way that the order of the records doesn't
>matter (I am looking for ease/simplicity of use)?
>
>Or do I just tell them to put the records in alphabetical order?
>
>-Si.
>
>(Please CC replies to me).
>
>
More information about the Haskell
mailing list