Reputation: 251
Allow me to explain if my question is not clear. Let's say I have tuples :: [(a, Int)]
. I have created this using zip
. Now, I want to find a corresponding Int
value for my a
element. I'm trying to figure out how I do this.
f :: [(a, Int)] -> a -> Int
Above is the type of the function I need.
Or how it needs to be used in ghci:
let tuples = zip ['a','b','c'] [1..]
f tuples 'a'
returns: 1
Upvotes: 1
Views: 1707
Reputation: 2986
As the other answer says, you may wish to use lookup :: Eq a => a -> [(a, b)] -> Maybe b
(source-code). You may implement it in point-free style as lookup key = fmap snd . safeHead . filter ((== key) . fst)
.
To drop the safety when the key is not present on the list, just swap safeHead :: [a] -> Maybe a
with head :: [a] -> a
, and to change the parameter order simply flip :: (a -> b -> c) -> b -> a -> c
.
Therefore, to find your initial specification we could have:
myLookup :: Eq a => [(a, b)] -> a -> b
myLookup = flip myLookup'
where myLookup' key = snd . head . filter ((== key) . fst)
Upvotes: 1
Reputation: 3201
There's a
lookup :: Eq a => a -> [(a, b)] -> Maybe b
in the Prelude. It returns a Maybe
because the item you're looking up might not be in the list.
But you didn't ask for safety and the argument order is different from what you asked, so it doesn't answer your question exactly.
Upvotes: 3