[Haskell-cafe] Creating a Point

Rafael Almeida almeidaraf at gmail.com
Sat Jul 19 22:44:46 UTC 2014


Hello,

I was talking to friends about how could you make a Point type in haskell.
It's intuitive to make a 2D point such as:

    type Point2D = (Double, Double)

Let's define one operation on this new type:

    add2D (x1, y1) (x2, y2) = (x1+x2, y1+y2)

Let's say now we want a 3D point. Then we'd be tempted to do:

    type Point3D = (Double, Double, Double)

    add3D (x1, y1, z1) (x2, y2, z2) = (x1+x2, y1+y2, z1+z2)

Although those types work great and you could make a type class so you
don't have to suffix each function with 2D and 3D. It feels like we are
just repeating code when defining the add function. If we want to go 4D,
5D, etc it would be more repeated code.

Using a list would be more general:

    type Point = [Double]

now we have a nice, general add function

    add = zipWith (+)

It's not so fun that we are able to do something like:

    add [2,3] [5,7,11]

We have no type-safety that we can only operate on points with the same
dimension.

How could we address this? Can we make a general function, yet retain the
type safety? I suppose maybe there's something that could be done with TH
so that we automatically generate those Point2D, Point3D, etc code. I'm not
sure that would be a nice path to follow, though.

[]'s
Rafael
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20140719/b5be09f4/attachment.html>


More information about the Haskell-Cafe mailing list