4

I'm started working with Juicy Pixels library and have some problem with deconstructing.

There are type:

data DynamicImage =
    ImageY8   (Image Pixel8)
    | ImageYA8  (Image PixelYA8)
    | ImageRGB8 (Image PixelRGB8)
    | ImageRGBA8 (Image PixelRGBA8) 
    | ImageYCbCr8 (Image PixelYCbCr8)

where Pixel* is instances of Pixel a class

There are some functions that work with Image a type and i wish to extract Image a from DynamicImage, but i can't

When i try to do something like

img :: (Pixel a) => DynamicImage -> Image a
img (ImageY8 i) = i
img (ImageYA8 i) = i  
img (ImageRGB8 i) = i
img (ImageRGBA8 i) = i  
img (ImageYCbCr8 i) = i

interpreter thwors an errors like

Couldn't match type `PixelYCbCr8' with `GHC.Word.Word8'
Expected type: Image b
  Actual type: Image Pixel8
In the expression: i
In an equation for `img': img (ImageY8 i) = i

Is there any other way to extract Image a data?

1 Answer 1

5

Your approach does not work because the type signature of img promises to provide an Image for every a, not just one particular chosen by img itself.

One possibility is to change the type signature to also take the function that will handle the polymorphic image, and use RankNTypes to allow that:

withImg :: DynamicImage -> (forall a. Pixel a => Image a -> b) -> b
withImg (ImageY8 i) f = f i
withImg (ImageYA8 i) f = f i  
withImg (ImageRGB8 i) f = f i
withImg (ImageRGBA8 i) f = f i  
withImg (ImageYCbCr8 i) f = f i

This ensures that the function passed to withImg will accept any Image as an argument, without any further information about it.

5
  • 3
    This is actually a transformation of exists a. Pixel a => DynamicImage -> Image a into continuation-passing style. Aug 28, 2012 at 15:59
  • True, but that is not a valid Haskell type. Is there a non-continuation-passing-style variant that works in Haskell? Aug 28, 2012 at 21:20
  • data SomeImage = forall a. Pixel a => SomeImage (Image a) (which needs -XExistentialQuantification).
    – Vitus
    Aug 28, 2012 at 22:34
  • Also, it's transformation of (a) DynamicImage -> (exists a. Pixel a => Image a) - note the position of exists. (b) exists a. Pixel a => DynamicImage -> Image a is a bit stronger in the sense that you can go from b to a, but not the other way around.
    – Vitus
    Aug 28, 2012 at 22:59
  • Ok, you can introduce a new type. But to actually use the functions mentioned in the original question, which take a "Pixel a" and not a SomeImage, you’d again have to do a CPS transformation. Aug 29, 2012 at 8:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.