2016-10-04 79 views
1

我有一个函数getImage,它接受DynamicImage类型的输入并将其更改为图像。功能如下尝试在构造函数值上执行haskell模式匹配

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

以上定义来自Codec.Picture模块。但它给了我一个错误:

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. 

这是为什么不工作,我可以做到以下几点:

data Shape = Circle Float | Rectangle Float Float 

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

这是类似我的问题。

回答

4

您可能会考虑函数getImage的返回类型。 (我想你可能已经使用了包JuicyPixels您可以描述的,而不是该模块的包名......。)

让我们看到的数据类型的定义:

ImageY8 (Image Pixel8) 
ImageY16 (Image Pixel16) 

你可以看到返回getImage (ImageY8 image)getImage (ImageY16 image)的类型是不同的。前者是Image Pixel8,后者是Image Pixel16
因此,前函数的类型签名是DynamicImage -> Image Pixel8,后者是DynamicImage -> Image Pixel16。如你所知,一个函数不能有不同的类型签名。

您必须为每个类型签名重命名这些两个不同的函数。

+0

JuicyPixels更好。我在哪里可以找到它的proprer文档? –

+0

对不起,我的英文被打破了。我想在括号中说,我猜你已经使用了“JuicyPixels”,但你没有在你的问题中指出它。有'Codec.Picture',但它的名字可以被任何其他软件包使用。 这是你想问的吗? – QuietJoon

4

你认为getImage的类型是什么?编译器正在抱怨,因为一个方程的类型为DynamicImage -> Image Pixel8,另一个方程的类型为DynamicImage -> Image Pixel16,而这些类型不匹配。

你可以写的原因是:

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

是因为这两个公式的类型为Shape -> Float