For in Modelica
In Modelica, loops are primarily implemented using the for
construct. Let’s explore different types of loops and their usage.
model ForLoops
parameter Integer n = 3;
equation
// The most basic type, with a single condition
for i in 1:3 loop
Modelica.Utilities.Streams.print(String(i));
end for;
// A classic initial/condition/after loop
for j in 0:2 loop
Modelica.Utilities.Streams.print(String(j));
end for;
// Iterating over a range
for i in 0:n-1 loop
Modelica.Utilities.Streams.print("range " + String(i));
end for;
// Modelica doesn't have an exact equivalent to Go's infinite loop,
// but you can create a loop that runs for a very long time
for k in 1:1e6 loop
Modelica.Utilities.Streams.print("loop");
break;
end for;
// Demonstrating continue (in Modelica, it's called 'next')
for m in 0:5 loop
if mod(m, 2) == 0 then
next;
end if;
Modelica.Utilities.Streams.print(String(m));
end for;
end ForLoops;
In this example:
We use the basic
for
loop syntax to iterate over a range of values.Modelica’s
for
loops are more similar to range-based for loops in other languages, where you specify a range to iterate over.Modelica doesn’t have a direct equivalent to Go’s condition-only
for
loop, but you can achieve similar results by using a range.There’s no built-in infinite loop in Modelica, but you can create a loop with a very large range to simulate one.
Instead of
continue
, Modelica usesnext
to skip to the next iteration.Modelica doesn’t have a
break
statement for loops. To exit a loop early, you typically need to use a conditional statement that covers the entire loop body.
When you run this model, it will print:
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5
Note that Modelica is primarily used for modeling physical systems and simulations, so its looping constructs are often used differently than in general-purpose programming languages. The equation
section in Modelica models is used for writing equations that describe the system’s behavior, rather than imperative statements.
Modelica also provides other ways to work with arrays and iterate over elements, which can be more appropriate in certain modeling scenarios.