Message Boards Message Boards

5 Replies
3 Total Likes
View groups...
Share this post:

Recursive function with no apparent recursive relationship

Posted 9 years ago


I would like to understand a code which is a recursive function with this kind of structure f[x, y] := {f[x], f[y]}. This case is present in the XMLNote function used in the help for "Transforming XML".

I have already spent time on the help to look for more about recursive functions. But, I have seen only recursive functions such as Pise[0] = Pise[1] = 1; Pise[n_] := Pise[n - 1] + Pise[n - 2] . In this case, I understand how the indentation is made that is to say how the term of index n is calculated from the terms of index n-1 and n-2.

But, for this kind of recursive function f[x, y] := {f[x], f[y]}, i don't understand how the indentation is made.

May you complete me this example/ or furnish me a small example so that I can see how this kind of recursion works ?

Thanks for your help

5 Replies

Alternatively one could make the statement:

Attributes[f] = Listable;

This works in the case that the lists contain more than two elements.


POSTED BY: Henrik Schachner
Posted 9 years ago

Perfectly clear. Thank you


Since {1, 2} is one argument, a list with two elements, you have to add another definition like f[{x_, y_}] := {f[x], f[y]}.

Or you can do this in one line if you want:

f[{x_, y_} | PatternSequence[x_, y_]] := {f[x], f[y]}
f[{1, 2}, {2, 3}]

{{f[1], f[2]}, {f[2], f[3]}}

POSTED BY: Kuba Podkalicki
Posted 9 years ago

Yes, i almost understand. Thank you for your clear explanation.

I only need to apply it on a simple example

When i evaluate f[2, 3], the result is {f[2], f[3]}. Logically, the recursive function stops because each function has only one argument.

But I evaluate f[{2, 3}, {3, 3}], the result is {f[{2, 3}], f[{3, 3}]}. I would like to Mathematica continue the indentation. I believe that it becomes i didn't use the syntax of the list well.

May you help me to correct my syntax so that I can test this kind of recursive function on a example ?

Thanks a lot for your help.


The function you've provided is not refering to itself basing on values of arguments that were provided but basing on the pattern that those arguments match*.

p.s. you probably wanted to write:

f[x_, y_]:= {f[x], f[y]}

So f refers to itself only when you provide two arguments. Then it is returning itself scanned over those arguments. And since for f acting on one argument are no associated values the recursion stops.

Is that clear?

POSTED BY: Kuba Podkalicki
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract