Text Templates in Scilab

Our first program will demonstrate the use of string formatting in Scilab. Scilab doesn’t have a built-in templating system like Go’s text/template, but we can achieve similar results using string formatting and concatenation.

function result = executeTemplate(template, value)
    result = msprintf(template, value);
endfunction

function main()
    // We can create a simple template using printf-style formatting
    t1 = "Value is %s\n";
    
    // Execute the template with different values
    mprintf(executeTemplate(t1, "some text"));
    mprintf(executeTemplate(t1, string(5)));
    mprintf(executeTemplate(t1, strcat(["Go", "Rust", "C++", "C#"], " ")));
    
    // For structs, we can access fields by name
    person = struct("Name", "Jane Doe");
    t2 = "Name: %s\n";
    mprintf(executeTemplate(t2, person.Name));
    
    // For maps (represented as structs in Scilab), we can do the same
    person_map = struct("Name", "Mickey Mouse");
    mprintf(executeTemplate(t2, person_map.Name));
    
    // Conditional execution can be done with if-else statements
    function result = conditionalTemplate(value)
        if value ~= "" then
            result = "yes\n";
        else
            result = "no\n";
        end
    endfunction
    
    mprintf(conditionalTemplate("not empty"));
    mprintf(conditionalTemplate(""));
    
    // Looping through arrays
    function result = rangeTemplate(arr)
        result = "Range: " + strcat(arr, " ") + "\n";
    endfunction
    
    languages = ["Go", "Rust", "C++", "C#"];
    mprintf(rangeTemplate(languages));
end

main();

To run the program, save it as templates.sce and execute it in Scilab:

--> exec('templates.sce', -1)
Value is some text
Value is 5
Value is Go Rust C++ C#
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: Go Rust C++ C# 

In this Scilab example, we’ve replicated the functionality of Go’s text templates using string formatting and custom functions. Here’s a breakdown of the main differences:

  1. Scilab doesn’t have a built-in templating system, so we use msprintf for string formatting.
  2. We create custom functions to mimic template behavior.
  3. Structs in Scilab are used to represent both structs and maps from the Go example.
  4. Conditional execution is handled with regular if-else statements inside a function.
  5. Looping through arrays is done using Scilab’s string concatenation function strcat.

While not as powerful as Go’s template system, this approach allows for basic templating functionality in Scilab.