简体   繁体   English

尝试对构造函数值执行haskell模式匹配

[英]Trying to perform haskell pattern matching on Constructor value

I have a function getImage which takes an input of type DynamicImage and changes it into an image. 我有一个功能getImage,它接受类型为DynamicImage的输入并将其更改为图像。 The function is as follows 功能如下

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

The above definitions are from the Codec.Picture module. 上面的定义来自Codec.Picture模块。 But it gives me an error: 但这给了我一个错误:

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.

Why is this not working as I can do the following: 为什么这不起作用,因为我可以执行以下操作:

data Shape = Circle Float | Rectangle Float Float

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

which is similar to my question. 这类似于我的问题。

You may concern the return type of the function getImage . 您可能会关注getImage函数的返回类型。 (I think you may has used the package JuicyPixels . You may describe the package name instead of the module...) (我认为您可能已经使用了JuicyPixels软件包。您可以描述软件包名称而不是模块...)

Let see the definition of data type: 让我们看一下数据类型的定义:

ImageY8 (Image Pixel8)
ImageY16 (Image Pixel16)

You can see that the return type of getImage (ImageY8 image) and getImage (ImageY16 image) is different. 您会看到getImage (ImageY8 image)getImage (ImageY16 image)的返回类型不同。 The former is Image Pixel8 and the latter is Image Pixel16 . 前者是Image Pixel8 ,后者是Image Pixel16
Therefore, the type signature of former function is DynamicImage -> Image Pixel8 and the latter is DynamicImage -> Image Pixel16 . 因此,前一个函数的类型签名为DynamicImage -> Image Pixel8 ,后者为DynamicImage -> Image Pixel16 As you know, one function could not have different type signatures. 如您所知,一个函数不能具有不同的类型签名。

You have to rename these two different functions for each type signature. 您必须为每种类型签名重命名这两个不同的函数。

What would you expect the type of getImage to be? 您希望getImage的类型是什么? The compiler is complaining because one equation has the type DynamicImage -> Image Pixel8 and the other has type DynamicImage -> Image Pixel16 , and these types don't match. 编译器抱怨是因为一个方程式的类型为DynamicImage -> Image Pixel8 ,而另一个方程式的类型为DynamicImage -> Image Pixel8 DynamicImage -> Image Pixel16 ,而这些类型不匹配。

The reason you can write: 您可以写的原因:

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

Is because both equations have type Shape -> Float . 是因为两个方程式的类型都是Shape -> Float

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM