[Haskell-cafe] Trouble understanding records and existential types
Udo Stenzel
u.stenzel at web.de
Thu Jan 25 20:43:20 EST 2007
John Ky wrote:
> On 1/25/07, BBrraannddoonn SS.. AAllllbbeerryy KKFF88NNHH <_a_l_l_b_e_r_y_@_e_c_e_._c_m_u_._e_d_u> wrote:
> I'm probably missing something, but:
>
> (a) Why not:
>
> data ANode = Branch { name :: String, description :: String,
> children :: [AnyNode] }
> | Leaf { name :: String, value :: String } -- this reuse
> is legal
> -- leaving Node available if you still need it
>
> Would I be able to this?
>
> getLeaves :: ANode -> [Leaf]
data Branch = Branch { name :: String, description :: String, children :: [AnyNode] }
data Leaf = Leaf { name :: String, value :: String }
data AnyNode = Either Branch Leaf
Now if you absolutely insist on overloading the 'name' identifier, you
can do this:
data Branch = Branch { brName :: String, description :: String, children :: [AnyNode] }
data Leaf = Leaf { lName :: String, value :: String }
data AnyNode = Either Branch Leaf
class HasName a where name :: a -> Name
instance HasName Branch where name = brName
instance HasName Leaf where name = lName
instance HasName AnyNode where name = either brName lName
Okay, you lose record update and construction syntax for AnyNode, but I
don't think that's so much of a loss.
On a side note, all this has nothing to do with OOP. If you wanted to
simulate objects, you would "replace case by polymorphism", but I can't
demonstrate how to do that, since none of your "objects" has any
methods.
-Udo.
--
"Technology is a word that describes something that doesn't work yet."
-- Douglas Adams, JavaOne keynote, 1999
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20070126/65e0ee53/attachment.bin
More information about the Haskell-Cafe
mailing list