一个monad可以成为一个共同体吗? [英] Can a monad be a comonad?
本文介绍了一个monad可以成为一个共同体吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题是:可以是monad 和一个comonad吗?
我预见了两个可能的答案:
- 是的,这是常见而且非常有用的。
- 不,他们做这样不同的工作,以至于没有理由
- 不,他们做这样不同的工作,以至于没有理由
所以,这是什么?
>解决方案是的。将一些注释转换为答案:
newtype Identity a = Identity {runIdenity :: a}派生Functor
实例Monad身份其中
return =身份
加入= runIdentity
实例CoMonad身份其中
coreturn = runIdentity
cojoin =身份
读者和作者是完全对偶的,如
所示 class CoMonoid m其中
comempty ::(m,a) - > a
comappend :: m - > (m,m)
--every haskell类型是一个CoMonoid
- 这是因为CCC很无聊!
实例Monoid a => Monad((,)a)其中
返回x =(mempty,x)
join(a,(b,x))=(a<> b,x)
instance CoMonoid a => CoMonad((,)a)其中
coreturn = comempty
cojoin =关联。第一个comappend
实例CoMonoid a => Monad(( - >)a)其中
return = flip(咖喱comempty)
加入f = uncurry f。 comappend
instance Monoid a => CoMonad(( - >)a)其中
coreturn f = f mempty
cojoin fab = f(a<> b)
I know what a monad is. I think I have correctly wrapped my mind around what a comonad is. (Or rather, what one is seems simple enough; the tricky part is comprehending what's useful about this...)
My question is: Can something be a monad and a comonad?
I foresee two possible answers:
- Yes, this is common and widely useful.
- No, they do such different jobs that there would be no reason to want something to be both.
So, which is it?
解决方案
Yes. Turning some comments into an answer:
newtype Identity a = Identity {runIdenity :: a} deriving Functor
instance Monad Identity where
return = Identity
join = runIdentity
instance CoMonad Identity where
coreturn = runIdentity
cojoin = Identity
Reader and Writer are exact duals, as shown by
class CoMonoid m where
comempty :: (m,a) -> a
comappend :: m -> (m,m)
--every haskell type is a CoMonoid
--that is because CCCs are boring!
instance Monoid a => Monad ((,) a) where
return x = (mempty,x)
join (a,(b,x)) = (a <> b, x)
instance CoMonoid a => CoMonad ((,) a) where
coreturn = comempty
cojoin = associate . first comappend
instance CoMonoid a => Monad ((->) a) where
return = flip (curry comempty)
join f = uncurry f . comappend
instance Monoid a => CoMonad ((->) a) where
coreturn f = f mempty
cojoin f a b = f (a <> b)
这篇关于一个monad可以成为一个共同体吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文