Range Over Built in Modelica
Based on the code and the explanation provided, here is the corresponding Modelica code:
Our first program will print the classic “hello world” message. Here’s the full source code.
model HelloWorld
function printHelloWorld
input String message;
algorithm
print(message);
end printHelloWorld;
algorithm
printHelloWorld("hello world");
end HelloWorld;
To run the program, save the code in a .mo
file and use the OpenModelica compiler omc
to execute it:
$ omc HelloWorld.mo
We have successfully printed the “hello world” message using Modelica. Let’s learn more about the language by exploring more examples.
Here we use a loop to sum the numbers in an array. Arrays work like this too.
model SumArray
Real nums[3] = {2, 3, 4};
Real sum = 0;
algorithm
for i in 1:size(nums, 1) loop
sum := sum + nums[i];
end for;
print("sum: " + String(sum));
end SumArray;
The above code sums the array elements using a for
loop and prints the result:
$ omc SumArray.mo
sum: 9
To iterate over arrays and get index and value for each entry, although Modelica does not have a direct way to ignore indices like _
, you can simply access both.
model IndexValue
Real nums[3] = {2, 3, 4};
algorithm
for i in 1:size(nums, 1) loop
if nums[i] == 3 then
print("index: " + String(i - 1));
end if;
end for;
end IndexValue;
Output:
$ omc IndexValue.mo
index: 1
Modelica also allows iterating over key/value pairs in a dictionary-like way using records, but it’s more common to handle key-value arrays.
record KeyValue
String key;
String value;
end KeyValue;
model KeyValuePair
KeyValue kvs[2] = {KeyValue("a", "apple"), KeyValue("b", "banana")};
algorithm
for i in 1:size(kvs, 1) loop
print(kvs[i].key + " -> " + kvs[i].value);
end for;
end KeyValuePair;
Output:
$ omc KeyValuePair.mo
a -> apple
b -> banana
To iterate over just the keys, one can simply access the key field of the record.
model KeysOnly
KeyValue kvs[2] = {KeyValue("a", "apple"), KeyValue("b", "banana")};
algorithm
for i in 1:size(kvs, 1) loop
print("key: " + kvs[i].key);
end for;
end KeysOnly;
Output:
$ omc KeysOnly.mo
key: a
key: b
Iterating over strings requires accessing string characters individually.
model StringIteration
String str = "go";
algorithm
for i in 1:length(str) loop
print(String(i - 1) + " " + String(str[i]));
end for;
end StringIteration;
Output:
$ omc StringIteration.mo
0 g
1 o
Now that we understand how to perform these iterations in Modelica, let’s continue to explore more features of the language.