不确定如何将参数应用于构造函数[Haskell& CodeWorld API]

时间:2018-03-19 10:57:21

标签: haskell

前言:

我在CodeWorld API中的Haskell中有这个功能。

shapeToPic :: Shape -> Picture

包含数据类型定义的.hs文件:

module Shape where

import CodeWorld (Point)

data Shape = Rectangle Side Side
           | Ellipse   Side Side
           | Polygon   [Point]
           | Line      Point Point
  deriving (Show)

data Tool = RectangleTool (Maybe Point)
          | EllipseTool   (Maybe Point)
          | LineTool      (Maybe Point)
          | PolygonTool   [Point]
  deriving (Show)

toolKeyMap :: [(String, Tool)]
toolKeyMap = [
  ("R", RectangleTool Nothing),
  ("E", EllipseTool Nothing),
  ("P", PolygonTool []),
  ("L", LineTool Nothing)
  ]

type Side = Double

主要

我想定义定义数据类型“Shape”所需的每个模式(Rectangle,Ellipse等)。

现在我的当前代码由

组成
shapeToPic :: Shape -> Picture
shapeToPic Rectangle = (translated (-3) 6  (solidRectangle 4 4))
shapeToPic Ellipse = colored red (translated 0 (-1.5) (solidCircle 8))
shapeToPic Polygon = colored blue (translated 0 (-1.5) (solidPolygon [4,2]))
shapeToPic Line = c

我得到一个错误说:

The constructor Rectangle' should have 2 arguments, but has been given none
      In the pattern: Rectangle
      In an equation for shapeToPic':
          shapeToPic Rectangle = (translated (- 3) 6 (solidRectangle 4 4))

现在我不确定如何给构造函数 Rectangle 两个参数,我不确定Rectangle数据类型定义中“Side Side”的含义。通过应用“solidRectangle 4 4​​”,我认为它将满足双方要求。现在我很困惑。

非常感谢帮助。

1 个答案:

答案 0 :(得分:1)

您无法匹配 构造函数;你还需要匹配它的参数:

shapeToPic (Rectangle x y) = (translated (-3) 6  (solidRectangle 4 4))

如果您不关心实际的xy值,可以将其替换为_

shapeToPic (Rectangle _ _) = (translated (-3) 6  (solidRectangle 4 4))

这两个值(可能)是值的长度和宽度,您可能希望保留它们,假设solidRectangle是一个返回新Rectangle值的函数。 / p>

    shapeToPic (Rectangle x y) = (translated (-3) 6  (solidRectangle x y))

或者,您可能只想重复使用原始值:

shapeToPic (Rectangle x y) = translated (-3) 6 (Rectangle x y)

shapeToPic r@(Rectangle _ _) = translated (-3) 6 r