在haskell中使用Data.Map的奇怪错误

Gio*_*ssa 1 haskell map ghc

我正在尝试编写一个非常简单的编辑器,如"ed".在这个程序中,我正在尝试使用映射来构建控件,该控件在要执行的操作中转换string-command.这是一段代码:

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
Run Code Online (Sandbox Code Playgroud)

问题是,当我执行编辑器功能时,无论是在ghci还是在可执行文件中,当我输入"o"时,我收到消息"未知命令"而不是调用函数来打开文件.我使用关联列表而不是Map尝试了相同的代码,在这种情况下它可以工作.那么这里可能出现什么问题呢?

更奇怪的是,如果我在ghci中的映射命令上调用键,它返回一个包含字符串"o"的列表.

我提前感谢你的帮助.

Dan*_*her 6

commands :: Map String ([Handle] -> IO ())
commands = fromAscList [
   ("o",_),
   ("i",_),
   ("q",_)
]
Run Code Online (Sandbox Code Playgroud)

ghci> Data.List.sort ["o","i","q"]
["i","o","q"]
Run Code Online (Sandbox Code Playgroud)

你撒谎Data.Map,所以它构造了一个Map不满足所需的不变量.因此查找中的内容Map不起作用,因为请求被发送到错误的分支(有时).

  • `fromAscList`要求对列表进行排序.如果您使用过`fromList`,那就可以了.如果对键进行排序,则可以更有效地构建"Map",这就是"fromAscList"和"fromDistinctAscList"存在的原因. (4认同)