如何在haskell中定义一个n边多边形函数 [英] How to define an n-sided polygon function in haskell

查看:218
本文介绍了如何在haskell中定义一个n边多边形函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义一个函数来移动笔,它从左下角的(0,0)开始,根据输入绘制正确的多边形,每一边的形状长度为1 。我需要在不导入已经存在的任何函数的情况下执行此操作。我正在使用OpenGL绘制形状。命令定义为:

  data命令
= Fd Double
| Bk Double
| Lt Double
| Rt Double
|转到命令
|命令:>命令

我已经完成了一个可以工作的三角形,但现在想要能够说出形状而不是定义每个形状。 Triangle:

  triangle:命令
triangle = Fd 1:> Rt 120
:> Fd 1:> Rt 120
:> Fd 1:> Rt 120

cabal run polygon 6

应该创建一个六角形等等



到目前为止,我得到的是:

  polygon :: Int - > Command 
polygon n =


解决方案

顶点由公式 360 / n 给出。所以每一次都是这样,并且移动,重复 n 次:

 多边形n = foldl1(:>)。复制n(Fd 1:> Rt(360.0 / fromInteral n))

Broken up: p>

  polygon n = foldl1(:>)双方
其中
双方=复制n方
side = Fd 1:> Rt角度
angle = 360.0 / fromIntegral n


作为一个方面说明,我会定义 CommandList = [Command] 并摆脱那个中缀类型的构造函数。它确实看起来很有趣,但是不太方便。






我刚刚注意到奇怪的


我需要在不导入任何已经存在的函数的情况下执行它。



<在你的问题中。由于我认为这个限制是荒谬的,我不会坚持它。如果你想,你可以自己从Prelude中复制 foldl1 replicate 的实现。尽管严格来说,您不必手动导入它们才能使用它们。


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 = 

解决方案

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.

这篇关于如何在haskell中定义一个n边多边形函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆