How do I write a function that only takes binary input?
-
2$\begingroup$ Modern computers are all binary machines. Want to be more specific about your requirements? $\endgroup$– Oleksandr R.Nov 5, 2013 at 15:24
-
2$\begingroup$ @OleksandrR. lrss.fri.uni-lj.si/people/ilbajec/papers/pecar_isvlsi09.pdf $\endgroup$– Dr. belisariusNov 5, 2013 at 16:04
-
1$\begingroup$ @belisarius I'd consider that more of a postmodern computer... $\endgroup$– Oleksandr R.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$– Sjoerd C. de VriesNov 5, 2013 at 16:53
4 Answers
Assuming Sjoerd's interpretation, I would use:
f[x : 0 | 1] := 1 - x
-
$\begingroup$ Yay! That one deserves some explanation! $\endgroup$ Nov 5, 2013 at 18:43
-
1
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.
-
$\begingroup$ Probably
BinaryQ[x_] := If[x == 1 || x == 0, True, False, False ]
is clearer $\endgroup$ Nov 7, 2013 at 18:58