删除Haskell中Data.Map的必要性

NoS*_*nse 0 regex haskell

好的,我正在努力学习哈斯克尔.有几次我发布了被投票的问题,因为我无法解释我想要实现的目标,但我将再次尝试一个新问题.

我找到了一段我想要修改的代码.这里是:

import qualified Data.Map as M

type Dict = M.Map String String

translate :: Dict -> [String] -> [String]
translate dict words = map trans words
  where
    trans :: String -> String
    trans w =
      case M.lookup w dict of
        (Just w') -> w'
        Nothing   -> "whatchamacallit"

testTranslation :: Dict -> IO ()
testTranslation dict = do
    print $ translate dict ["where", "is", "the", "colosseum"]

testInsertion :: Dict -> IO Dict
testInsertion dict = do
    return $ M.insert "colosseum" "colosseo" dict

main = 
    let dict = M.fromList [("where", "dove"), ("is", "e"), ("the", "il")]
    in do
          testTranslation dict
          dict'  <- testInsertion dict
          testTranslation dict'
          putStrLn "The original dictionary is unchanged:"
          testTranslation dict
Run Code Online (Sandbox Code Playgroud)

简而言之:它将取代elems的,其中鸽子,Ë和等,但它使用Data.Map.

所以我的问题是 - 有没有办法在不使用Data.Map的情况下做同样的事情

Ing*_*ngo 6

您可以将列表用作词典.当然,对于大字典来说这是不切实际的,因为查找是O(N).

这是列表查找的类型签名:

lookup :: Eq ? => ? -> [(?, ?)] -> Maybe ?
Run Code Online (Sandbox Code Playgroud)

这告诉以下内容:

给定一个类型为a的项和一个元组列表(a,b),该函数将返回Nothing或Just someb,其中someb的类型为b.

你可以很容易地发现你是否在该函数中玩了一下,ghci如果元组的第一部分等于键,它将返回元组中的第二个值.

因此:

lookup 42 [(1, "one"), (42, "it"), (2, "bar")]  
Run Code Online (Sandbox Code Playgroud)

应该

Just "it"
Run Code Online (Sandbox Code Playgroud)

lookup 77 [(1, "one"), (42, "it"), (2, "bar")]
Run Code Online (Sandbox Code Playgroud)

应该

Nothing
Run Code Online (Sandbox Code Playgroud)

您可以在GHCi中尝试它,并且它应该太难以在您的程序中摆脱Data.Map.据我所知,只有3个小的改动(不计入导入的丢弃).

  • @NoSense` return $("colosseum","colosseo"):dict` (3认同)