Switch in Modelica

Here’s a basic switch.

model SwitchExample
  Integer i = 2;
  
  function printString
    input String str;
  algorithm 
    Modelica.Utilities.Streams.print(str);
  end printString;

  // Time simulation
  parameter Integer h = 15 "hour of day";
  parameter Integer w = 3 "weekday as integer"; // e.g., 1=Monday, 7=Sunday
algorithm 
  // Integer switch example
  printString("Write " + String(i) + " as ");
  if i == 1 then
    printString("one");
  elseif i == 2 then
    printString("two");
  elseif i == 3 then
    printString("three");
  end if;
  
  // Weekday switch example
  if w == 6 or w == 7 then
    printString("It's the weekend");
  else
    printString("It's a weekday");
  end if;
  
  // Hour-of-day switch example
  if h < 12 then
    printString("It's before noon");
  else
    printString("It's after noon");
  end if;
  
  // Type switch example
  function whatAmI
    input Real value;
    input String t; // 'bool' or 'int' simulation
  algorithm
    if t == "bool" then
      printString("I'm a bool");
    elseif t == "int" then
      printString("I'm an int");
    else
      printString("Don't know type " + t);
    end if;
  end whatAmI;
  whatAmI(1.0, "bool");
  whatAmI(1.0, "int");
  whatAmI(1.0, "string");
end SwitchExample;

To run the example, simulate the Modelica model.

$ openmodelica --sim=SwitchExample.mo

When you run this example, you should see output similar to:

Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string

Next example: Arrays.