创建一个矩形? - 哈斯克尔

时间:2018-05-02 07:06:51

标签: haskell types compiler-errors type-mismatch algebraic-data-types

rectangleRaster :: Coord -> Coord -> Raster
rectangleRaster a b = (Rectangle [(a, 1)] [(b, 1)])

Rectangle由两点定义:

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

和Point定义为

type Point = (Double, Double)

其中:

type Shade = Double
type Coord = (Int, Int)

type Pixel = (Coord, Shade)
type Raster = [Pixel]

错误:

src\View.hs:70:24: error:
* Couldn't match type `Shape' with `[Pixel]'
  Expected type: Raster
    Actual type: Shape
* In the expression: (Rectangle [(a, 1)] [(b, 1)])
  In an equation for `rectangleRaster':
      rectangleRaster a b = (Rectangle [(a, 1)] [(b, 1)])
   |
70 | rectangleRaster a b = (Rectangle [(a, 1)] [(b, 1)])
   |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^

src\View.hs:70:34: error:
    * Couldn't match type `[(Coord, Integer)]' with `(Double, Double)'
      Expected type: Point
        Actual type: [(Coord, Integer)]
    * In the first argument of `Rectangle', namely `[(a, 1)]'
      In the expression: (Rectangle [(a, 1)] [(b, 1)])
      In an equation for `rectangleRaster':
          rectangleRaster a b = (Rectangle [(a, 1)] [(b, 1)])
   |
70 | rectangleRaster a b = (Rectangle [(a, 1)] [(b, 1)])
   |                                  ^^^^^^^^

src\View.hs:70:43: error:
    * Couldn't match type `[(Coord, Integer)]' with `(Double, Double)'
      Expected type: Point
        Actual type: [(Coord, Integer)]
    * In the second argument of `Rectangle', namely `[(b, 1)]'
      In the expression: (Rectangle [(a, 1)] [(b, 1)])
      In an equation for `rectangleRaster':
          rectangleRaster a b = (Rectangle [(a, 1)] [(b, 1)])
   |
70 | rectangleRaster a b = (Rectangle [(a, 1)] [(b, 1)])
   |            

不确定我做错了什么?它可能与Raster作为[Pixel]列表有关,如果是这样,任何人都可以帮我解决这个问题吗?谢谢!

2 个答案:

答案 0 :(得分:3)

目前尚不清楚您想要做什么,但如果您想编写一个具有rectangleRaster类型的函数,则不必涉及Rectangle

看起来像OP的最简单的解决方案是这样的:

rectangleRaster :: Coord -> Coord -> Raster
rectangleRaster a b = [(a, 1), (b, 1)]

在这里,我将每个Shade的{​​{1}}值硬编码为Pixel,因为它看起来像OP中的尝试解决方案。

你可以这样调用这个函数:

1

另一方面,如果您要创建*Q50128894> rectangleRaster (1,2) (3,4) [((1,2),1.0),((3,4),1.0)] ,则需要提供两个Rectangle值,您可以在以下GHCi示例中执行此操作:

Point

答案 1 :(得分:3)

throw Error()是一个数据构造函数。根据定义

,它会创建Rectangle类型的值
Shape

它实际上有data Shape = .... | Rectangle Point Point | .... -- ^^^^^ ^^^^^^^^^ ^^^^^ ^^^^^ -- type data type type -- constructor 类型。

但在你的定义中

Rectangle :: Point -> Point -> Shape

您宣布rectangleRaster :: Coord -> Coord -> Raster rectangleRaster a b = Rectangle [(a, 1)] [(b, 1)] 为返回rectangleRaster的函数,而不是Raster。因此类型不匹配错误。甚至说,

Shape

即。根据您的声明/类型规范,期望找到src\View.hs:70:24: error: * Couldn't match type `Shape' with `[Pixel]' Expected type: Raster Actual type: Shape ,但实际找到类型为Raster的值,由数据构造函数Shape