haskell - 对于类型对齐的序列,我如何用 foldMap 来表达 foldr?

标签 haskell types monoids type-variables foldable

我在玩type-aligned sequences ,特别是我正在搞乱折叠它们的想法。一个可折叠的类型对齐序列看起来像这样:

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 :: ...

很容易实现foldrTA根据 foldMapTA首先使用 foldMapTA以简单的方式将序列转换为类型对齐的列表(即,使用类型对齐的列表类别),然后折叠该列表。不幸的是,这可能非常低效,因为长列表可能会附加到短列表之前。我一直在尝试找出一种方法来使用类似于 Data.Foldable 中使用的技巧。更有效地定义左右折叠,但类型让我头晕目眩。 Endo似乎不够通用,无法做到这一点,而且我在其他方向上采取的每一步都会导致我获得更多的类型变量,而我无法跟踪。

最佳答案

我发现这个类型检查:

{-# 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)

不知道这是否有意义,但是有这么多类型索引,我怀疑有很多类型检查代码没有意义。

关于haskell - 对于类型对齐的序列,我如何用 foldMap 来表达 foldr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30985070/

相关文章:

haskell - 如何组合将 bool 值返回给一个函数的函数

haskell - 如何通过纯函数计算将 "waste"精确到仅 "burning CPU"的大致指定时间?

haskell - 通过动态函数列表传输数据

haskell - 为什么foldr有一个 'b'类型的变量?

java - 如何在java中划分两个长变量

c++ - 如何处理为相同输入数据类型返回不同数据类型的 api?

c++ - 在 C++ 中选择运行时数组或 vector

haskell - 在 Haskell 中获取数字的除数列表时出现问题

string - 文本或字节串

macos - 如何在 Mac OS 上安装 Haskell