I am working with code:
test2 :: Int -> Map Int Int -> Int
test2 key cache
| Map.member key cache = Map.lookup key cache
| otherwise = 0
Here I want to check the existance of Int in the Map and lookup the value if it exists. But I get error:
Couldn't match expected type `Int' with actual type `Maybe a0'
In the return type of a call of `Map.lookup'
In the expression: Map.lookup key cache
In an equation for `test2':
test2 key cache
| member key cache = Map.lookup key cache
| otherwise = 0
Why? I have checked existance of key in the Map. How can I fix it?
Updated
Thans for your answers, but my real code is a little bit complex:
data Coord = Coord Int Int deriving (Show)
calculation :: Coord -> Map Coord Integer -> Integer
calculation coord cache
| corner coord = 0
| side coord = 1
| Map.member coord cache = Map.lookup key cache
| otherwise = (calculation (move_right coord) cache) + (calculation (move_down coord) cache)
where (Coord x y) = coord
I have updated the code like this:
calculation :: Coord -> Map Coord Integer -> Integer
calculation coord cache
| corner coord = 0
| side coord = 1
| Map.member coord cache = Map.findWithDefault (calculation (move_right coord) cache) + (calculation (move_down coord) cache) coord cache
where (Coord x y) = coord
But get the next error:
problem_15.hs:21:14:
No instance for (Ord Coord)
arising from a use of `member'
Possible fix: add an instance declaration for (Ord Coord)
In the expression: member coord cache
In a stmt of a pattern guard for
an equation for `calculation':
member coord cache
In an equation for `calculation':
calculation coord cache
| corner coord = 0
| side coord = 1
| member coord cache
= findWithDefault (calculation (move_right coord) cache)
+ (calculation (move_down coord) cache) coord cache
where
(Coord x y) = coord
problem_15.hs:21:39:
Couldn't match expected type `Integer'
with actual type `k0 -> Map k0 a0 -> a0'
In the return type of a call of `findWithDefault'
In the first argument of `(+)', namely
`findWithDefault (calculation (move_right coord) cache)'
In the expression:
findWithDefault (calculation (move_right coord) cache)
+ (calculation (move_down coord) cache) coord cache