[Haskell-cafe] Typeclasses vs simple functions?
Olex P
hoknamahn at gmail.com
Tue Sep 15 13:00:56 EDT 2009
Thanks for explanation Sean!
On Tue, Sep 15, 2009 at 4:30 PM, Sean Leather <leather at cs.uu.nl> wrote:
>
>
>> "Existential types" sounds a bit scary :)
>>
>>>
> It's unfortunate that they've developed a scariness feeling associated with
> them. They can be used in strange ways, but simple uses are quite
> approachable. One way to think of them is like implementing an
> object-oriented interface. You know it's an object, but you can't do
> anything with it except use the methods of the interface.
>
> ---
>
> {-# LANGUAGE ExistentialQuantification #-}
>
> data Square = Square ...
> data Circle = Circle ...
>
> class Perimeter a where perimeter :: a -> Double
> instance Perimeter Square where perimeter (Square ...) = ...
> instance Perimeter Circle where perimeter (Circle ...) = ...
>
> -- The 'a' is hidden here. The interface is defined by the class
> constraint.
> data Perimeterizable = forall a . (Perimeter a) => P a
>
> -- This is the accessor method for things Perimeterizable.
> getPerimeter (P x) = perimeter x
>
> vals :: [Perimeterizable]
> vals = [P Square, P Circle]
>
> perims = map getPerimeter vals
>
> ---
>
> Regards,
> Sean
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090915/861ba65d/attachment.html
More information about the Haskell-Cafe
mailing list