Search code examples
fortranwolfram-mathematicasplice

How do I use FileTemplate as a substitute for Splice to export Mathematica expressions into Fortran?


I found the Splice functionality in Mathematica quite useful in the past. I am trying to insert mathematica expressions, formatted for Fortran, into Fotran code.

Does anyone have a small working example they would be willing to share? Thanks.

I could write Mathematica code

y=x^3

and construct a file test.fm with

      program test
      real x,y
      x=1.0
      y=
     -  <* y *>
      write(6,*) "y",y
      end

and the mathematica line Splice["test.fm"] would give a file test.f with

      program test 
      real x,y
      x=1.0
      y=
     - x**3
      write(6,*) "y",y
      end

Apparently this use of Splice is removed in recent Mathematica releases, and I get an error message

  The function Splice with filename inputs is now obsolete and has been
    superseded by FileTemplate.

I tried

FileTemplate["test.mf"]

but it returns something that apparently needs further output. I then tried

TemplateApply[FileTemplate["my.fm"]]

but this didn't work either.


Solution

  • FileTemplate yields a TemplateObject expression that you need to apply. Here is an example application using your code and StringTemplate, which similarly yields a TemplateObject expression.

    Clear[x]
    y = x^3
    StringTemplate["      program test
          real x,y
          x=1.0
          y=
         -  <* y *>
          write(6,*) \"y\",y
          end", InsertionFunction -> ToString@*FortranForm][<|"y" -> y|>]