Sign up ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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

share|improve this question
Modern computers are all binary machines. Want to be more specific about your requirements? – Oleksandr R. Nov 5 '13 at 15:24
@belisarius I'd consider that more of a postmodern computer... – Oleksandr R. Nov 5 '13 at 16:30
How will this binary input be passed to the function? The integers 1 and 0 or the booleans True and False? – Sjoerd C. de Vries Nov 5 '13 at 16:53

4 Answers 4

Assuming Sjoerd's interpretation, I would use:

f[x : 0 | 1] := 1 - x
share|improve this answer
Yay! That one deserves some explanation! – Yves Klett Nov 5 '13 at 18:43
I like this one best. – Sjoerd C. de Vries Nov 5 '13 at 20:06

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

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


notFun[x_]:=1-x /; x==0||x==1
share|improve this answer

Following Sjoerd´s interpretation:

f[x_ /; MemberQ[{0, 1}, x]] := x
share|improve this answer

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}]

(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.

share|improve this answer
Probably BinaryQ[x_] := If[x == 1 || x == 0, True, False, False ] is clearer – belisarius has settled Nov 7 '13 at 18:58

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.