下面是一个使用haskeline和StateT转换器创建有状态输入命令循环的简单示例:
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleContexts #-}
import Control.Monad.State.Strict
import Control.Monad.Trans (lift)
import System.Console.Haskeline
main = runStateT (runInputT defaultSettings loop) ""
check ma b fb = maybe b fb ma
commands :: (MonadState String m, MonadIO m) => [(String, [String] -> InputT m ())]
commands = [ ("set", performSet), ("get", performGet) ]
performSet args = lift $ put (head args)
performGet _ = do v <- lift get; outputStrLn $ "v = " ++ show v
loop :: (MonadException m, MonadState String m) => InputT m ()
loop = do
minput <- getInputLine "% "
check minput (return ()) $ \inp -> do
let args = words inp
case args of
[] -> loop
(arg0:argv) -> do
case lookup arg0 commands of
Nothing -> do outputStrLn "huh?"; loop
Just handler -> do handler argv; loop列表commands包含所有可识别的命令-对(名称、处理程序)。我希望使用如下表达式获取名称列表:
commandNames = map fst commands但是类型检查器抱怨“(MonadState String m0)由于使用‘m0’-类型变量‘m0’是不明确的.”
我需要做什么来满足类型检查?
发布于 2014-12-08 01:28:52
commands是多态的,它有一个类型变量m,但是commandNames :: [String]没有任何类型变量。这意味着(除非有一些内置的默认值)类型推断将无法推断commands的类型变量。你可以做两件事。您可以自己为commands提供一个类型
commandNames :: [String]
commandNames = map fst (commands :: [(String, [String] -> InputT (StateT String IO) ())])或者,您可以更改代码,以便根据较少的变量定义具有更多类型变量的值。
commandNames :: [String]
commandNames = ["set", "get"]
commands :: (MonadState String m, MonadIO m) => [(String, [String] -> InputT m ())]
commands = zip commandNames [performSet, performGet]https://stackoverflow.com/questions/27349748
复制相似问题