尝试在Constructor值上执行haskell模式匹配

时间:2016-10-04 05:48:20

标签: haskell pattern-matching

我有一个函数getImage,它接受DynamicImage类型的输入并将其更改为图像。功能如下

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

这与我的问题类似。

2 个答案:

答案 0 :(得分:5)

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

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

ImageY8 (Image Pixel8)
ImageY16 (Image Pixel16)

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

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

答案 1 :(得分:4)

您期望getImage的类型是什么?编译器抱怨,因为一个等式的类型为DynamicImage -> Image Pixel8而另一个等式的类型为DynamicImage -> Image Pixel16,而且这些类型不匹配。

你可以写的原因:

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

是因为两个方程都有Shape -> Float类型。

相关问题