1

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]
pre-kidney
  • 693
  • 3
  • 9

1 Answers1

5

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.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • 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. – pre-kidney Feb 02 '15 at 07:19
  • @pre-kidney You're welcome. We all have mental blocks from time to time; I think I have more than my share of them. – Mr.Wizard Feb 02 '15 at 07:20