Reputation: 5829
I'd appreciate help understanding the origin of the extra map
in Map.lookup lockerNumber map
, from the following example taken from chapter 8 of Learn You a Haskell for Great Good
lockerLookup :: Int -> LockerMap -> Either String Code
lockerLookup lockerNumber map =
case Map.lookup lockerNumber map of
Nothing -> Left $ "Locker number " ++ show lockerNumber ++ " doesn't exist!"
Just (state, code) -> if state /= Taken
then Right code
else Left $ "Locker " ++ show lockerNumber ++ " is already taken!"
Upvotes: 1
Views: 3985
Reputation: 116174
Briefly put, here map
is a variable of type LockerMap
, which I assume to be of the form Data.Map.Map someKeyType someValueType
. It represents a (finite) association between elements of someKeyType
and those of someValueType
. This is sometimes also called a (finite) mapping, (finite) function, dictionary, hash, etc.
The expression Map.lookup x map
simply accesses the map
with key value x
. The result is Nothing
is there is no association for x
in the map
, and Just v
if x
is associated with value v
.
Upvotes: 1
Reputation: 105915
There's no "additional" map
(as in map :: (a -> b) -> [a] -> [b]
) in that code. It gets more clear if we rename map
to m
:
lockerLookup :: Int -> LockerMap -> Either String Code
lockerLookup lockerNumber m =
case Map.lookup lockerNumber m of
-- snip
Now you just need to remember that Map.lookup
has type Ord k => k -> Map k a -> Maybe a
and therefore you need to supply a Map
. Luckily, the second argument (m
) is a LockerMap
, which is the same as Map Int (LockerState, Code)
.
Upvotes: 2