我想要實現可摺疊的如何爲常量a實現可摺疊實例b =常量a?
data Constant a b = Constant a
這是我簡單的嘗試:
instance Foldable (Constant a) where
foldr f b (Constant a) = f a b
編譯錯誤我想了解的部分是:
Couldn't match expected type ‘a1’ with actual type ‘a’
‘a1’ is a rigid type variable bound by the type signature for
foldr :: (a1 -> b -> b) -> b -> Constant a a1 -> b
,你可以看到摺疊功能採用我無法訪問的常量中的「幻像類型」(?)a1
;我只能訪問a
。
我該如何解決這個問題?請解釋你的解決方案,因爲我很困惑。
整個編譯錯誤是:
try2/chap20/ex1.hs:9:30: Couldn't match expected type ‘a1’ with actual type ‘a’ …
‘a’ is a rigid type variable bound by
the instance declaration
at /Users/moron/code/haskell/book/try2/chap20/ex1.hs:8:10
‘a1’ is a rigid type variable bound by
the type signature for
foldr :: (a1 -> b -> b) -> b -> Constant a a1 -> b
at /Users/moron/code/haskell/book/try2/chap20/ex1.hs:9:3
Relevant bindings include
a :: a
(bound at /Users/moron/code/haskell/book/try2/chap20/ex1.hs:9:23)
f :: a1 -> b -> b
(bound at /Users/moron/code/haskell/book/try2/chap20/ex1.hs:9:9)
foldr :: (a1 -> b -> b) -> b -> Constant a a1 -> b
(bound at /Users/moron/code/haskell/book/try2/chap20/ex1.hs:9:3)
In the first argument of ‘f’, namely ‘a’
In the expression: f a b
Compilation failed.
你不能。你只能爲'數據C a b = C b'定義一個'Foldable(C a)'實例。在你的情況下,你需要像'instance Foldable(\ a - > Constant a b)'這樣的東西,但是我們在Haskell中沒有類型級的lambda表達式。 – chi
偉大的問題,我只是想知道這一點,而試圖實現foldl –