[英]Trying to perform haskell pattern matching on Constructor value
我有一個功能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
這類似於我的問題。
您可能會關注getImage
函數的返回類型。 (我認為您可能已經使用了JuicyPixels
軟件包。您可以描述軟件包名稱而不是模塊...)
讓我們看一下數據類型的定義:
ImageY8 (Image Pixel8)
ImageY16 (Image Pixel16)
您會看到getImage (ImageY8 image)
和getImage (ImageY16 image)
的返回類型不同。 前者是Image Pixel8
,后者是Image Pixel16
。
因此,前一個函數的類型簽名為DynamicImage -> Image Pixel8
,后者為DynamicImage -> Image Pixel16
。 如您所知,一個函數不能具有不同的類型簽名。
您必須為每種類型簽名重命名這兩個不同的函數。
您希望getImage
的類型是什么? 編譯器抱怨是因為一個方程式的類型為DynamicImage -> Image Pixel8
,而另一個方程式的類型為DynamicImage -> Image Pixel8
DynamicImage -> Image Pixel16
,而這些類型不匹配。
您可以寫的原因:
area (Circle r) = …
area (Rectangle a b) = …
是因為兩個方程式的類型都是Shape -> Float
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.