<div class="gmail_quote"><div>Hi Lenny,<br> <br></div><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;"><div>i am not quite sure how to do this in the most elegant way:<br>
<br>
I have some data structures:<br>
<br>
data A = A Double<br>
data B = B Double<br>
data C = C Double<br>
...<br>
<br>
and i want to allow only a subset in another data structure, so i did something like this:<br>
<br>
data SubSet = SubSetA A | SubSetC C<br>
<br>
and use it in Foo:<br>
<br>
data Foo = Foo [SubSet]<br>
<br>
No i want to perform a polymorphic operation on the contents of A,B,C, e.g.<br>
<br>
doSomething :: Foo -> [Double]<br>
doSomething (Foo s) = map doSomethingElse s<br></div></blockquote></div><br>You can do things similar to this using one of the many generics libraries for Haskell [1,2]. I'm not sure if this is exactly what you're after, but here is a possibility using EMGM [3].<br>
<br><blockquote style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex; font-family: courier new,monospace;" class="gmail_quote">{-# LANGUAGE TemplateHaskell #-}<br>{-# LANGUAGE UndecidableInstances #-}<br>
{-# OPTIONS -fglasgow-exts #-}<br><br>import Generics.EMGM<br>import Generics.EMGM.Derive<br><br>data A = A Double<br>data B = B Double<br>data C = C Double<br><br>data Subset = SubsetA A | SubsetC C<br><br>data Foo = Foo [Subset]<br>
<br>$(deriveMany [''A,''B,''C,''Subset,''Foo])<br><br>doSomething :: Foo -> [Double]<br>doSomething = collect<br></blockquote><br>In GHCi, I get the following:<br><br><span style="font-family: courier new,monospace;">*Main> doSomething (Foo [SubsetA (A 5.0),SubsetC (C 9.9)])</span><br style="font-family: courier new,monospace;">
<span style="font-family: courier new,monospace;">[5.0,9.9]</span><br style="font-family: courier new,monospace;"><br>Other libraries to look at include SYB [4] and Uniplate [5].<br><br>Regards,<br>Sean<br><br>[1] <a href="http://hackage.haskell.org/packages/archive/pkg-list.html#cat:generics">http://hackage.haskell.org/packages/archive/pkg-list.html#cat:generics</a><br>
[2] <a href="http://www.cs.uu.nl/research/techreps/UU-CS-2008-010.html">http://www.cs.uu.nl/research/techreps/UU-CS-2008-010.html</a><br>[3] <a href="http://www.cs.uu.nl/wiki/GenericProgramming/EMGM">http://www.cs.uu.nl/wiki/GenericProgramming/EMGM</a><br>
[4] <a href="http://www.cs.uu.nl/wiki/GenericProgramming/SYB">http://www.cs.uu.nl/wiki/GenericProgramming/SYB</a><br>[5] <a href="http://community.haskell.org/~ndm/uniplate/">http://community.haskell.org/~ndm/uniplate/</a><br>