How to define an n-sided polygon function in haskell

纵饮孤独 提交于 2019-12-02 13:19:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!