import Prelude hiding (lookup) import Data.Map employeeDept = fromList([("John","Sales"), ("Bob","IT")]) deptCountry = fromList([("IT","USA"), ("Sales","France")]) countryCurrency = fromList([("USA", "Dollar"), ("France", "Euro")]) employeeCurrency :: String -> Maybe String employeeCurrency name = do dept <- lookup name employeeDept country <- lookup dept deptCountry lookup country countryCurrency main = do putStrLn $ "John's currency: " ++ (show (employeeCurrency "John")) putStrLn $ "Pete's currency: " ++ (show (employeeCurrency "Pete"))The output of this program:
John's currency: Just "Euro" Pete's currency: Nothing
0 <= i < length xs ==> lookup i xs == Just (toList xs !! i)
i < 0 || i >= length xs ==> lookup i xs = NothingUnlike index, this can be used to retrieve an element without forcing it. For example, to insert the fifth element of a sequence xs into a Map m at key k, you could use
case lookup 5 xs of Nothing -> m Just x -> insert k x m
>>> let v4 = ["133.4.0.0/16","133.5.0.0/16","133.5.16.0/24","133.5.23.0/24"] :: [AddrRange IPv4] >>> let rt = fromList $ zip v4 v4 >>> lookup "127.0.0.1" rt Nothing >>> lookup "133.3.0.1" rt Nothing >>> lookup "133.4.0.0" rt Just 133.4.0.0/16 >>> lookup "133.4.0.1" rt Just 133.4.0.0/16 >>> lookup "133.5.16.0" rt Just 133.5.16.0/24 >>> lookup "133.5.16.1" rt Just 133.5.16.0/24
>>> lookup 2 [(1, "first"), (2, "second"), (3, "third")] Just "second"
import Prelude hiding (lookup) import Data.Map employeeDept = fromList([("John","Sales"), ("Bob","IT")]) deptCountry = fromList([("IT","USA"), ("Sales","France")]) countryCurrency = fromList([("USA", "Dollar"), ("France", "Euro")]) employeeCurrency :: String -> Maybe String employeeCurrency name = do dept <- lookup name employeeDept country <- lookup dept deptCountry lookup country countryCurrency main = do putStrLn $ "John's currency: " ++ (show (employeeCurrency "John")) putStrLn $ "Pete's currency: " ++ (show (employeeCurrency "Pete"))The output of this program:
John's currency: Just "Euro" Pete's currency: Nothing