[英]Unification Weirdness in Typeclass Instance
假設我有以下(愚蠢的)課程:
class BlindMap m where
mapB :: m a -> m b
我可以提供以下[]
實例:
instance BlindMap [] where
mapB = map id
RHS的類型為[a] -> [a]
,應與[a] -> [b]
統一,但GHC並不這樣認為:
Couldn't match type ‘a’ with ‘b’
‘a’ is a rigid type variable bound by
the type signature for mapB :: [a] -> [b] at dingas.hs:11:5
‘b’ is a rigid type variable bound by
the type signature for mapB :: [a] -> [b] at dingas.hs:11:5
Expected type: a -> b
Actual type: b -> b
Relevant bindings include
mapB :: [a] -> [b]
In the first argument of ‘map’, namely ‘id’
In the expression: map id
我在這里想念什么?
提前致謝。
我在這里想念什么?
給定此類值的列表, map id
會生成某種任意類型的值的列表。 [a] -> [b]
承諾在給定可能不同類型的值的列表的情況下,產生某種任意類型的值的列表。
因此,它期望的是a- a -> b
,但是基於id的函數只能取返回值,因此b -> b
。
更籠統地說,您說將提供具有以下類型的函數:
forall a b.[a] -> [b]
在您的實例定義中。 編譯器對此表示贊同。
現在您有了一個實例,編譯器確實需要查看該神奇功能。 並且它拒絕所有比您承諾的要少的代碼。
在繼續之前,您應該嘗試編寫一個函數
forall a b. a -> b
並且您將看到最多可以提出以下內容:
f x = f x
g x = error "not terminating."
而且,只要沒有可用的元素映射功能,就只能編寫以下實例:
instance BlindMap (Maybe a) where mapB _ = Nothing
instance BlindMap ([a]) where mapB _ = []
以同樣的精神等等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.