Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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'
like image 746
xiaolingxiao Avatar asked Dec 11 '22 14:12

xiaolingxiao


1 Answers

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')]
like image 180
icktoofay Avatar answered Dec 14 '22 03:12

icktoofay