From the book "Essentials of Programming in Mathematica" (Fibonacci numbers):
If we think of this sequence as a function, we would just change this to a functional definition.
F(1) = 1
F(2) = 1
F(n) = F(n – 2) + F(n – 1), for n > 2
In this form, we can translate the definition directly into code. The condition n > 2
is unnecessary because specific rules such as F[1] = 1
are looked up before more general rules like that for F[n]
.
F[1] = 1;
F[2] = 1;
F[n_] := F[n - 2] + F[n - 1]
Questions
What do
F[1] = 1;
andF[2] = 1;
mean, and what they do? For me, it looks like we are calling the function that is not even defined yet and assigning it a value. I do not understand that.How
F[n_] := F[n - 2] + F[n - 1]
andF[1] = 1;
andF[2] = 1;
are related to each other and how they influence each other?Is there is another, better example to understand recursion in Mathematica?
f[1]=
is mentioned in Details section as well as e.g. in Scope / lhs. $\endgroup$DownValues
and "everything is an expression". $\endgroup$