Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

wolfram mathematica - Preventing "Plus" from rearranging things

The following code creates a diagram of a certain calculation. My problem is that even though the terms in denominator are in a nice order, after applying Plus on it, they get rearranged arbitrarily. Any suggestions how to force the original order to be kept?


(source: yaroslavvb.com)

r[i_] := Floor[(i - 1)/n] + 1;
c[i_] := Mod[i, n, 1];
adj[a_, b_] := Abs[r[a] - r[b]] + Abs[c[a] - c[b]] == 1;
indsetQ[s_] := Not[Or @@ (adj @@@ Subsets[s, {2}])];
indsets[k_] := Select[Subsets[Range[n^2], {k}], indsetQ];
twoColorGraph[g_, seen_, lbl_] := Module[{radius = .22},
   vcoords = # -> {c[#], n - r[#]} & /@ Range[n^2];
   fv = Function[{p, v}, {EdgeForm[Thick], 
      If[MemberQ[seen, v], Pink, White], Disk[p, radius]}];
   GraphPlot[g, VertexLabeling -> True, VertexRenderingFunction -> fv,
     PlotLabel -> Style[lbl, 20], LabelStyle -> Directive[Bold], 
    VertexCoordinateRules -> vcoords, ImageSize -> 80]
   ];
n = 2;
g = Array[Boole[adj[#1, #2]] &, {n^2, n^2}];
weight[set_] := Times @@ (Subscript[[Lambda], c[#], r[#]] & /@ set);
denominator = 
  twoColorGraph[g, #, weight[#]] & /@ 
   Join @@ (indsets[#] & /@ Range[2]);
numerator = twoColorGraph[g, {1}, weight[{1}]];
Style[numerator/(Plus @@ denominator), FontSize -> 30]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The trick to formatting something like myPlus to look like Plus on output is to use Format. Here's a simple example to get you started:

Format[myPlus[expr__]] := Row[Riffle[{expr}, "+"]]

Then, what you will see visually in the notebook is:

In[7]:= x = myPlus[3, 2, 1]
Out[7]= 3+2+1

... but x will still have head myPlus.

Here is a tutorial from the documentation that goes into more details about formatting output, operator precedence, etc.

Hope that helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...