2
$\begingroup$

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

$\endgroup$
4
  • 2
    $\begingroup$ Modern computers are all binary machines. Want to be more specific about your requirements? $\endgroup$ Nov 5, 2013 at 15:24
  • 2
    $\begingroup$ @OleksandrR. lrss.fri.uni-lj.si/people/ilbajec/papers/pecar_isvlsi09.pdf $\endgroup$ Nov 5, 2013 at 16:04
  • 1
    $\begingroup$ @belisarius I'd consider that more of a postmodern computer... $\endgroup$ Nov 5, 2013 at 16:30
  • 1
    $\begingroup$ How will this binary input be passed to the function? The integers 1 and 0 or the booleans True and False? $\endgroup$ Nov 5, 2013 at 16:53

4 Answers 4

11
$\begingroup$

Assuming Sjoerd's interpretation, I would use:

f[x : 0 | 1] := 1 - x
$\endgroup$
2
  • $\begingroup$ Yay! That one deserves some explanation! $\endgroup$
    – Yves Klett
    Nov 5, 2013 at 18:43
  • 1
    $\begingroup$ I like this one best. $\endgroup$ Nov 5, 2013 at 20:06
6
$\begingroup$

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
$\endgroup$
4
$\begingroup$

Following Sjoerd´s interpretation:

f[x_ /; MemberQ[{0, 1}, x]] := x
$\endgroup$
3
$\begingroup$

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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