I am making complex 3d graphics, and to clear up functions, I want to use With
to remove a repeated action. This action occurs many times through many functions, so I want the With
outside all of them, so I only declare it once. Except Mathematica doesn't seem to like having a With
outside a function, if it is replacing parameters. A simplified version is shown below:
With[{y = x},
draw[x_] := Cylinder[{{y,0,0}, {y+1,0,1}}, 0.1]
...(*other functions:See Bottom!!!!!!!!*)
]
then:
Graphics3D[draw[3]]
If I do the above, it brings the error:
So it should go y -> x -> 3. But it only gets half-way. It has changed y to x but I think it is after when the parameters are put in, so x is not changed to 3. Is there a way to keep the with
outside, so it is only declared once.
Also, in case anybody says put the With
before cylinder
. No, I don't want to do that, as there are other functions using the values changed by "With"
-----------------------EDIT-----------------------------
The answers can replace the values for one function, as is shown in the code example, but it doesn't show (although I did say it), that it needs to work through many functions, as shown below. Sorry for the confusion, as causing the first two answers to not fully work.
With[{y = x},
draw1[x_] := Cylinder[{{y, 0, 0}, {y + 1, 0, 1}}, 0.1],
draw2[x_] := Cylinder[{{y, 0, 0}, {y + 1, 0, 1}}, 0.2]
...(*more functions*)
]
draw[3]
will yield the outputCylinder[{{x, 0, 0}, {x, 0, 0}}, 0.1]
. In other words, Mathematica doesn't think the formula you've given it fordraw
involves the input variable at all. $\endgroup$Function[ draw[x_] := Cylinder[{{#, 0, 0}, {# + 1, 0, 0}}, 0.1] ][x]
, notice I've added+1
since your code makes no sense. $\endgroup$Function[ draw1[x_] := Cylinder[{{#, 0, 0}, {# + 1, 0, 1}}, 0.1]; draw2[x_] := Cylinder[{{#, 0, 0}, {# + 1, 0, 1}}, 0.2];][x]
$\endgroup$