NoSense
NoSense

Reputation: 959

Remove the necessity of Data.Map in Haskell

Ok, I'm trying to learn haskell. Couple of times I've posted questions that has been down voted because I can't explain well what I'm trying to achieve, but I'm going to try again with a new question.

I find a piece of code that I want to modify a bit. Here it is:

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

In short: It will replace the elems where with dove, is with e and e.t.c but it is using Data.Map.

So my question is - Is there a way to do the same thing without using Data.Map

Upvotes: 0

Views: 177

Answers (1)

Ingo
Ingo

Reputation: 36339

You can use lists as dictionaries. Of course, it will not be practical for big dictionaries, because the lookup is O(N).

Here is the type signature of the list lookup:

lookup :: Eq α => α -> [(α, β)] -> Maybe β

This tells the following:

Given some item of type a and a list of tuples (a,b), the function will return Nothing or Just someb, where someb is of type b.

As you could easily find out if you played around a bit with that function in ghci, it will return the second value in the tuple if the first part of the tuple equals the key.

Hence:

lookup 42 [(1, "one"), (42, "it"), (2, "bar")]  

should be

Just "it"

whereas

lookup 77 [(1, "one"), (42, "it"), (2, "bar")]

should be

Nothing

You can try it in GHCi and it should ot be too hard to get rid of Data.Map in your program. As far as I can see, there are just 3 small changes to do (not counting the dropping of the import).

Upvotes: 6

Related Questions