Recursion in Modelica

Our example demonstrates recursive functions in Modelica. Here’s a classic factorial implementation:

function factorial
  input Integer n;
  output Integer result;
algorithm
  if n == 0 then
    result := 1;
  else
    result := n * factorial(n - 1);
  end if;
end factorial;

model RecursionExample
  Integer fact7;
equation
  fact7 = factorial(7);
  
  when terminal() then
    Modelica.Utilities.Streams.print("Factorial of 7: " + String(fact7));
  end when;
end RecursionExample;

This factorial function calls itself until it reaches the base case of factorial(0).

In the RecursionExample model, we calculate the factorial of 7 and print the result.

Modelica doesn’t have a direct equivalent to closures or anonymous functions. However, we can achieve similar functionality using function pointers. Here’s an example of a recursive Fibonacci function using a function pointer:

function fibonacciImpl
  input Integer n;
  input FibonacciFunc fibFunc;
  output Integer result;
algorithm
  if n < 2 then
    result := n;
  else
    result := fibFunc(n-1, fibFunc) + fibFunc(n-2, fibFunc);
  end if;
end fibonacciImpl;

function fibonacci
  input Integer n;
  output Integer result;
algorithm
  result := fibonacciImpl(n, fibonacciImpl);
end fibonacci;

model RecursionExample
  Integer fib7;
equation
  fib7 = fibonacci(7);
  
  when terminal() then
    Modelica.Utilities.Streams.print("Fibonacci of 7: " + String(fib7));
  end when;
end RecursionExample;

In this example, we define a fibonacciImpl function that takes a function pointer fibFunc as an argument. The fibonacci function then calls fibonacciImpl with itself as the function pointer, allowing for recursion.

To run these examples, you would typically use a Modelica simulation environment. The results would be printed at the end of the simulation:

Factorial of 7: 5040
Fibonacci of 7: 13

Note that Modelica is primarily used for physical system modeling and simulation, so these examples are somewhat atypical. In practice, recursive algorithms in Modelica are less common than in general-purpose programming languages.