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.
zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.
The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With