2016-05-24 74 views
3

我想要實現可摺疊的如何爲常量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. 
+0

你不能。你只能爲'數據C a b = C b'定義一個'Foldable(C a)'實例。在你的情況下,你需要像'instance Foldable(\ a - > Constant a b)'這樣的東西,但是我們在Haskell中沒有類型級的lambda表達式。 – chi

+0

偉大的問題,我只是想知道這一點,而試圖實現foldl –

回答

9

Constant a b不含任何b -s,所以我們折起它,就好像它是的b -s空列表:

instance Foldable (Constant a) where 
    foldr f z (Constant a) = z 

Constant a ba是不相關的Foldable例如,由於只涉及最後一個參數。因此,您無法在您的定義中真正使用a

2

我認爲唯一的可能性是:

data Constant a b = C a 

-- foldMap :: Monoid m => (b -> m) -> t b -> m 
instance Foldable (Constant a) where 
    foldMap f (C a) = mempty 

這是微不足道的解決方案。

這可能是有益的看到爲什麼你能爲這個定義做:

data Constant' a b = C' b 

-- foldMap :: Monoid m => (b -> m) -> t b -> m 
instance Foldable (Constant' a) where 
    foldMap f (C' a) = f a 

這裏tConstant' a,所以

  • 類型t bConstant' a b。這種類型的值具有結構C bval對於b類型的某個值bval
  • f的類型是b -> m,所以我們可以應用到fbval

在其他情況下,雖然,我們沒有從b值適用於f,所以我們能做的最好的是回報mempty

相關問題