# Recursive function

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.

• Try list^Range[Length[list]]. – J. M.'s discontentment Jan 2 '17 at 17:28
• 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) – Kristijan Šaver Jan 2 '17 at 19:36
• 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. – Bill Jan 2 '17 at 19:41
• @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. – Mr.Wizard Jan 3 '17 at 9:45

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}