# Build nested function

By running the following code:

q[y_] = y;

For[i = 1, i <= 4, i++, q[y_] = q[If[1 - i <= x <= 2 + i, i, y]]];

f[x_] = q[If[7 <= x <= 6, 10 x, x]];

f[x]


I get:

If[0 <= x <= 3, i,
If[-1 <= x <= 4, i, If[-2 <= x <= 5, i, If[-3 <= x <= 6, i, x]]]]


and unfortunately I just can not figure out how to get the value of "i" and not "i" ultimate expression!

For example:

f[x_] = If[0 <= x <= 1 - 1/5, x,  If[1 + 1/5 <= x <= 2, -x + 2, 1 - 1/5]];

Plot[f[x], {x, 0, 2}] So, in short, I'm interested in building a function f with the characteristics described above and can not find an effective way to do this (what I have shown is the one thing that is the closest). The actual setting is really complicated to explain, all will be placed in a much larger program.

• Please clarify what you're attempting to accomplish, and why you choose this approach. – kirma Jul 27 '16 at 10:16
• Have you seen Nest[]? – J. M.'s discontentment Jul 27 '16 at 10:38
• @J.M. Once I understood what the For construct was trying to accomplish, I definitely ran into the same conclusion. :) - That is, imperative redeclaration of q is not very easy to understand and not very Mathematica-like. – kirma Jul 27 '16 at 10:44
• @Manu, why not describe your actual problem and then maybe show what you expect to get from, say, two or three nestings? – J. M.'s discontentment Jul 27 '16 at 10:46

If has attribute HoldRest, which you can clear, but I don't recommend that.

I think the right solution is to replace a[HoldedArgument] by a[#] &[ToDoBeforeHold], i.e.

q[y_] = y;
For[i = 1, i <= 4, i++, q[y_] = q[If[1 - i <= x <= 2 + i, #, #2] &[i, y]]];
f[x_] = q[If[7 <= x <= 6, 10 x, x]];
f[x]


You may use Piecewise.

For your For loop function

g[x_] = Piecewise[{#, 1 - # <= x <= 2 + #} & /@ Range]

Plot[g[x], {x, -3, 6}] f[x_] = Piecewise[{
{x       ,  0 <= x <= 1 - 1/5},
{-x + 2  , 1 + 1/5 <= x <= 2},
{1 - 1/5 , True}
}]

Plot[f[x], {x, 0, 2}] Hope this helps.

• @Manu See update. – Edmund Jul 27 '16 at 11:58
• @Manu, Edmund's methods ought to be easily extendible by changing the appropriate numbers. – J. M.'s discontentment Jul 27 '16 at 11:59
• @Manu The key is Piecewise. Generate your list of value-condition pairs with your algorithm and enclose that list in Piecewise. – Edmund Jul 27 '16 at 12:08
• @Manu Piecewise evaluates its conditions in the order they are given and returns the value of the first condition that is true. Therefore you can Join your exclusion value-condition pairs to the list of value-condition pairs generated by your algorithm. Then enclose this list in Piecewise. For example Piecewise[Join[{{x, 0 < x < .5}, {-x + 1, .5 <= x < 1}}, {#, 1 - # <= x <= 2 + #} & /@Range]]. – Edmund Jul 27 '16 at 12:33