3

I came across a bit of code that uses the syntax /: and I don't know what it does. I can't find its documentation, or maybe I'm just not looking properly. The code snippet is something like:

F/:F[A___,b_?NumberQ B_, C___] := b*F[A,B,C]

(i.e. part of the definition of multi-linearity). How does this behave differently than the following?:

G[A___,b_?NumberQ B_, C___] := b*G[A,B,C]

Thanks!

kglr
  • 394,356
  • 18
  • 477
  • 896
Ian Hincks
  • 1,859
  • 13
  • 21

1 Answers1

17

/: is the short-hand notation for TagSetDelayed, which is creating UpValues. It's useful for over-loading how a particular function behaves with a specific head. For example:

In[1]:= h /: Plus[x : h[arg1_, arg2_], y : h[arg3_, arg4_]] := Plus[arg1, arg2, arg3, arg4]

In[2]:= h[1, 2] + h[3, 4]
Out[2]= 10

The benefit being you don't have to Unprotect[Plus] to set the definition, and if you Remove[h] this definition will be wiped out as well.

nikko
  • 736
  • 6
  • 7
  • 1
    Thanks @nikko. What purpose do the x and y serve in this example? It seems to work without them. – Ian Hincks May 03 '12 at 18:35
  • @IanHincks in this example, they don't serve any purpose, but they could be used to refer to the entire object matched by h[arg1_, arg2_]. So, if you had need of the entire pattern, you could use it. – rcollyer May 03 '12 at 18:36
  • 4
    In this case, it is TagSetDelayed rather than TagSet. The syntax in fact has to parts: s/:lhs:=rhs or s/:lhs=rhs, so /: alone is not enough to tell which one it is. Also, a correct statement is that TagSetDelayed (or TagSet) can create UpValues (but it can also create OwnValues, DownValues and SubValues, in which case, the tag part is redundant). – Leonid Shifrin May 03 '12 at 18:43
  • yes, sorry the x: and y: are superfluous here. – nikko May 03 '12 at 18:45