MathGroup Archive 2002

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

Search the Archive

RE: Pure recursive functions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg38424] RE: [mg38363] Pure recursive functions
  • From: "David Park" <djmp at earthlink.net>
  • Date: Sat, 14 Dec 2002 03:20:29 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

Niall,

What objection do you have to making fact a Global variable? That is the
normal Mathematica usage. Every symbol you create is put in the Global
context (unless you are writing a package and put it in the package
context.)

Your recursive function could probably be better written with multiple
definitions as follows.

fact[0] := 1;
fact[n_] := n fact[n - 1]

Often it may be useful to use "dynamic programming" (Section 2.4.9) so as to
save computed values.

fact[0] := 1;
fact[n_] := fact[n] = n fact[n - 1]

David Park
djmp at earthlink.net
http://home.earthlink.net/~djmp/


From: Niall Palfreyman [mailto:niall.palfreyman at fh-weihenstephan.de]
To: mathgroup at smc.vnet.net

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 == 0, 1, n fact[n - 1]]

However this has the disadvantage that the symbol "fact" is now global.
The logical step to avoid this seems to be to make the name of the
function local as in something like the following:

Function[fact, fact[5]] @@ {Function[n, If[n==0, 1, n fact[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: More about ellipse and circle intersection
  • Next by Date: Re: Question about precision.
  • Previous by thread: Re: Pure recursive functions
  • Next by thread: PlusMinus Operator Question