Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.math.mathematica

Topic: Creating a recursive function which returns a sequence
Replies: 2   Last Post: Oct 25, 2012 1:42 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Sseziwa Mukasa

Posts: 106
Registered: 8/26/07
Re: Creating a recursive function which returns a sequence
Posted: Oct 25, 2012 1:41 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

Flatten does what you need. Also there's no need to use Return:

(Debug) In[5]:= f[n_] := Module[{}, If[n < 0, {},
Flatten[{g[n], f[n - 1]}]]]
(Debug) In[6]:= f[2]
(Debug) Out[6]= {g[2], g[1], g[0]}

Sequence makes no sense outside of a function, so you can just do Sequence@@f[n] when you want to insert the result as the argument of another function.

Regards,
Sseziwa

On Oct 24, 2012, at 3:32 AM, Wei-Hsun Lin wrote:

> Hello all,
>
> I would like to create a recursive function of which the returning
> value is a sequence. For example,
>
> f[n_]:=Module[{},
> If[n<0,Return[Sequence[]]];
> Sequence[g[n],f[n-1]]
> ]
>
> The above code doesn't work because the Sequence function was
> evaluated before it's returned.
> Could anyone please advise me as to what's is the usual way to achieve
> this? Thank you very much!
>
> The result I want is
>
> f[2]
> =Sequence[g[2],f[1]]
> =Sequence[g[2],Sequence[g[1],f[0]]]
> =Sequence[g[2],g[1],f[0]]
> =Sequence[g[2],g[1],Sequence[g[0],f[-1]]]
> =Sequence[g[2],g[1],g[0],f[-1]]
> =Sequence[g[2],g[1],g[0],Sequence[]]
> =Sequence[g[2],g[1],g[0]]
>
> Best regards,
> Wei-Hsun
>






Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.