Specifics of usage and internal work of *Set* functions

纵然是瞬间 提交于 2019-12-01 18:21:14

Taking the case of UpSet first, this is expected behavior. One can write:

 5[b] ^= 1

The assignment is made to b not the Integer 5.

Regarding Set and SetDelayed, while these have Hold attributes, they still internally evaluate expressions. This allows things such as:

p = n : (_List | _Integer | All);

f[p] := g[n]

Test:

f[25]
f[{0.1, 0.2, 0.3}]
f[All]
   g[25]
   g[{0.1, 0.2, 0.3}]
   g[All]

One can see that heads area also evaluated. This is useful at least for UpSet:

p2 = head : (ff | gg);
p2[x] ^:= Print["Echo ", head];

ff[x]
gg[x]

Echo ff

Echo gg

It is easy to see that it happens also with Set, but less clear to me how this would be useful:

j = k;
j[5] = 3;
DownValues[k]

(* Out=  {HoldPattern[k[5]] :> 3}  *)

My analysis of the first part of your question was wrong. I cannot at the moment see why a[b] = 2 is accepted and a[1] = 2 is not. Perhaps at some stage of assignment the second one appears as 5[1] = 2 and a pattern check sets off an error because there are no Symbols on the LHS.

The behavour you show appears to be a bug in 7.0.1 (and possibly earlier) that was fixed in Mathematica 8. In Mathematica 8, both of your original a[b] = 2 and a[1] = 2 examples give the Set::write ... is protected error.

The problem appears to stem from the JLink-related down-value of Set that you identified. That rule implements the JLink syntax used to assign a value to the field of a Java object, e.g. object@field = value.

Set in Mathematica 8 does not have that definition. We can forcibly re-add a similar definition, thus:

Unprotect[Set]
HoldPattern[sym_Symbol[arg_Symbol]=val_] :=
  With[{obj=sym}
  , setField[obj[arg], val] /; Head[obj] === Symbol && StringMatchQ[Context[obj],"Something`*"]
  ]

After installing this definition in Mathematica 8, it now exhibits the same inconsistent behaviour as in Mathematica 7.

I presume that JLink object field assignment is now accomplished through some other means. The problematic rule looks like it potentially adds costly Head and StringMatchQ tests to every evaluation of the form a[b] = .... Good riddance?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!