Generics in Modelica

Our example demonstrates the concept of generic programming in Modelica. While Modelica doesn’t have built-in generics like some other languages, we can achieve similar functionality using replaceable types and redeclarations.

First, let’s create a generic function that finds the index of an element in an array:

function SlicesIndex
  replaceable type T;
  input T[:] arr;
  input T value;
  output Integer index;
algorithm
  index := -1;
  for i in 1:size(arr, 1) loop
    if arr[i] == value then
      index := i;
      break;
    end if;
  end for;
end SlicesIndex;

Now, let’s create a generic linked list structure:

model List
  replaceable type T;
  
  record Element
    T value;
    Element next;
  end Element;
  
  Element head;
  Element tail;
  
  function push
    input T v;
  algorithm
    if tail == null then
      head := Element(v, null);
      tail := head;
    else
      tail.next := Element(v, null);
      tail := tail.next;
    end if;
  end push;
  
  function allElements
    output T[:] elements;
  algorithm
    elements := {};
    for e in Element(head.value, head.next) loop
      elements := cat(1, elements, {e.value});
    end for;
  end allElements;
end List;

Now, let’s use these generic structures:

model Main
  String[:] s = {"foo", "bar", "zoo"};
  Integer index;
  List intList(redeclare type T = Integer);
equation
  index = SlicesIndex(s, "zoo");
  
  when initial() then
    intList.push(10);
    intList.push(13);
    intList.push(23);
  end when;
  
  when terminal() then
    Modelica.Utilities.Streams.print("index of zoo: " + String(index));
    Modelica.Utilities.Streams.print("list: " + String(intList.allElements()));
  end when;
end Main;

In this Modelica example, we’ve created generic-like structures using replaceable types. The SlicesIndex function can work with any type of array, and the List model can store any type of data.

To use these generic structures, we specify the actual type when instantiating. For example, intList(redeclare type T = Integer) creates a list of integers.

Note that Modelica’s approach to generics is different from some other languages. Instead of type parameters, Modelica uses replaceable types and redeclarations to achieve similar functionality.

When you simulate this model, it will print the index of “zoo” in the string array and the contents of the integer list.

index of zoo: 3
list: {10, 13, 23}

This example demonstrates how to implement generic-like behavior in Modelica, allowing for more flexible and reusable code structures.