问题
I need to define a function that moves the "pen", which starts at (0,0) in the bottom left, around to draw the correct polygon depending on the input, with every side of the shape having length of 1. I need to do it without importing any functions that already exist. I am using OpenGL to draw the shape. Command is defined as:
data Command
= Fd Double
| Bk Double
| Lt Double
| Rt Double
| Go Command
| Command :> Command
I have done a triangle which works but now want to be able to just say how many sides the shape has instead of defining every shape. Triangle:
triangle :: Command
triangle = Fd 1 :> Rt 120
:> Fd 1 :> Rt 120
:> Fd 1 :> Rt 120
cabal run polygon 6
should create a hexagon etc
so far all I've got is:
polygon :: Int -> Command
polygon n =
回答1:
The angle between the vertices is given by the formula 360/n
. So every time turn by that and move, repeated n
times:
polygon n = foldl1 (:>) . replicate n (Fd 1 :> Rt (360.0 / fromIntegral n))
Broken up:
polygon n = foldl1 (:>) sides
where
sides = replicate n side
side = Fd 1 :> Rt angle
angle = 360.0 / fromIntegral n
Working example online
As a side note, I'd define CommandList = [Command]
and get rid of that infix type constructor. It sure looks funny, but is much less convenient.
I've just noticed the weird
I need to do it without importing any functions that already exist.
in your question. Since I consider this constraint absurd, I'm not going to adhere to it. If you want to, copy the implementations of foldl1
and replicate
from Prelude yourself. Although strictly speaking you don't have to manually import them in order to use them.
来源:https://stackoverflow.com/questions/33736975/how-to-define-an-n-sided-polygon-function-in-haskell