1
votes

I want to write a recursive function, that evaluates symbolic variables. Here's an example in python:

x = ["x0",...]
y = ["y0",...]
def f(n):
    if n<=0:
        return x[0]
    t1 = x[n]
    t2 = y[n]
    r = f(n-1)
    return t1+t2+r

How can I reimplement that in Mathematica?

I tried creating variable names manually:

toFixedWidth[n_Integer, width_Integer] := \
StringJoin[PadLeft[Characters[ToString[n]], width, "0"]]
make_var[i_] := ToExpression[StringJoin["x", toFixedWidth[i, 2]]]
xtab := Table[{make_var[i]}, {i, 0, 10}]
xtab

But it doesn't work:

{{make_var[0]}, {make_var[1]}, {make_var[2]}, {make_var[3]}, {
  make_var[4]}, {make_var[5]}, {make_var[6]}, {make_var[7]}, {
  make_var[8]}, {make_var[9]}, {make_var[10]}}

I want to see how the expression unfolds (for a more complicated function than in the example), that's why I want all variables to be symbolic.

1

1 Answers

3
votes

Underscores are reserved for pattern matching (Blank). Try makevar instead:

toFixedWidth[n_Integer, width_Integer] := 
 StringJoin[PadLeft[Characters[ToString[n]], width, "0"]]
makevar[i_] := ToExpression[StringJoin["x", toFixedWidth[i, 2]]]
xtab := Table[{makevar[i]}, {i, 0, 10}]
xtab
{{x00}, {x01}, {x02}, {x03}, {x04}, {x05}, {x06}, {x07}, {x08}, {x09}, {x10}}

Incidentally:

Table[Unique["x"], {11}]
{x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11}