[Haskell-cafe] using phantom types to validate html
Thomas ten Cate
ttencate at gmail.com
Sun Jun 7 06:51:41 EDT 2009
I have been thinking about this same problem a while ago, and found
that HaXml [1] can generate Haskell types from a DTD schema. However,
the code that you need to build HTML from that is quite verbose.
Being no expert in Haskell, I talked to Twan van Laarhoven, who came
up with something [2] that looks quite similar to your solution. It
allows you to write stuff like this:
test = html $ body [p ["x",em "y"], ul [li "1", li "2"]]
Your use of phantom types looks a lot like his. The main difference
with your solution is that Twan's generates strings right away,
instead of using an intermediate data structure. Whether or not this
is desirable depends on the application, I guess.
A slight disadvantage is that the monomorphism restriction doesn't
allow you to use the same value as children of two nodes of different
types. In practice, this will probably not occur often. The linked
file provides a workaround, but NoMonomorphismRestriction will of
course also work.
Generating such code for the full HTML spec, or any XML for that
matter, while also including more advanced validation rules like "only
1 head section" would be an interesting exercise. If you manage to
pull this off, I'm definitely interested.
Hope this helps,
Thomas
[1] http://www.cs.york.ac.uk/fp/HaXml/
[2] http://moonpatio.com/fastcgi/hpaste.fcgi/view?id=2581#a2582
On Sat, Jun 6, 2009 at 20:41, Mathijs Kwik<bluescreen303 at gmail.com> wrote:
> Hi all,
>
> Please have a look at
> http://moonpatio.com/fastcgi/hpaste.fcgi/view?id=2575#a2575
> I wanted to use the typesystem to mandate businesslogic (in this case
> w3c validation rules).
> Thanks to some helpful people in #haskell I learned a bit about phantom types.
> Please let me know if I implemented them correctly.
>
> Also this little experiment raises some questions:
> The code becomes very verbose if there are more elements added or more
> rules to check.
> Since repetitive code can be a source of error, and hellish to
> maintain, I would like to know if there's some way to get this
> generated, or maybe there's some meta-programming stuff I don't know
> about.
> Another thing I can't figure out yet is how to do more advanced
> validation rules like "an html element cannot have 2 head sections",
> or (made up) "a span element isn't allowed to be a child(any level
> deep) of a p element".
>
> I think this would ask for an exponentially growing number of strange
> types and classes. Am I right?
>
> Just to be clear: this is just some practice to use the typesystem.
> I'm well aware that just using runtime validation checks will be a lot
> easier and clearer in most cases.
>
> Thanks,
> Mathijs
> _______________________________________________
> 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