8

Mathematica allows this syntax, but I cannot find any documentation (or books) that discuss the various uses/advantages of it

g[1] := Plus;
g[2] := Times;
g[1][3, 5]
(* 8 *)

g[2][3, 5]
(* 15 *)

What keywords can I use to find this in the documentation?

rm -rf
  • 88,781
  • 21
  • 293
  • 472
W1TM
  • 81
  • 2

2 Answers2

12

Your g[1] and g[2] are simply acting as Head:

g[1] := Plus;

So there is no mystery in this syntax:

 {g[1][a, b], Plus[a, b]}

{a + b, a + b}

 Head /@ {g[1][a, b], Plus[a, b]}

{Plus, Plus}

So you need to read:

But maybe there is a bit more to it than meets the eye. You actually almost wondered into programming concept called Currying which according to Wikipedia "is the technique of transforming a function that takes multiple arguments in such a way that it can be called as a chain of functions each with a single argument (partial application)."

So you can do things like:

f[x_][y_] := Sin[x y]

f[x] /@ Range[5]

{Sin[x], Sin[2 x], Sin[3 x], Sin[4 x], Sin[5 x]}

Documentation mentions it here. For deeper insight see discussion in @SalMangano "Mathematica Cookbook".

BTW, @acl nice addition (to see how Mathematica thinks) can be visualized as

TreeForm[Trace[g[1][a, b]]]

enter image description here

So the thinking goes from top to bottom and from left to right.

Vitaliy Kaurov
  • 73,078
  • 9
  • 204
  • 355
6

Just to add to Vitaliy's answer: You can see what happens with

g[1] := Plus;
FullForm /@ (g[1][3, 4] // Trace)

Mathematica graphics

So, on evaluating g[1][3,4], Mathematica looks up g[1] and sees it evaluates to Plus; it's then left with Plus[3,4] which evaluates to 7.

acl
  • 19,834
  • 3
  • 66
  • 91
  • +1 Cool idea to use Trace. I referred to your answer too ;-) – Vitaliy Kaurov Aug 22 '12 at 22:41
  • @VitaliyKaurov does that mean the entire fabric of reality is going to rip apart? Or, just stackexchange? – rcollyer Aug 22 '12 at 22:52
  • @rcollyer This just means that you need to answer too and do a three way cross-referencing – rm -rf Aug 22 '12 at 23:00
  • 1
    @R.M there's a French term for that, but I don't think it is appropriate for polite company. – rcollyer Aug 23 '12 at 00:09
  • @rcollyer it just means household of three so I don't see the problem :) – acl Aug 23 '12 at 00:12
  • @rcollyer I was thinking of a Mexican standoff, but a ménage à trois is equally appropriate, I guess – rm -rf Aug 23 '12 at 00:13
  • @R.M make love not war, etc – acl Aug 23 '12 at 00:35
  • @acl an older professor of mine has been giving talks on ménage à trois in quantum mechanics, and yes he uses that exact term and enjoys the laughter he gets from it. I am very sorry I didn't take more classes with him as he was a brilliant teacher when I had him. – rcollyer Aug 23 '12 at 02:08