Re: Self referring function
- To: mathgroup at smc.vnet.net
- Subject: [mg2426] Re: Self referring function
- From: rubin at msu.edu (Paul A. Rubin)
- Date: Sun, 5 Nov 1995 16:07:01 -0500
- Organization: Michigan State University
In article <479b5h$j5n at ralph.vnet.net>, mvyver at ecel.uwa.edu.au (Mark Van de Vyver) wrote: ->Hi, -> ->I've run into the following weird (well to me at least) function which ->appears in a module. ->I'm still working through Maeder's Programming in MMA (2nd Ed.) and haven't ->seen an explanation/example yet, or I've missed it! -> ->The set up is: -> ->Module[ {input1, input2, a=x[], b=y[]}, -> f[input1_, input2_] := f[input1, input2] = If[input1==c, g[], -> Max[ {a, b}.{f[ input1, input2+1 ], f[ input1+1, input2+1 ->]}, g[] ] ]; -> res=f[0, 0]; -> Clear[ f ]; -> res ]; -> ->I'll point out that everyhting works, but the fact that f[] is defined in ->terms of itself I found a bit weird. ->Could someone point me to a text example that makes the how and why clear? ->In the mean time I'll keep plugging away at Maeder. -> ->Thanks in advance. -> ->Mark -> Mark Van de Vyver ->_________________________________________________________________________ ____ -> Mark Van de Vyver -> Department of Accounting and Finance Phone: (61) (09) 380-2510 -> University of Western Australia Fax: (61) (09) 380-1047 -> Nedlands 6907 e-mail: mvyver at ecel.uwa.edu.au -> Perth ->_________________________________________________________________________ ____ Check out Section 2.4.9 (page 258) in Wolfram's Mathematica book (2nd ed.). The basic idea is that the first time f is called with a particular pair of arguments (say f[a,b]), the SetDelayed part of the definition is invoked, the If[...] expression is evaluated, and f[a,b] is Set to that expression. Thereafter, if f[a,b] is called again (same arguments a and b), instead of recomputing the If[...] expression, Mma will find the result tabulated in memory and will just regurgitate it. The validity of this in your context hinges on the value of f[a,b] always being the same with each evaluation (specifically, c never changing in your case). Paul ************************************************************************** * Paul A. Rubin Phone: (517) 432-3509 * * Department of Management Fax: (517) 432-1111 * * Eli Broad Graduate School of Management Net: RUBIN at MSU.EDU * * Michigan State University * * East Lansing, MI 48824-1122 (USA) * ************************************************************************** Mathematicians are like Frenchmen: whenever you say something to them, they translate it into their own language, and at once it is something entirely different. J. W. v. GOETHE