Text Templates in Co-array Fortran

Our first program demonstrates how to create and use text templates in Co-array Fortran. Here’s the full source code:

program text_templates
  use iso_fortran_env
  implicit none

  character(len=100) :: template_string
  character(len=100) :: result
  integer :: i

  ! Create a simple template
  template_string = "Value is {value}"

  ! Use the template with different values
  call apply_template(template_string, "some text", result)
  print *, result

  call apply_template(template_string, "5", result)
  print *, result

  ! Template for struct-like data
  template_string = "Name: {name}"
  call apply_template(template_string, "Jane Doe", result)
  print *, result

  ! Conditional template
  template_string = "{ if value /= '' }yes{ else }no{ end if }"
  call apply_template(template_string, "not empty", result)
  print *, trim(result)

  call apply_template(template_string, "", result)
  print *, trim(result)

  ! Range-like template
  template_string = "Range: {value}"
  call apply_template(template_string, "Go Rust C++ C#", result)
  print *, result

contains

  subroutine apply_template(template, value, result)
    character(len=*), intent(in) :: template, value
    character(len=*), intent(out) :: result
    integer :: i, j, k

    result = template
    i = index(result, "{")
    j = index(result, "}")
    if (i > 0 .and. j > i) then
      result = result(1:i-1) // trim(value) // result(j+1:)
    end if
  end subroutine apply_template

end program text_templates

This program demonstrates basic text template functionality in Co-array Fortran. While Co-array Fortran doesn’t have built-in template support like some other languages, we can implement a simple version of it.

We define a subroutine apply_template that takes a template string and a value, and replaces a placeholder in the template with the value.

The program showcases different use cases:

  1. Simple value insertion
  2. Using the template with different types of values
  3. A struct-like template (although Fortran doesn’t have structs, we simulate it)
  4. A conditional template (note that the actual logic is not implemented in this simple version)
  5. A range-like template (again, without actual iteration logic)

To run the program, save it as text_templates.f90 and compile it using a Fortran compiler that supports Co-array Fortran:

$ gfortran -fcoarray=single text_templates.f90 -o text_templates
$ ./text_templates

The output will be similar to:

Value is some text
Value is 5
Name: Jane Doe
yes
no
Range: Go Rust C++ C#

This example provides a basic framework for text templates in Co-array Fortran. For more complex use cases, you would need to implement more sophisticated parsing and evaluation logic.