[Haskell-cafe] Abstraction in data types
John Meacham
john at repetae.net
Thu Mar 18 14:26:58 EDT 2010
On Wed, Mar 17, 2010 at 09:20:49PM -0700, Darrin Chandler wrote:
> Trying to get up to speed in Haskell, I'm playing with doing some
> abstraction in data types. Specifically, I have this:
>
> type Cartesian_coord = Float
>
> type Latitude = Float
> type Longitude = Float
>
> data Point = Cartesian (Cartesian_coord, Cartesian_coord)
> | Spherical (Latitude, Longitude)
>
> type Center = Point
> type Radius = Float
>
> data Shape = Circle Center Radius
> | Polygon [Point]
phantom types can help you, providing the ability to distinguish the two
without the run-time overhead of checking the Cartesioan and Spherical
constructors
> data Cartesian -- empty, just used for the type constructor
> data Spherical
> data Point a = Point Float Float
> data Shape a = Circle (Point a) Radius
> | Polygon [Point a]
now you can have routines like
> spPoint :: Latitude -> Longitude -> Point Spherical
> cPoint :: Cartesian_coord -> Cartesian_coord -> Point Cartesian
to create points of each, yet you can still have functions on 'Point a'
that will work on any type of point.
You may want to create a class that converts between the two
> class Coordinated f where
> toCartesian :: f Spherical -> f Cartesian
> toSpherical :: f Cartesian -> f Spherical
>
> instance Coordinated Point where ...
> instance Coordinated Shape where ...
John
--
John Meacham - ⑆repetae.net⑆john⑈ - http://notanumber.net/
More information about the Haskell-Cafe
mailing list