How to create a function from a list of tuples?

I want to convert this list of tuples:

[(1,'a'),(2,'b') ... ] 

into a function that can be written as follows:

 g :: Int -> Char g 1 = 'a' g 2 = 'b' . . . 

Use Case:

 g 1 -- | 'a' 
+4
source share
1 answer

The signature of such a function will be [(a, b)] -> a -> b . This sounds like a normal operation, so allow a search on Hoogle to see if it exists. Oh, it's almost like that, and it's called lookup :

 lookup :: Eq a => a -> [(a, b)] -> Maybe b 

lookup key assocs searches for a key in the list of associations.

What we need to do is flip the first two arguments (use flip ) and cut Maybe with the result (compile with fromJust ). Result:

 g :: Int -> Char g = fromJust . flip lookup [(1,'a'),(2,'b'),(3,'c')] 
+13
source

Source: https://habr.com/ru/post/1482869/


All Articles