Incerteza
Incerteza

Reputation: 34934

Pattern matching over Data.Map

I did a search but, surprisingly, didn't find anything that would help me to perform pattern matching over it. I need to make sure that in my Map "variable" exactly 3 keys. That's it. Instead of "if ... then ... else", I want to go with pattern matching as it is easier to read and seems to be more haskell way. So:

myFunction :: Map String String
--.......................

main = do
  let var1 = myFunction
  -- how do I ensure it has exactly 3 keys in it and if not raise an error?  

Upvotes: 3

Views: 1229

Answers (2)

bennofs
bennofs

Reputation: 11973

You could pattern match on M.toList:

import qualified Data.Map as M
-- ...
main = do
  case (M.toList myFunction) of
    [a,b,c] -> ... -- exactly 3 arguments
    _       -> ... -- more or less than 3 arguments

Upvotes: 6

Joachim Breitner
Joachim Breitner

Reputation: 25782

You cannot pattern match on abstract data types, as you don’t have access to their constructors¹, so you will have to work with the functions provided by the `Data.Map´ module.

But note that there is a size :: Map k a -> Int function you can use. And if you don’t like if .. then .. else .. (which is in no way wrong or unhaskellish), you can use pattern guards:

foo m | size m == 3 = ...
      | otherwise = error "Not three element"

¹ Disregarding view patterns and pattern synonyms here, but these are just syntactic surgar.

Upvotes: 11

Related Questions