缺少 Monadstate 实例

Missing Monadstate instance

我正在尝试使用这个库构建一个 slackbot:https://hackage.haskell.org/package/slack-api,只是为了多学一点 haskell,并希望最终理解 monads -_-.

然后我有以下类型:

data BotState = BotState
  { 
    _appState :: AppState
  }

makeLenses ''BotState


type AppState = HM.Map String ChannelState

emptyState :: AppState
emptyState = HM.empty

data ChannelState = ChannelState
{ _counter :: Int}

type Bot = Slack.Slack BotState

我 运行 我的机器人有:

initApp = lookupEnv "SLACK_API_TOKEN" >>=
  \apiToken -> case apiToken of
    Nothing -> throwM ApiTokenMissingException
    Just t -> void $ Slack.runBot (Slack.SlackConfig t) runApp $ BotState emptyState

其中:

runApp :: Slack.Event -> Bot ()
runApp m@(Slack.Message cid uid body _ _ _) = sendMessage cid "GAH I CAN HAZ CHZBURGHER!" 

这 运行 很好,现在我想添加更新系统状态的功能(通过递增计数器,或以其他方式)。

所以我向我的机器人添加了一个 modifyState 函数:

modifyState :: (AppState -> AppState) -> Bot ()
modifyState f = uses Slack.userState $ view appState >>=
  \state -> modifying Slack.userState $ set appState $ f state 

这中断于:

 No instance for (Control.Monad.State.Class.MonadState
                           (Slack.SlackState BotState) ((->) BotState))
          arising from a use of ‘modifying’
        In the expression: modifying Slack.userState
        In the expression:
          modifying Slack.userState $ set appState $ f state
        In the second argument of ‘(>>=)’, namely
          ‘\ state -> modifying Slack.userState $ set appState $ f state’

考虑到 modifying:

的签名,这是有道理的
modifying :: MonadState s m => ASetter s s a b -> (a -> b) -> m ()

但是,在查看 Slack.userState 的文档时:

userState :: forall s s. Lens (SlackState s) (SlackState s) s s Source

然后:

data SlackState s

 ... Constructor ...
    Instances
Show s => Show (SlackState s)Source  
MonadState (SlackState s) (Slack s)Source   

那么为什么 BotState 不是 MonadState 的实例呢?我该如何解决这个问题?

$ 运算符具有固定性 0,而 >>= 具有固定性 1,因此这样的代码可以工作:

main :: IO ()
main = do
  putStrLn "hello world" >>= \_ -> putStrLn "hi"

但不是这个:

main :: IO ()
main = do
  putStrLn $ "hello world" >>= \_ -> putStrLn "hi"

它被解释为:

main :: IO ()
main = do
  putStrLn ("hello world" >>= \_ -> putStrLn "hi")

要查看固定信息,请使用 ghci:info 命令:

 :info $
($) ::
  forall (r :: ghc-prim-0.5.0.0:GHC.Types.RuntimeRep) a (b :: TYPE
                                                                r).
  (a -> b) -> a -> b
    -- Defined in ‘GHC.Base’
infixr 0 $
 :info >>=
class Applicative m => Monad (m :: * -> *) where
  (>>=) :: m a -> (a -> m b) -> m b
  ...
    -- Defined in ‘GHC.Base’
infixl 1 >>=

此外,如果您不确定,这里总是有很好的旧括号来解救:)