1
$\begingroup$

Mathematica has a large number of built-in symbols, and I am unsure when there is a shorthand for the operation I am trying to perform.

Question 1:

Is there a shorthand for the function Join[#,#] &? Here I only need the operation to apply to lists.

Question 2:

Is there a shorthand for a function which swaps out one operation with another:

f[bool_, a_, b_] := If[bool, a + b, a - b]
$\endgroup$
  • 1
    $\begingroup$ I highly recommend waiting 24 hours before Accepting an answer, to give people all around the world time to respond. You never know what answers you might get. :-) $\endgroup$ – Mr.Wizard Feb 2 '15 at 7:19
  • $\begingroup$ Point taken. Unaccepted for now. $\endgroup$ – pre-kidney Feb 2 '15 at 7:19
  • $\begingroup$ I guess no one else feels like answering. $\endgroup$ – Mr.Wizard Feb 5 '15 at 8:16
5
$\begingroup$

I can't think of a way to improve Join[#, #] &. Merely as a game you could use:

{##, ##} & @@ {1, 2, 3}
{1, 2, 3, 1, 2, 3}

However this is inadvisable because it will unpack packed arrays and it loses the original Head.

For the second case if the arguments are long, rather than just a and b, it can be shorter to use:

If[bool, Plus, Subtract][a, b]

Somewhat related: List manipulation to build a functional expression.

You could also use two separate definitions:

f[True,  a_, b_] := a + b
f[False, a_, b_] := a - b

Neither is an improvement in your example but each has its place I believe.

$\endgroup$
  • $\begingroup$ Thanks, the If[bool, Plus, Subtract] was what I was looking for. I am embarrassed to admit that I had tried If[bool, +, -] before giving up. $\endgroup$ – pre-kidney Feb 2 '15 at 7:19
  • $\begingroup$ @pre-kidney You're welcome. We all have mental blocks from time to time; I think I have more than my share of them. $\endgroup$ – Mr.Wizard Feb 2 '15 at 7:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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