繁体   English   中英

每个monad都是一个applicative functor - 推广到其他类别

[英]Every monad is an applicative functor — generalizing to other categories

我可以很容易地在Haskell中定义一般的FunctorMonad类:

class (Category s, Category t) => Functor s t f where
    map :: s a b -> t (f a) (f b)

class Functor s s m => Monad s m where
    pure :: s a (m a)
    join :: s (m (m a)) (m a)
    join = bind id
    bind :: s a (m b) -> s (m a) (m b)
    bind f = join . map f

我正在阅读这篇文章 ,它解释了一个应用函子是一个松散(封闭或幺半)的仿函数。 它是在(指数或幺半群)bifunctor方面这样做的。 我知道在Haskell类别中,每个Monad都是Applicative ; 我们如何概括? 我们应该如何选择(指数或幺半群)仿函数来定义Applicative 令我困惑的是我们的Monad类似乎没有任何关于(闭合或幺半)结构的概念。

编辑:评论者说通常不可能,所以现在问题的一部分是可能的。

令我困惑的是我们的Monad类似乎没有任何关于(闭合或幺半)结构的概念。

如果我正确理解你的问题,那将通过monad的张力来提供。 Monad类没有它,因为它是Hask类的固有特性。 更具体地说,假设是:

t :: Monad m => (a, m b) -> m (a,b)
t (x, my) = my >>= \y -> return (x,y) 

基本上,monoidal仿函数方法中涉及的所有monoidal东西都发生在目标类别上。 它可以正式化,因此

class (Category s, Category t) => Functor s t f where
  map :: s a b -> t (f a) (f b)

class Functor s t f => Monoidal s t f where
  pureUnit :: t () (f ())
  fzip :: t (f a,f b) (f (a,b))

s -morphisms只有进来,如果你考虑monoidal函子的法律,大致说的monoidal结构s应该被映射到这个monoidal结构t由仿函数。

也许更有见地的是将fmap分解为类方法,因此很清楚“func - ” - 函子的一部分是做什么的:

class Functor s t f => Monoidal s t f where
  ...
  puref :: s () y -> t () (f y)
  puref f = map f . pureUnit
  fzipWith :: s (a,b) c -> t (f a,f b) (f c)
  fzipWith f = map f . fzip

Monoidal ,我们可以找回我们古老的Hask - Applicative

pure :: Monoidal (->) (->) f => a -> f a
pure a = puref (const a) ()

(<*>) :: Monoidal (->) (->) f => f (a->b) -> f a -> f b
fs <*> xs = fzipWith (uncurry ($)) (fs, xs)

要么

liftA2 :: Monoidal (->) (->) f => (a->b->c) -> f a -> f b -> f c
liftA2 f xs ys = fzipWith (uncurry f) (xs,ys)

也许在这种情况下更有趣的是另一个方向,因为它向我们展示了在一般情况下与monad的连接:

instance Applicative f => Monoidal (->) (->) f where
  pureUnit = pure
  fzip = \(xs,ys) -> liftA2 (,) xs ys
       = \(xs,ys) -> join $ map (\x -> map (x,) ys) xs

lambdas和tuple部分在一般类别中不可用,但是它们可以被翻译成笛卡尔封闭类别


我使用(,)作为两个monoidal类别的产品,带有identity元素() 更一般地,您可以为产品及其各自的标识元素写入data I_sdata I_ttype family (⊗) xytype family (∙) xy

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM