user5691928
user5691928

Reputation:

Trying to perform haskell pattern matching on Constructor value

I have a function getImage which takes an input of type DynamicImage and changes it into an image. The function is as follows

getImage (ImageY8 image) = image 
getImage (ImageY16 image) = image

The above definitions are from the Codec.Picture module. But it gives me an error:

Couldn't match type ‘GHC.Word.Word16’ with ‘GHC.Word.Word8’
    Expected type: Image Pixel8
      Actual type: Image Pixel16
    In the expression: image
    In an equation for ‘getImage’: getImage (ImageY16 image) = image
Failed, modules loaded: none.

Why is this not working as I can do the following:

data Shape = Circle Float | Rectangle Float Float

area (Circle r) = 3.14 * r * r
area (Rectangle a b) = a * b

which is similar to my question.

Upvotes: 1

Views: 144

Answers (2)

QuietJoon
QuietJoon

Reputation: 491

You may concern the return type of the function getImage. (I think you may has used the package JuicyPixels. You may describe the package name instead of the module...)

Let see the definition of data type:

ImageY8 (Image Pixel8)
ImageY16 (Image Pixel16)

You can see that the return type of getImage (ImageY8 image) and getImage (ImageY16 image) is different. The former is Image Pixel8 and the latter is Image Pixel16.
Therefore, the type signature of former function is DynamicImage -> Image Pixel8 and the latter is DynamicImage -> Image Pixel16. As you know, one function could not have different type signatures.

You have to rename these two different functions for each type signature.

Upvotes: 4

Jon Purdy
Jon Purdy

Reputation: 54979

What would you expect the type of getImage to be? The compiler is complaining because one equation has the type DynamicImage -> Image Pixel8 and the other has type DynamicImage -> Image Pixel16, and these types don’t match.

The reason you can write:

area (Circle r) = …
area (Rectangle a b) = …

Is because both equations have type Shape -> Float.

Upvotes: 3

Related Questions