Recherche Google
OpenMusic 6 – User ManualAdvanced Visual Programming > Abstraction > Recursive Patches > Recursion in OM
previous pagenext page

Recursion in OM

Creating a Recursion

Creating a recursion : a patch is dropped into its own editor.
Creating a recursion : a patch is dropped into its own editor.

Recursive programs can be designed in OM by inserting the reference of a blue patch in its own editor – that is, putting a patch within itself. If this patch has inputs and outputs, they will also appear on the patch box, so that the patch can be "called from inside itself".

Infinite Calls

A termination condition is absolutely necessary to call a recursive patch. Otherwise, a succession of infinite calls will be triggered at the evaluation. Remind to save all your material before calling a recursive patch.

Example : Implementation of the Factorial Function

Factorial Patch

We have renamed the recursive patch as "fact". We will use it to create a recursive function that actually corresponds to the factorial function.

The function has one input, n, which calculates fact(n) = n * fact(n-1).

This function has no termination condition. If it is called in its current state, it will never end.

  • The n values sent recursively are strictly decreasing, since they are always equal to n-1.
  • Besides, we know that fact(1) = 1.
  • Therefore, we will add a non recursive branch, applying to cases where n = 1, via omif.
Implementing a Termination Condition

The resulting patch means : if n = 1, then fact(n) = 1 else, fact(n) = n * fact(n-1)

  1. When omif is evaluated, it evaluates the = predicate.

  2. The = predicate returns "nil" if n ≠ 1 and "t" if n = 1. This is the termination condition of the patch.

    • omif returns the value of its second input (1), if it gets "t".
    • omif triggers the evaluation of the boxes that are connected to its third input if n ≠ 1.
    • The factorial of n is calculated by om-, the fact sub patch and om*.
Internal Patch Recursion

Do not ever build recursive programs with internal – red – patches, or with OMLoop boxes. A function has to be global to apply within itself.

previous pagenext page
About...(c) Ircam - Centre PompidouMade with Scenari