更多rmonad图书馆?

时间:2011-09-08 03:01:41

标签: haskell monads monad-transformers

我想用RMonad做一些基本的事情。是否有使用“as monad”功能的方法

  • 有一个身份rmonad,将monad变形金刚应用到?
  • 有像StateT变形金刚这样的常见内容吗?
  • 为现有的monad添加约束? (例如,如果有人希望StateT有其他限制条件)

不幸的是,我还没有掌握数据系列之类的东西,这些东西让它起作用......否则我可能很乐意自己编写代码。

修改

我从图书馆来源一起攻击StateT,看看它是否有效......

[http://pastebin.com/VT3uyEgr]

1 个答案:

答案 0 :(得分:4)

快速浏览后,您的StateT版本看起来是正确的。不幸的是,使用RMonad等。人。 需要复制几乎所有内容;我开始使用“合适”编写一些代码并放弃,因为它涉及太多的重复(最后我并不需要它)。

修改

从我对Suitable的工作原理的记忆中,它是这样的:

考虑Functor类:Set不能是它的实例,因为它需要额外的Ord约束。

一种天真的方法就像:

{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}

import qualified Data.Set as S

class MyFunctor c a | c -> a where
      myfmap :: (MyFunctor c b) => (a -> b) -> c a -> c b

instance (Ord a) => MyFunctor S.Set a where
      myfmap = S.map

但是这会返回以下错误:

Error: test.hs:11:16: Could not deduce (Ord b) arising from a use of `S.map'
    from the context (Ord a)
      bound by the instance declaration at /tmp/test.hs:10:10-37
    or from (MyFunctor S.Set b)
      bound by the type signature for
                 myfmap :: MyFunctor S.Set b => (a -> b) -> S.Set a -> S.Set b
      at /tmp/test.hs:11:7-20
    Possible fix:
      add (Ord b) to the context of
        the type signature for
          myfmap :: MyFunctor S.Set b => (a -> b) -> S.Set a -> S.Set b
        or the instance declaration
    In the expression: S.map
    In an equation for `myfmap': myfmap = S.map
    In the instance declaration for `MyFunctor S.Set a'

这是为什么?这是因为在实例级别没有保留或找到约束,因此GHC没有意识到在使用myfmap时,Ord上应该有b约束。

Suitable类型用于显式创建约束字典,允许您指定这些类型的约束:

import Data.Suitable
import qualified Data.Set as S

class MyFunctor c where
      myfmap :: (Suitable c a, Suitable c b) => (a -> b) -> c a -> c b

instance MyFunctor S.Set where
      myfmap f s = withConstraintsOf s
                   $ \ SetConstraints
                       -> withResConstraints $ \ SetConstraints -> S.map f s

(其中SetConstraints已在Data.Suitable)中定义

这个实现有效,但它确实使类型签名更复杂,方法实现有点毛茸茸(注意我们需要引入SetConstraints 两次:一次用于Set aSet b的另一个。Suitable。请注意,对于没有任何约束的类型,不需要Suitable约束函数。

我已经开始尝试在Typeclassopedia中创建类的{{1}}版本但放弃了,因为实例变得非常毛茸茸。