How to define an n-sided polygon function in haskell

后端 未结 1 1405
旧巷少年郎
旧巷少年郎 2021-01-24 09:21

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 s

相关标签:
1条回答
  • 2021-01-24 09:43

    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.

    0 讨论(0)
提交回复
热议问题