我正在尝试编写一个非常简单的编辑器,如"ed"。在这个程序中,我试图使用映射来构建转换字符串命令在动作中执行的控制。下面是一段代码:
commands :: Map String ([Handle] -> IO ())
commands = fromAscList [
("o",list -> print "Insert name of the file to be opened" >> getLine >>= nomefile ->
openFile nomefile ReadWriteMode >>= handle -> editor (handle:list)),
("i",list -> case list of { [] -> print "No buffer open" ; handle:res -> write handle } >> editor list),
("q",list -> if list == [] then return () else mapM_ hClose list >> return ())
]
editor :: [Handle] -> IO()
editor list = do
command <- getLine
let action = lookup command commands
case action of
Nothing -> print "Unknown command" >> editor list
Just act -> act list
问题是,当我执行编辑器函数时,无论是在ghci还是在可执行文件中,当我输入"o"时,我得到的消息是"未知命令",而不是调用函数打开文件。我尝试了相同的代码使用关联列表而不是地图,在这种情况下,它的工作原理。那么问题是什么呢?
更奇怪的是,如果我在ghci的映射命令中调用键,它也会返回一个包含字符串"o"的列表。
事先感谢您的帮助。
commands :: Map String ([Handle] -> IO ())
commands = fromAscList [
("o",_),
("i",_),
("q",_)
]
,
ghci> Data.List.sort ["o","i","q"]
["i","o","q"]
你欺骗了Data.Map
,所以它构造了一个不满足不变量的Map
。因此,在Map
中查找东西不起作用,因为请求被发送到错误的分支(有时)。