# Map a Switch function to 2 or more lists

I have this program, which turns 1 and 0s to True or False.

randombool = RandomVariate[BernoulliDistribution[0.5], 10]
{1, 0, 1, 0, 0, 1, 1, 0, 0, 1}

TrueOrFalse[x_] := Switch[x, 1, True, 0, False]

Convert = Map[TrueOrFalse, randombool]
{True, False, True, False, False, True, True, False, False, True}

But when I do with 2 lists it stops working, for example:

randombool = RandomVariate[BernoulliDistribution[0.5], {2, 10}]
{{1, 0, 1, 1, 1, 1, 0, 1, 1, 1}, {1, 0, 0, 1, 0, 0, 1, 0, 0, 1}}

TrueOrFalse[x_] := Switch[x, 1, True, 0, False]

Convert = Map[TrueOrFalse, randombool]
{Switch[{1, 0, 1, 1, 1, 1, 0, 1, 1, 1},
1, True,
0, False], Switch[{1, 0, 0, 1, 0, 0, 1, 0, 0, 1},
1, True,
0, False]}

What am I doing wrong here? Thanks.

• Use Map[TrueOrFalse, randombool, {2}], i.e. map at 2nd level.
– Alx
Commented Apr 6, 2020 at 15:00
• You can also use ReplaceAll[{0 -> False, 1 -> True}]. Commented Apr 6, 2020 at 15:01
• Or SetAttribute[TrueOrFalse, Listable] and then TrueOrFalse[randombool].
– Alx
Commented Apr 6, 2020 at 15:05
• Or Map[(1 == #) &, {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1}, {1, 0, 0, 1, 0, 0, 1, 0, 0, 1}}, {-1}] Commented Apr 6, 2020 at 15:19
• Thank you Alx, it worked.
– joao
Commented Apr 6, 2020 at 17:11

Use OddQ instead of TrueOrFalse. It's the fast and easy inverse to Boole.

In[25]:= OddQ[{{1, 0, 1, 1, 1, 1, 0, 1, 1, 1}, {1, 0, 0, 1, 0, 0, 1,
0, 0, 1}}]

Out[25]= {{True, False, True, True, True, True, False, True, True,
True}, {True, False, False, True, False, False, True, False, False,
True}}

Some quick timings:

In[1]:= ints = RandomInteger[1, 10^6];

In[6]:= RepeatedTiming[v1 = OddQ[ints];]
Out[6]= {0.015, Null}

In[7]:= RepeatedTiming[v2 = ReplaceAll[ints, {0 -> False, 1 -> True}];]
Out[7]= {0.160, Null}

In[8]:= TrueOrFalse[x_] := Switch[x, 1, True, 0, False];

In[9]:= RepeatedTiming[v3 = TrueOrFalse /@ ints;]
Out[9]= {0.533, Null}

In[10]:= RepeatedTiming[v4 = Map[(1 == #) &, ints, {-1}];]
Out[10]= {0.319, Null}

In[11]:= v1 == v2 == v3 == v4
Out[11]= True