Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zipping same value over a list of tuples Haskell

I would like to transform the following tuple list

a = [(1,()),(2,())]

into a nested tuple list by the same value

b = [(False,(1,())),(False,(2,()))]

Using the zip function in this format

zip [False] a

only gives me

[(False,(1,()))]

Any suggestions or advice would be much appreciated.

like image 441
dfj328 Avatar asked May 26 '15 12:05

dfj328


People also ask

Can you zip a tuple and a list?

zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.

Does zip return a tuple?

The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.

How does zip work in Haskell?

In Haskell, we have a zip function that is used to merge the two arrays or lists or any data structure. But to merge them directly there is some condition by which they get merged. All the values which get merged with the same position element from the other array or input passed.

Are tuples immutable in Haskell?

A tuple is a sequence of values. The values can be of any type, and they are indexed by an integer, so tuples are not like lists. Tuples are immutable which means you cannot add more elements to the tuple as the program runs.


2 Answers

If you zip two lists of different lengths, you get the length of the shortest list.

You can fix this by zipping against an infinitely long list:

zip (repeat False) a

should do the trick.

like image 155
MathematicalOrchid Avatar answered Oct 12 '22 22:10

MathematicalOrchid


Alternatively, instead of using zip you can use map:

map (\x -> (False, x)) a

This would more appropriately express your intent (in my opinion) since you want to do the same thing to every element of the list. If you want to do different things to each element, then zip or zipWith may be more appropriate.

If you wanted to avoid the lambda, you can write it pointfree using &&& from Control.Arrow:

map (const False &&& id) a

which basically says "apply the functions const False and id to the input, then construct a tuple of both of their outputs". There is the TupleSections extension which would allow you to write this as

map (False,) a

(tip provided by @thoferon), but I personally find this less clear, since you have to know that the extension is enabled and notice the , after False. You could write it as

map ((,) False) a

without the extension since (,) acts as a function of type a -> b -> (a, b), and while a bit more verbose it doesn't require enabling a language extension.

like image 29
bheklilr Avatar answered Oct 12 '22 20:10

bheklilr