Search code examples
haskelltypescompiler-errorstype-mismatchalgebraic-data-types

Creating a rectangle? - Haskell


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

Rectangle is defined by two points:

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

and Point is defined as

type Point = (Double, Double)

where:

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

and

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

error:

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)])
   |            

Not sure what I'm doing wrong? It might have something to do with Raster being a list of [Pixel], if so, can anyone help me fix this problem? Thanks!


Solution

  • It's not clear what you want to do, but if you want to write a function with the type given for rectangleRaster, you don't have to involve Rectangle.

    The simplest solution that looks like the OP is something like this:

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

    Here, I've hard-coded the Shade value of each Pixel as 1, as that looks like the attempted solution in the OP.

    You can call the function like this:

    *Q50128894> rectangleRaster (1,2) (3,4)
    [((1,2),1.0),((3,4),1.0)]
    

    If, on the other hand, you want to create a Rectangle, you'll need to supply two Point values, which you can do like in the following GHCi example:

    *Q50128894> Rectangle (1,2) (3,4)
    Rectangle (1.0,2.0) (3.0,4.0)