2015-06-22 16 views
10

我正在玩type-aligned sequences,特別是我搞亂摺疊它們的想法。如何根據類型對齊的序列的foldMap來表達foldr?

class FoldableTA fm where 
    foldMapTA :: Category h => 
       (forall b c . a b c -> h b c) -> 
       fm a b d -> h b d 
    foldrTA :: (forall b c d . a c d -> h b c -> h b d) -> 
      h p q -> fm a q r -> h p r 
    foldlTA :: ... 

這是很容易先用foldMapTA到序列轉換爲用簡單的方式一種對齊列出了實現foldrTAfoldMapTA方面(即使用:摺疊式排列的序列看起來是這樣的類型對齊的列表類別),然後摺疊該列表。不幸的是,這可能是非常低效的,因爲長列表可能會被列爲短列表。我一直在想辦法使用類似於Data.Foldable中使用的技巧來更有效地定義右側和左側摺疊,但是這些類型讓我頭暈目眩。 Endo似乎不夠普通,我在其他方向上採取的每一步都會導致我獲得更多的類型變量,而我無法跟蹤。

回答

7

我發現,這typechecks:

{-# LANGUAGE RankNTypes #-} 
module FoldableTA where 

import Control.Category 
import Prelude hiding (id, (.)) 

class FoldableTA fm where 
    foldMapTA :: Category h => (forall b c . a b c -> h b c) -> fm a b d -> h b d 
    foldrTA :: (forall b c d . a c d -> h b c -> h b d) -> h p q -> fm a q r -> h p r 
    foldrTA f z t = appEndoTA (foldMapTA (\x -> TAEndo (f x)) t) z 

newtype TAEndo h c d = TAEndo { appEndoTA :: forall b. h b c -> h b d } 

instance Category (TAEndo h) where 
    id = TAEndo id 
    TAEndo f1 . TAEndo f2 = TAEndo (f1 . f2) 

沒有,如果它使任何意義,但與周圍這麼多類型的指標,我懷疑那裏是不有意義多類型檢查代碼的想法。

+2

事實上,我很確定任何終止和正確的類型是由參數性保證是正確的。非常感謝! – dfeuer

相關問題