I'm a Haskell newbie trying to understand how to work with the Data.Map structure, lazy evaluation, and the Maybe type.
In Python I can define a dictionary structure whose values are functions. Given a key I can then use the corresponding function:
d = {"+": lambda x,y: x+y}
def f(key, v1, v2):
if key in d:
return d[key](v1, v2)
else:
return 0
I've tried to do a similar thing in Haskell but it does not compile.
d = Map.fromList [('+', (+))]
f :: Char -> Integer -> Integer -> Integer
f key v1 v2 =
if k == Nothing
then 0
else f v1 v2
where
k = Map.lookup key d
(Just f) = k
This doesn't compile and returns an error like
No instance for (Eq (Integer -> Integer -> Integer))
I believe it's because Map.lookup '+' d only returns an instance of Maybe (Integer -> Integer -> Integer) not (Just (+)) or Nothing. And I assume this has to do with lazy evaluation.
Is there a Haskell-like way to do this kind of thing? Am I working with the Maybe type incorrectly? Can I force evaluation of the lookup?
This came up because I was trying to implement a reverse polish calculator in Haskell. I used the dictionary to organize the possible functions I could be using. I found a nice solution (https://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm#Haskell) without a dictionary but now I just want to understand how to properly access values in a Haskell Data.Map.
obj.getX()which will throw an exception unless one checksobj.hasX()beforehand. This is frowned upon in Haskell, since it is easy to forget the check: in your code, if you usedfwithout checkingk == Nothingfirst, you would crash the program. Fortunately, pattern matching provides a better way to solve it: in acasewe are prodded to consider all the constructors, and act accordingly -- this is always safe.