I'm trying to define a function that takes in a list (a1,a2,a3,...,an) and spits out (a1^1, a2^2, a3^3,...,an^n) using recursion. So far I've tried a lot of different things that don't work, and I would appreciate some help.

  • 1
    $\begingroup$ Try list^Range[Length[list]]. $\endgroup$ Jan 2, 2017 at 17:28
  • $\begingroup$ Works, thanks. how about a function that takes in (a1,a2,a3,...,an) and spits out an extended version (a1,a1, a2,a2,a3,a3,..,an,an) $\endgroup$ Jan 2, 2017 at 19:36
  • 1
    $\begingroup$ This sounds a lot like homework so I'll only offer a hint. I assume you have already learned how to write a recursive function that would, for example, divide each element by 3. This new problem requires the function keep track of how many times it has been called. So add one extra argument to the function. Imagine on your first call you make that argument=1. And each recursive call increments the value of that argument. That should be enough of a hint. $\endgroup$
    – Bill
    Jan 2, 2017 at 19:41
  • $\begingroup$ @Bill FWIW this problem does not require that one directly keep track of how many times the function is called; the recursion itself can build a structure with a shape that tracks this inherently. See my answer for an example. $\endgroup$
    – Mr.Wizard
    Jan 3, 2017 at 9:45

1 Answer 1


Using Mathematica's destructuring and list multiplication:

f[{a_, b___}] := Join[{a}, {b}*f[{b}]]

f[{a1, a2, a3, a4, a5}]
{a1, a2^2, a3^3, a4^4, a5^5}

In the comments you mention a second problem:

f2[{a_, b___}] := Join[{a, a}, f2[{b}]]
f2[{}] := {}

f2[{a1, a2, a3, a4, a5}]
{a1, a1, a2, a2, a3, a3, a4, a4, a5, a5}

Though practically this is better done in Mathematica without recursion:

Riffle[#, #] & @ {a1, a2, a3, a4, a5}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.