我使用代碼:Map.lookup - 類型聲明錯誤
test2 :: Int -> Map Int Int -> Int
test2 key cache
| Map.member key cache = Map.lookup key cache
| otherwise = 0
在這裏,我要檢查詮釋的地圖是否存在等,如果它存在查找的值。但我得到錯誤:
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
爲什麼?我檢查了地圖中存在的鑰匙。我該如何解決它?
更新
Thans你的答案,但我真正的代碼是一個有點複雜:
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
我已經更新了這樣的代碼:
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
但得到下一個錯誤:
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
您可以使用'Data.Maybe'中的'fromMaybe'來代替'maybe 0 id'來將表達式簡寫爲:'fromMaybe 0。 Map.lookup鍵$ cache'。 – shang 2012-02-24 09:33:57
我已更新我的問題。你可以看看嗎? – demas 2012-02-24 10:25:23
爲了在Map中使用數據類型作爲鍵,它必須是Ord類型類的實例(即它必須是可排序的)。要自動爲您的Coord數據類型派生Ord實例,只需將它添加到派生子句中:'data Coord = Coord Int Int派生(Show,Ord)' – 2012-02-24 10:31:05