I have a question about using a recursive function in a module. I made the following example to illustrate the question.

The followwing code works:

fib[1] = 1;
fib[2] = 1;
fib[n_] := fib[n - 1] + fib[n - 2]
f[a_, b_, n_] := Module[{x, y},
fib[1] = a;
fib[2] = b;
x = fib[n];
fib[1] = 2 a;
fib[2] = 2 b;
y = fib[n];
x + y
f[1, 1, 3] = 6.

but is slow, I want to use memoization, i.e.

fib[n_] := fib[n] = fib[n - 1] + fib[n - 2] 

but in that case

f[1, 1, 3] = 4. 

Question: How can I use a recursive function in a Module?

  • $\begingroup$ Isn't memoizing fib[a_,b_,n_] more appropriate? $\endgroup$ Nov 11, 2013 at 14:47

1 Answer 1


Here is one possibility:

      fibF[fib[1]=a;fib[2]=b;fib[n]] + fibF[fib[1]=2 a;fib[2]=2 b;fib[n]]

which uses memoization separately for both branches and is fast.

  • $\begingroup$ Again, you got me on the With / Module issue. :-) $\endgroup$ Nov 11, 2013 at 15:05
  • $\begingroup$ @ndroock1 Here, you have two completely separate branches, which are totally decoupled. Module is useful when you do need stateful variables which you mutate during the computation, or sometimes to introduce local (private) functions. It doesn't look like either of these is really needed here. $\endgroup$ Nov 11, 2013 at 15:07
  • $\begingroup$ @ndroock1 By the way, for the actual problem you are trying to solve, you might find the title of the question misleading. There are valid use cases where one does want to have recursive local functions defined within Module, but this one seems to be not it. $\endgroup$ Nov 11, 2013 at 15:09
  • $\begingroup$ As I mentioned @Leonid, it is only a styled example I could come up with to illustrate my question without putting too much irrelevant stuff in the question. I think it helps those who answer questions a lot if they have a snippet of code to start with and to test their answer. $\endgroup$ Nov 11, 2013 at 15:56
  • $\begingroup$ @ndroock1 Re: snippet of code - absolutely, I don't dispute that. All I meant was that the title of your question might not reflect the actual problem you had to solve, since apparently using Module and Module-local variables does not seem to be essential here. $\endgroup$ Nov 11, 2013 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.