MathGroup Archive 2002

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Pure recursive functions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg38369] Re: [mg38341] Pure recursive functions
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Fri, 13 Dec 2002 04:09:13 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

Well, you can use:

Function[If[#1 == 0, 1, #1 #0[#1 - 1]]]

for example:

In[36]:=
Function[If[#1==0,1,#1 #0[#1-1]]][3]

Out[36]=
6


#0 is a rarely used "parameter" which refers to the pure function 
itself and thus makes it possible to create pure recursive functions. I 
may be wrong but it seems to me that this feature is unique to 
Mathematica.

Andrzej Kozlowski
Yokohama, Japan
http://www.mimuw.edu.pl/~akoz/
http://platon.c.u-tokyo.ac.jp/andrzej/



On Thursday, December 12, 2002, at 03:36 PM, Niall Palfreyman wrote:

> Hello,
>
> I'm new to Mathematica, and I have a question to which I've found no
> answers in the archives. Can you help?
>
> The issue is: how do I create a pure recursive function? Normally when
> creating a recursive function I use the name of the function to perform
> the recursive call:
>
> fact[n_] :=
>   If[n == 1, 1, n fact[n - 1]]
>
> However this has the disadvantage that the symbol "fact" is now global.
> The logical step to make the name of the function local is something
> like:
>
> Function[factl, factl[5]] @@ {Function[n, If[n == 0, 1, n factl[n -
> 1]]]}
>
> or maybe:
>
> With[{fact = Function[n, If[n == 0, 1, n fact[n - 1]]]}, fact[5]]
>
> However both of these solutions steadfastly return the value "5
> fact[4]". I assume the problem is that the variables initialised in
> Function[] and With[] must be symbols, and cannot be patterns. But a
> recursion requires a pattern (n_ in the first, global, solution above).
> What do I do to get factorial to work _without_ making the symbol 
> "fact"
> global?
>
> I'd be grateful for any help.
>
> Thanks,
> Niall.
>
>
>



  • Prev by Date: Re: Plot[x Sin[x],{-100,100}] Bad {-100,99} Good?
  • Next by Date: Re: Polynomial GCD as Linear Combination
  • Previous by thread: Re: Pure recursive functions
  • Next by thread: RE: Pure recursive functions