Haskell – How to get a List of Tuples with certain combinations

Haskell – How to get a List of Tuples with certain combinations

Problem Description:

Is there a way to create a list of tuples with a certain pattern?

I have following inputs for example:

a = 100

b = [10,20,30]

c = ['a','b','c','d','e','f','g']

And I would like to have following Output:

[(100,10,'a'),(100,10,'b'),(100,10,'c'),(100,10,'d'),(100,10,'e'),(100,10,'f'),(100,10,'g'),
 (100,20,'a'),(100,20,'b'),(100,20,'c'),(100,20,'d'),(100,20,'e'),(100,20,'f'),(100,20,'g'),
 (100,30,'a'),(100,30,'b'),(100,30,'c'),(100,30,'d'),(100,30,'e'),(100,30,'f'),(100,30,'g')]

I think if I only had a and b for example I would do:

makeTuple :: Int -> [Int] -> [(Int,Int)]
makeTuple _ [] = []
makeTuple i (x:xs) = [(i,x)] ++ makeTuple i xs

This would give me:

[(100,10),(100,20),(100,30)]

Im not sure how I could make it work with 3 Inputs .

Solution – 1

You can use applicative composition:

ghci> (,,) <$> [a] <*> b <*> c
[(100,10,'a'),(100,10,'b'),(100,10,'c'),(100,10,'d'),(100,10,'e'),(100,10,'f'),(100,10,'g'),
 (100,20,'a'),(100,20,'b'),(100,20,'c'),(100,20,'d'),(100,20,'e'),(100,20,'f'),(100,20,'g'),
 (100,30,'a'),(100,30,'b'),(100,30,'c'),(100,30,'d'),(100,30,'e'),(100,30,'f'),(100,30,'g')]

Here’s an explanation of how that works, with examples in F#, Haskell, and C#: An applicative password list.

Solution – 2

List comprehensions can do it nicely:

[(a, x, y) | x <- b, y <- c]
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject