3
votes

I am working around with algebraic types in Haskell, doing some exercises from a worksheet. I got the following exercises:

  1. Define an algebraic type Point for representing (the coordinates of) points in twodimensional space.

My code for this exercise:

data Point = Point Float Float
  deriving (Show)
  1. Using Point, define a modified version PositionedShape of the Shape data type which includes the centre point of a shape, in addition to its dimensions.

Shape data previously defined:

data Shape = Circle Float |
             Rectangle Float Float
             deriving (Show)

My code for this exercise:

data PositionedShape = PositionedShape Shape Point
  deriving (Show)

Now my question comes in this one:

Define a function:

haskell move :: PositionedShape -> Float -> Float -> PositionedShape

which moves a shape by the given x and y distances

My implementation for this was the following:

move :: PositionedShape -> Float -> Float -> PositionedShape
move (Shape (Point x y)) newX newY = Shape (Point newX newY)

This is returning me this error:

Week8.hs:103:7: error: Not in scope: data constructor ‘Shape’ Failed, modules loaded: none.

Can someone please explain me why this error and how can I solve it? I am getting a bit confused with algebraic types, I tried a lot of things but it just seems I can't get a solution.

3

3 Answers

4
votes

You need to pattern match on data constructors (like Circle and Rectangle), not on type constructors as you're trying to do now (like Shape). For PositionedShape, they happen to have the same name, although you completely forgot the match on this one (and in fact, you don't need to care about the inner Shape at all except to copy it through). Also, move is meant to move the shape by the given distances, not to move it to a new given position;.

2
votes

You need to use the PositionedShape constructor to break apart a PositionedShape You have used the Shape constructor instead.

Try starting with:

move (PositionedShape shape (Point old_x old_y)) [...]

1
votes

How about

move (PointedShape s (Point x y)) dx dy = PointedShape s (Point (x+dx) (y+dy))