I want to convert this list of tuples:
[(1,'a'),(2,'b') ... ]
into a function that could be written as this:
g :: Int -> Char
g 1 = 'a'
g 2 = 'b'
.
.
.
Use case:
g 1 -- | 'a'
The signature of such a function would be [(a, b)] -> a -> b
. It sounds like a common operation, so let's search on Hoogle to see if it already exists. Oh, it almost does, and it's called lookup
:
lookup :: Eq a => a -> [(a, b)] -> Maybe b
lookup key assocs
looks up a key in an association list.
What we need to do is flip the first two arguments (use flip
) and strip the Maybe
off the result (compose with fromJust
). Result:
g :: Int -> Char
g = fromJust . flip lookup [(1,'a'),(2,'b'),(3,'c')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With