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

Rat*_*thy 1 haskell pattern-matching

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

getImage (ImageY8 image) = image 
getImage (ImageY16 image) = image
Run Code Online (Sandbox Code Playgroud)

以上定义来自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.
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用,因为我可以执行以下操作:

data Shape = Circle Float | Rectangle Float Float

area (Circle r) = 3.14 * r * r
area (Rectangle a b) = a * b
Run Code Online (Sandbox Code Playgroud)

这与我的问题类似.

Qui*_*oon 5

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

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

ImageY8 (Image Pixel8)
ImageY16 (Image Pixel16)
Run Code Online (Sandbox Code Playgroud)

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

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