xiaolingxiao
xiaolingxiao

Reputation: 4885

How do I build a function out of list of tuples?

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'

Upvotes: 4

Views: 125

Answers (1)

icktoofay
icktoofay

Reputation: 128991

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')]

Upvotes: 13

Related Questions