代码之家  ›  专栏  ›  技术社区  ›  yong

我如何使MonadRandom成为Functor?

  •  10
  • yong  · 技术社区  · 11 年前

    随机fu包中的MonadRandom似乎不是Functor,因为我收到的错误如下:

    Could not deduce (Functor m) arising from a use of ‘_1’
    from the context (MonadRandom m)
    

    我已尝试添加以下代码:

    instance Functor MonadRandom where
        fmap = liftM
    
    instance Applicative MonadRandom where
        pure  = return
        (<*>) = ap
    

    但我得到了错误:

    The first argument of ‘Functor’ should have kind ‘* -> *’,
      but ‘MonadRandom’ has kind ‘(* -> *) -> Constraint’
    In the instance declaration for ‘Functor MonadRandom’
    
    The first argument of ‘Applicative’ should have kind ‘* -> *’,
      but ‘MonadRandom’ has kind ‘(* -> *) -> Constraint’
    In the instance declaration for ‘Applicative MonadRandom’
    
    1 回复  |  直到 11 年前
        1
  •  17
  •   Zeta    11 年前

    MonadRandom 是类,而不是类型 * -> * 喜欢 Maybe 例如通常,你会使用

    instance MonadRandom m => Functor m where
        fmap = liftM
    
    instance MonadRandom m => Applicative m where
        pure  = return
        (<*>) = ap
    

    然而 ,在这种情况下 instances of MonadRandom 已经是函子,所以现在实例是不明确的!相反,您应该添加 Functor 函数的约束:

    yourFunction :: (MonadRandom m, Functor m) => ...
    -- instead of yourFunction :: (MonadRandom m) => ...