Skip to main content

evaluation - How to properly inject iterators into table?



Goofing off on a prior question, I was fiddling with other methods, which led me to the need to inject a constructed set of iterators into a table construct.


Now,


ClearAll[a, b, z, z2]


z = {{a, {1, 2, 3}}, {b, {1, 2, 3}}}
Table[{a, b}, Evaluate[Sequence @@ z]]

(* {{{1, 1}, {1, 2}, {1, 3}}, {{2, 1}, {2, 2}, {2, 3}}, {{3, 1}, {3, 2}, {3, 3}}} *)

Precisely what I'd expect. What I've been trying to inject is of the form:


z2 = {{a, {1, 2, 3}}, {b, Complement[{1, 2, 3}, {a}]},{c, Complement[{1, 2, 3}, {a,b}]}}

It seems whatever combinations of Hold, Unevaluated, etc. I wrap this in (so the Complement doesn't get immediately evaluated), it doesn't make it through injection: I get results as if the complement is not there. I know it is, since changing the second argument to Complement to something invalid throws an error in the Table evaluation and shows it in the error information.



I'm guessing the iterator variables I'm using in the second arguments to the Complements are just getting eval'd as the symbol name, so the Complement is the complete first argument since there's no overlap.


I'm stumped. Any suggestions?


Update: Playing around with Kuba's interesting answer, and getting there, but still some issues. Here's a snippet of some pieces to show what's happening:


t = 4
c = {0, 0, 1, 2}

cr = Reverse@Range[c, t - 1];
vars = Unique[] & /@ Range@t
varsx = Map[vars[[;; # - 1]] &, Range@t];


m = Sequence @@
MapThread[{#1, HoldForm@Complement[#2, #3]} &, {vars, cr, varsx}];

res = Unevaluated[ReleaseHold@Table[vars, m]] /. OwnValues[m];

I create the ranges for each iterator in cr, the variable each corresponds to in vars, and the list of what's to be complemented in varsx.


The map creates the list of {iterator var, Complement[interator range, prior iterators]}... In this example, I've used HoldForm to prevent immediate evaluation of the Complement, but as I said, I've tried various incantations.


In any case, the correct desired results show up in res using Kuba's technique, despite MMA complaining about malformed iterators.


Update: Thanks to all for the enlightening answers. All were useful an interesting, and picking an accept was troublesome: I picked LS's becuase his answer is the "proper" way to do such things, but that does not reduce the value of all the other answers to me.


I'd advise readers to look at all of them...




Answer



General


I think that one can achieve the goal much easier if we reformulate the request. A variable is IMO not a proper object to store an iterator in the form of expression. What you really need is an environment, which would use certain iterator in code.


Simple lexical / dynamic environment


Here is how it may look:


ClearAll[withIterator];
SetAttributes[withIterator, HoldAll];
withIterator[{var_Symbol, iter__}] :=
Function[
code,

Unevaluated[code] /. var :> Sequence@iter,
HoldAll
];

This is a lexical scoping construct, which binds the variable var lexically to the iterator(s) you may want to use. Now, for your particilar iterator, we construct a custom environment and store it in a variable:


iterEnv = 
withIterator[{
iter,
{a, {1, 2, 3}}, {b, Complement[{1, 2, 3}, {a}]}, {c, Complement[{1, 2, 3}, {a, b}]}}
];


You can now use this with any code, just using the iter variable there:


iterEnv@Table[{a, b}, iter]

(* {{{{1, 2}}, {{1, 3}}}, {{{2, 1}}, {{2, 3}}}, {{{3, 1}}, {{3, 2}}}} *)

So, the resulting environment is half-lexical and half-dynamic. You do store it in a variable, but what you store is a full environment (a function, closure), rather than just an expression for an iterator.


Another version of a lexical environment


The above version has a flaw that the lexical binding for variable iter is broken into two different pieces of code - the environment proper and the call. For better readability, and robustness, it is better to have a fully lexical environment, where the variable is bound to a value at the same piece of code, so the binding is transparent.


Here is a way to do this. First, we define a generator for environments:



iterEnvironmentGenerator = 
Function[Null, Function[var, withIterator[{var, ##}], HoldAll], HoldAll]

Now, the fully lexical environment:


ClearAll[withIteratorLex];
SetAttributes[withIteratorLex, HoldRest];
withIteratorLex[env_Function, {var_Symbol, code_}] := env[var][code];

Here is how it can be used. First, you create an environment, using a generator:


env = 

iterEnvironmentGenerator[
{a, {1, 2, 3}},
{b, Complement[{1, 2, 3}, {a}]},
{c, Complement[{1, 2, 3}, {a, b}]}
];

Now you call:


withIteratorLex[env, {it, Table[{a, b}, it]}]

(* {{{{1, 2}}, {{1, 3}}}, {{{2, 1}}, {{2, 3}}}, {{{3, 1}}, {{3,2}}}} *)


The bindings for a and b remain split between env and the code in Table, but they are dynamic anyway, so this is kind of ok. But the binding of it is now fully lexical, which is certainly a plus.


Remarks


The conclusion seems to be that the complexity of the solution directly depends on how the code is split into part / building blocks. To quote John Hughes ("Why functional programming matters"), "Our ability to decompose a problem into parts depends directly on our ability to glue solutions together". Mathematica provides various ways to glue things together, and depending on our choice of building blocks, the composability of them is different.


Philosophically, the problems with the original approach were mostly because you tried to break the code into pieces which, in the context of iterators and variable bindings, do not make sense by themselves, and therefore require extra trickery on every invocation. As a rule, it is better to incapsulate the process of variable binding together with a piece of code, rather than doing tricks with scope surgery and evaluation control to de-facto implement binding at the moment when you call your code. To put it differently, scoping constructs nest and compose well, so whenever the problem asks for it, it may be a good idea to create one.


Comments

Popular posts from this blog

plotting - Filling between two spheres in SphericalPlot3D

Manipulate[ SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, Mesh -> None, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], {n, 0, 1}] I cant' seem to be able to make a filling between two spheres. I've already tried the obvious Filling -> {1 -> {2}} but Mathematica doesn't seem to like that option. Is there any easy way around this or ... Answer There is no built-in filling in SphericalPlot3D . One option is to use ParametricPlot3D to draw the surfaces between the two shells: Manipulate[ Show[SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], ParametricPlot3D[{ r {Sin[t] Cos[1.5 Pi], Sin[t] Sin[1.5 Pi], Cos[t]}, r {Sin[t] Cos[0 Pi], Sin[t] Sin[0 Pi], Cos[t]}}, {r, 1, 2 - n}, {t, 0, Pi}, PlotStyle -> Yellow, Mesh -> {2, 15}]], {n, 0, 1}]

plotting - Plot 4D data with color as 4th dimension

I have a list of 4D data (x position, y position, amplitude, wavelength). I want to plot x, y, and amplitude on a 3D plot and have the color of the points correspond to the wavelength. I have seen many examples using functions to define color but my wavelength cannot be expressed by an analytic function. Is there a simple way to do this? Answer Here a another possible way to visualize 4D data: data = Flatten[Table[{x, y, x^2 + y^2, Sin[x - y]}, {x, -Pi, Pi,Pi/10}, {y,-Pi,Pi, Pi/10}], 1]; You can use the function Point along with VertexColors . Now the points are places using the first three elements and the color is determined by the fourth. In this case I used Hue, but you can use whatever you prefer. Graphics3D[ Point[data[[All, 1 ;; 3]], VertexColors -> Hue /@ data[[All, 4]]], Axes -> True, BoxRatios -> {1, 1, 1/GoldenRatio}]

plotting - Mathematica: 3D plot based on combined 2D graphs

I have several sigmoidal fits to 3 different datasets, with mean fit predictions plus the 95% confidence limits (not symmetrical around the mean) and the actual data. I would now like to show these different 2D plots projected in 3D as in but then using proper perspective. In the link here they give some solutions to combine the plots using isometric perspective, but I would like to use proper 3 point perspective. Any thoughts? Also any way to show the mean points per time point for each series plus or minus the standard error on the mean would be cool too, either using points+vertical bars, or using spheres plus tubes. Below are some test data and the fit function I am using. Note that I am working on a logit(proportion) scale and that the final vertical scale is Log10(percentage). (* some test data *) data = Table[Null, {i, 4}]; data[[1]] = {{1, -5.8}, {2, -5.4}, {3, -0.8}, {4, -0.2}, {5, 4.6}, {1, -6.4}, {2, -5.6}, {3, -0.7}, {4, 0.04}, {5, 1.0}, {1, -6.8}, {2, -4.7}, {3, -1.