Peter
Peter

Reputation: 71

How to use Data.Map ! Operator?

I have the following anti-pattern in my code:

existsFunc :: Maybe Item -> Item

This is part of a larger piece of code that checks if a name is in a Dictionary:

genFunc :: InputType -> Item
genFunc input = existsFunc(Data.Map.lookup input (myDictionary))
  
existsFunc :: Maybe Item -> Item
existsFunc (Just x) = x
existsFunc Nothing = error "input missing from dictionary"

I would like to replace the above anti-pattern with with ! Map operator, but am having trouble understanding the syntax. How can the ! be applied?

genFunc :: InputType -> Item
genFunc input = ! Data.Map.lookup input (myDictionary) Error: element not in the map
genFunc input = Data.Map.lookup input (myDictionary)

edit:

I also thought that it could be applied in the following way:

genFunc :: InputType -> Item
genFunc input = Data.Map.lookup input (myDictionary) ! input Error: element not in the map
genFunc input = Data.Map.lookup input (myDictionary)

Upvotes: 0

Views: 134

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152737

Like this:

genFunc input = myDictionary Data.Map.! input

Usually people give a short name like M to the Data.Map module, using an import like:

import qualified Data.Map as M

Then this shorter version is right:

genFunc input = myDictionary M.! input

Probably not even worth naming this function. Just use M.! inline wherever you were gonna use genFunc.

Keep in mind that ! is exactly as much an antipattern as your existsFunc. So don't think you're fixing that here -- a real fix involves handling Nothing from lookup for real. Each application's needs here vary; sometimes using a default value is correct, sometimes raising an error in some containing monad is correct, sometimes propagating the Maybe into the caller's return type is correct, ...and half a dozen other responses exist out there, I'm sure.

Upvotes: 3

Related Questions