Function to return a replaced record in Modelica

I would like to define a function that returns a pluggable record (either MyRecord0, MyRecord1, or MyRecord2) given the Integer index of the input (0, 1, or 2).

Note that this is just a simple demo example and in practice there can be many entries, each containing additional parameters.

The definition of the example entries is shown below:

  record MyRecord0
    parameter Integer myIndex = 0;
    parameter Real myValue = 0;
  end MyRecord0;

  record MyRecord1
    extends MyRecord0(
      myIndex = 1,
      myValue = 1);
  end MyRecord1;

  record MyRecord2
    extends MyRecord0(
      myIndex = 2,
      myValue = 2);
  end MyRecord2;

      

I was able to successfully return the corresponding record from the function using the getRecord function shown below, but I need to explicitly declare an object for each record type inside the function.

function getRecord
  input Integer index "record index";
  replaceable output MyRecord0 myRecord;

  // Explicit declaration of instances for each possible record type
  MyRecord0 record0;
  MyRecord1 record1;
  MyRecord2 record2;

algorithm 
  if index == 1 then
    myRecord := record1;
  else
    if index == 2 then
      myRecord := record2;
    else
      myRecord := record0;
    end if;
  end if;   
end getRecord;

      

Can anyone suggest an alternative syntax that removes the need to declare instances of every possible record type within a function? For example, I have tried the options shown below, but cannot find a satisfactory method that compiles correctly.

function getRecord_Generic
  input Integer index "record index";
  replaceable output MyRecord0 myRecord;

  redeclare MyRecord1 myRecord if index == 1; else (redeclare MyRecord2 myRecord if index == 2 else redeclare MyRecord0 myRecord);
end getRecord_Generic;

      

or

function getRecord_Generic2
  input Integer index "record index";
  replaceable output MyRecord0 myRecord;

algorithm 
  if index == 1 then
    redeclare MyRecord1 myRecord;
  else
    if index ==2 then
      redeclare MyRecord2 myRecord;
    else
      // default case
      redecalre MyRecord0 myRecord;
    end if;
  end if;      
end getRecord_Generic2;

      

Any advice or suggestions are greatly appreciated!

+3


source to share


1 answer


Assuming this simple example can be done:

  function getRecord2
  input Integer index "record index";
  output MyRecord0 myRecord;

  algorithm 
    if index==1 then
      myRecord := MyRecord1();
  else
    if index == 2 then
      myRecord := MyRecord2();
    else
      myRecord := MyRecord0();
    end if;
  end if;   
end getRecord2;

      



(Only tested with Dymola.)

If some of the different records contain additional fields, there is no good solution.

+2


source







All Articles