【发布时间】:2018-06-19 15:51:56
【问题描述】:
为什么我们将结构的翻转称为“序列”,为什么我们要谈论“遍历”和“遍历”?
我正在将这些概念的实现添加到 haskell 中以供讨论...
class (Functor t, Foldable t) => Traversable t where
{-# MINIMAL traverse | sequenceA #-}
-- | Map each element of a structure to an action, evaluate these actions
-- from left to right, and collect the results. For a version that ignores
-- the results see 'Data.Foldable.traverse_'.
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
traverse f = sequenceA . fmap f
-- | Evaluate each action in the structure from left to right, and
-- and collect the results. For a version that ignores the results
-- see 'Data.Foldable.sequenceA_'.
sequenceA :: Applicative f => t (f a) -> f (t a)
sequenceA = traverse id
【问题讨论】:
-
sequence(动词):将可遍历的“容器”“内部”的应用“动作”序列(名词)转化为产生结果序列的应用“动作”。对于列表,可以定义为sequenceA = foldr (liftA2 (:)) (pure [])。traverse可以称为mapA,因为它与mapM平行。我猜映射是一种遍历。 -
另外,对于列表,
sequence [] = return [] ; sequence (x:xs) = do { x <- x; xs <- sequence xs; return (x:xs) }其中所有“计算”xs都是预先知道的,因此 Monad 的全部功能能够根据先前运行的计算结果创建新计算(如y <- foo x) 实际上不需要。因此,Applicative Functor 是一个比 Monadic Functor 更不强大、更通用的 Functor。
标签: haskell category-theory traversable