[Haskell-beginners] how to implement accesor function for
given data type
Brent Yorgey
byorgey at seas.upenn.edu
Mon Sep 13 09:53:21 EDT 2010
On Mon, Sep 13, 2010 at 02:52:06PM +0200, Martin Tomko wrote:
> Dear all,
> apologies for a newbie question, but I am returning to Haskell after
> years of hiatus and Java...
>
> I have the following data type (representing geometries):
>
> data Geometry = Point FID Coordinate
> | LineSegment FID (Coordinate,Coordinate)
> | Polyline FID [Coordinate]
> | Polygon FID [Coordinate]
> deriving (Show,Eq)
>
> type Coordinate = (Float, Float)
>
> And this is where I fail: I have no idea how to type getCoordinates,
> in order to match against the three different combinations -> it can
> result into a Coordinate, or a typle, or a List. I am sure it is
> possible!
It is not possible. What would you do with the coordinates once you
had them? You wouldn't know what type of coordinates you would be
getting and hence you would be unable to do anything with them.
Why not something like this?
getCoordinates :: Geometry -> [Coordinate]
getCoordinates (Point _ c) = [c]
getCoordinates (LineSegment _ (c1,c2)) = [c1,c2]
getCoordinates (Polyline _ cs) = cs
getCoordinates (Polygon _ cs) = cs
-Brent
More information about the Beginners
mailing list