ceth
ceth

Reputation: 45325

Map Map.lookup to list

I have the Data.Map (freqMap) which looks like:

"SO" -> "10"
"OM" -> "20"
...

so every two letters I map some value.

And I have a list of strings:

["SO", "OM", "ME", "ET" ...]

I need to transform this list to another list:

["10", 20", ...]

where every element is a value from my Map (freqMap).

I have created solution using recursion:

score_ngram :: [String] -> Map.Map String String -> [Int] -> [Int]
score_ngram [] scores result = result
score_ngram ngrams scores result = score_ngram (tail ngrams) scores (result ++ [value])
    where value = case (Map.lookup (head ngrams) scores) of
        Just v -> read v :: Int
        Nothing -> 0

But i'm just wondering if it is possible to get it using map function ?

Something like this:

map (Map.lookup element_of_list freqMap) ["SO", "OM", "ME", "ET" ...]

Upvotes: 1

Views: 616

Answers (1)

Assuming you want a score of 0 for nonexistent ngrams, you can use:

map (read . flip (Map.findWithDefault "0") freqMap) ["SO", "OM", "ME", "ET" ...]

Upvotes: 4

Related Questions