成对的Monad实例 [英] Monad instance for pairs

查看:97
本文介绍了成对的Monad实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题显示了(,) a b的实例定义,其中aMonoid的实例.

This question shows an instance definition for (,) a b, where a is an instance of Monoid.

但是,我不知道如何为(,) a b编写类似的内容,而bMonoid的实例?只要写出定义,我就可以做到:

However, I don't know how to write similar thing for (,) a b, and b is an instance of Monoid? I can basically do this as long as I can write the definition:

instance Monoid b => Monad ((,) ???) where
    return a = (a,mempty)
    ~(a,b) >>= f = let (c,b1) in f a in (c,b `mappend` b1)

所以问题是如何编写???部分?

So the question is how to write the ??? part?

更新

实际上,这个问题是更常见问题的特例:是否可以编写作用于某些未出现在末尾的类型的类型类的实例?就我而言,类型构造函数是(,) a b,我想使其成为Monad a的实例,其中a不是最后一个类型参数.

Actually this question is special case of a more generic problem: is it possible to write instance of type classes that act on some types that is not appear at the end? In my case, the type constructor is (,) a b, and I want to make it an instance of Monad a where a is not the last type parameter.

推荐答案

我们可以编写,因为现在同义词在这种情况下不适合,所以我们使用newtype:

We could write, for now synonyms works inappropriate for this case, so we use newtype:

newtype RevTuple b a = RevTuple { totuple :: (a , b) }

instance Monoid b => Monad (RevTuple b) where
    return a = RevTuple (a,mempty)
    (RevTuple (a,b)) >>= f = 
                 let RevTuple (c,b1) = f a in RevTuple (c,b `mappend` b1)

这篇关于成对的Monad实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆