1
$\begingroup$

I'm using this example to study Mathematics.Example Demo. In this example, before generating recursion tree, she flats the function. But I have a difficultly to understand how flatten works, especially the 3rd line of the code below. Could someone teach me? Thank you very much.

f[___, 0] := {};
f[___, 1] := {};
f[m___, p_] := {{m, p} -> {m, p, p - 1}, {m, p} -> {m, p, p - 2}, //How to understand this line?
f[m, p, p - 1], f[m, p, p - 2]}
j[n_] := f[n] // Flatten
$\endgroup$
2
$\begingroup$

To understand j[n__]:= f[n] //Flatten we need to understand f[n]. As an example, take f[3].

MMA applies more specific definitions first. In this case this will be f[m___, p_], where m is empty. Therefore, we replace f[3] by

{{3} -> {3, 2}, {3} -> {3, 1}, f[3,2],f[3,1]}. 

f[3, 1] is, by definition, an empty list.

f[3, 2] is, by the pattern: f[m___, p_],

{{3, 2} -> {3, 2, 1}, {3, 2} -> {3, 2, 0}, f[3, 2, 1], f3, 2, 0]}. 

f[3, 2, 1] and f3, 2, 0] are by definition empty lists, so this is:

{{3, 2} -> {3, 2, 1}, {3, 2} -> {3, 2, 0}, {}, {}}

Inserting f[3, 2] and f[3, 1] in the list above:

{{3} -> {3, 2}, {3} -> {3, 1}, {{3, 2} -> {3, 2, 1}, {3, 2} -> {3, 2, 0}, {}, {}}, {}}

Flatten will take away the empty lists. So we finally get:

{{3} -> {3, 2}, {3} -> {3, 1}, {3, 2} -> {3, 2, 1}, {3, 2} -> {3, 2, 0}}
$\endgroup$
3
  • $\begingroup$ Thank you very much for your answer. But I don't understand f[m___, p_] := {{m, p} -> {m, p, p - 1}, {m, p} -> {m, p, p - 2}. What does this step {{m, p} -> {m, p, p - 1} mean? Sorry I'm new to use Mathematic so it's must be very naive question. Thanks in advance. $\endgroup$ – RAN LIU Feb 16 at 18:56
  • $\begingroup$ MMA works not like other languages, it is a replacement system That means, you define patters and replacements. If MMA finds a pattern it replaces it with the replacement and keeps on doing this until nothing changes anymore. ` f[m___, p_] := {{m, p} -> {m, p, p - 1}, {m, p}` defines a pattern ` f[m___, p_] ` and a replacement: {{m, p} -> {m, p, p - 1}, {m, p} -> {m, p, p - 2}. If MMA find a part that matches the pattern, it replaces it by the replacement. Look pattern matching up in the help. E.g. _ means "anything". You may name this, e.g. p_. __means one or more "anythings" e.t.c $\endgroup$ – Daniel Huber Feb 16 at 19:33
  • $\begingroup$ Gotcha! Thank you so much. $\endgroup$ – RAN LIU Feb 16 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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