1

(Edited to provide an example)

Recently I have found myself writing silly functions like the following, which is just a new arity of Subtract in which the arguments are inside a list.

subtract[{a_, b_}] := Subtract[a, b]

If I were adding that variant to one of my own functions, I would use the same name, and would feel more comfortable about it.

I feel sure I should not need to do this for system functions, yet these variants are very convenient when I am working with lists.

There is probably some elementary principle of Mathematica coding that I have failed to absorb. What could it be?

Example:

pairsOfPositions = {{{a, b, c}, {d, e, f}}, {{g, h, i}, {j, k, l}}, {{m, n, o}, {p, q, r}}}; differences = Map[subtract, pairsOfPositions, {1}];

where the desired result for differences is { {a - d, b - e, c - f}, {g - j, h - k, i - l}, {m - p, n - q, o - r} }

Karsten7
  • 27,448
  • 5
  • 73
  • 134
Ralph Dratman
  • 1,250
  • 12
  • 20
  • 5
  • 1
    Proposed duplicates: (10833), (46238) – Mr.Wizard Aug 03 '15 at 02:10
  • My question is supposed to be about items embedded in a list. Maybe Apply would help, but I don't yet understand how. – Ralph Dratman Aug 03 '15 at 02:28
  • @RalphDratman does not Subtract @@@ pairsOfPositions give the output you want? If so you just need to take the time to understand Apply. If this is not the result you want or you chose a narrow example please edit the question to explain. – Mr.Wizard Aug 03 '15 at 02:30
  • Yes, thank you Sir Wizard, Subtract @@@ pairsOfPositions does work. Thank you so much. I will as you suggested look more deeply into Apply. – Ralph Dratman Aug 03 '15 at 02:55
  • I feel dumb about asking such a simple question and getting such an apparently easy answer. Believe it or not, I use Mathematica frequently and effectively, but, as with most computer languages (for me), there are areas where my mind refuses to latch on. For me this happens with the inner parts of lists. Maybe there is a LIS gene which I lack. – Ralph Dratman Aug 03 '15 at 03:06
  • @Ralph Not only do we all have those moments, but lots of things in Mathematica, and the rest of life really, look simple after you understand. :-) – Mr.Wizard Aug 03 '15 at 03:09
  • @RalphDratman Apply[Subtract] is more or less equivalent to your subtract function. This syntax is available since v10. Try Apply[Subtract][{a,b}]. – Szabolcs Aug 03 '15 at 11:42

1 Answers1

2
Subtract @@ {a, b}
(* a - b *)
John Doty
  • 13,712
  • 1
  • 22
  • 42