# How to limit the argument to binary type in mathematica function

How do I write a function that only takes binary input?

• Modern computers are all binary machines. Want to be more specific about your requirements? Nov 5, 2013 at 15:24
• Nov 5, 2013 at 16:04
• @belisarius I'd consider that more of a postmodern computer... Nov 5, 2013 at 16:30
• How will this binary input be passed to the function? The integers 1 and 0 or the booleans True and False? Nov 5, 2013 at 16:53

Assuming Sjoerd's interpretation, I would use:

f[x : 0 | 1] := 1 - x

• Yay! That one deserves some explanation! Nov 5, 2013 at 18:43
• I like this one best. Nov 5, 2013 at 20:06

Your question is not very clear, but I guess something like this meets your requirements:

notFun[x_?(#==0||#==1&)]:= 1-x


or

notFun[x_]:=1-x /; x==0||x==1


Following Sjoerd´s interpretation:

f[x_ /; MemberQ[{0, 1}, x]] := x


Another way to skin this cat is to define your own test to verify what you consider binary. For example, if you mean a single binary digit you would use

BinaryQ[x_] := If[x == 1 || x == 0, True, False]


Or some other analogous expression. This form can lead to a cleaner implementation when you have more than one variable

logicFun[x1_?BinaryQ, x2_?BinaryQ] := x1 x2


You can also use patterns to define more general combinations of binary values in the arguments of your functions. Moreover, by changing the implementation of BinaryQ you can accomodate more elaborate definitions of what is binary. For example, you want True-False as in logic prepositions? Then you will be better off with

BinaryQ[x_] := If[x == True || x == False, True, False]


(Obviously, in this case you should change the implementation of logicFun accordingly). Is your definition of binary is a list of 0s and 1s? Then

BinaryQ[x_] := Switch[Sort[Union[x]],
{0, 1}, True,
{0}, True,
{1}, True,
True, False]


will do the trick:

logicFun[{1, 0, 1, 1}, {0, 1, 0, 1}]

{0,0,0,1}


(the definition of logicFun here is just for illustrative purposes). I guess nothing prevents you from writing a more complex BinaryQ function that could combine single digit binary cases with lists of binary digits or even wrapper that characterize binary input.

• Probably BinaryQ[x_] := If[x == 1 || x == 0, True, False, False ] is clearer Nov 7, 2013 at 18:58