[Haskell-cafe] building a regular polygon

Frank Buss fb at frank-buss.de
Sun Aug 19 19:12:57 EDT 2007


> From: Rafael Almeida [mailto:almeidaraf at gmail.com] 
> 
> I used the cosine law in order to calculate r. After all, s is
> actually the size of the side of the polygon and not the distance of
> its vertices from the origin.

You are right, my solution was wrong. If you don't mind rounding errors,
this is another solution:

import List

regularPolygon n s = iteratedAdd segments
    where a = 2 * pi / (fromIntegral n)
          segments = [rotatedSegment (fromIntegral i) | i <- [0..n-1]]
          rotatedSegment i = (s*sin(i*a),s*cos(i*a))
          iteratedAdd = snd . mapAccumR (\s x->(add s x, add s x)) (0,0)
          add (x1,y1) (x2,y2) = (x1+x2,y1+y2)

With this list comprehension, your solution could be written like this:

regularPolygon n s = [(r * cos(a i), r * sin(a i)) | i <- [0..n-1]]
   where a i = 2 * fromIntegral i * pi / fromIntegral n
         r = sqrt(s^2 / (2 * (1 - cos(2 * pi / fromIntegral n))))

-- 
Frank Buss, fb at frank-buss.de
http://www.frank-buss.de, http://www.it4-systems.de



More information about the Haskell-Cafe mailing list