
I'm new to functional programming and to haskell. I'm reading ``The Haskell School of Expression'' by Paul Hudak and I'm studying how to solve exercise 2.2. My difficulty here is more algorithmic than Haskellian, but perhaps many here have solved this exercise already, or would know how to solve it; I hope it's okay to post. (*) Exercise 2.2 Define a function regularPolygon :: Int -> Side -> Shape such that regularPolygon n s is a regular polygon with n sides, each of length s. (Hint: consider using some of Haskell's trigonometric functions, such as sin :: Float -> Float, cos :: Float -> Float, and tan :: Float -> Float.) My idea is to start with the vertices (0,0) and (0,s). Then I ``connect a line'' from (0,0) to (0,s) and I then I need to compute the next vertex of the polygon. The angles of a regular polygon are alpha = ((n - 2) * pi)/n, where n is the number of sides of the polygon. So the third vertex of the polygon is x = cos (180 - alpha) * s y = sin (180 - alpha) * s, but I don't know how to teach the computer to get to the forth vertex. Once I figure that in a general way, I would just call myself until I get to the last vertex; if I start at n, we end at at n = 2 in which I return []. Something like:
data Shape = Polygon [Vertex] deriving Show
type Side = Float type Vertex = (Float, Float)
regularPolygon :: Int -> Side -> Shape regularPolygon n s = Polygon ((0,0) : (0,s) : buildList n s (fromIntegral n)) where buildList :: Int -> Side -> Float -> [Vertex] buildList 2 _ _ = [] buildList n s m = let x = cos(pi - alpha) * s y = sin(pi - alpha) * s alpha = ((m - 2) * pi)/m in (x,y) : buildList (n-1) s m
but right now it just repeats all the vertices after the second. Any help is appreciated.