I would like to define a function that returns a replaceable record (either MyRecord0, MyRecord1, or MyRecord2) given an input Integer index (0, 1, or 2).
Note that this is only a simple demonstration example case and in practice there may be many more records, each containing additional parameters.
The definition of the example records 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 have been able to successfully return the appropriate record from a function using the getRecord function shown below, but I need to explicitly declare an object for each record type within 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 alternate syntax that eliminates the need to declare instances of each possible record type within the function? For example, I have tried variations shown below but cannot find a satisfactory method that properly compiles.
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 tips or suggestions are appreciated!
Assuming the example is that simple you could do:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With