Haskell polymorphic deconstruction

haskell, polymorphism, types

Solution

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.

Problem

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?

Original source