0
$\begingroup$

Let's say I have some expression like,

expr = 1*a + 2*b +3*c + 4*d

I want to write this to a string that I can then use in some other Fortran script. I want all the integers to be of the form "X.0_dp". To do this I can simply do,

StringReplace[
  ToString[expr, FortranForm], {"1" -> "2.0_dp", "2" -> "2.0_dp", 
  "3" -> "3.0_dp", "4" -> "4.0_dp"}]

which works a treat.

Now, is there a way such that I don't have to do this by hand, and generalizes to all integers? e.g. something of the form,

StringReplace[
  ToString[expr, FortranForm], {"x" -> "x.0_dp"}]

Thanks for any help

$\endgroup$
4
  • 1
    $\begingroup$ Does StringReplace[ToString[expr, FortranForm], x : NumberString :> If[StringFreeQ[x, "."], x <> ".0_dp", x <> "0_dp"]] suit your needs? $\endgroup$ Mar 5, 2019 at 10:07
  • $\begingroup$ Yes that works perfectly! If you submit as an answer I can then mark as accepted :) Further:is there a way to do this for decimals e.g. 0.5 ---> 0.50_dp ? $\endgroup$ Mar 5, 2019 at 10:11
  • $\begingroup$ Did you try the snippet I gave in that case? $\endgroup$ Mar 5, 2019 at 10:17
  • $\begingroup$ Ah my bad - all works. Thanks! :) $\endgroup$ Mar 5, 2019 at 10:20

2 Answers 2

3
$\begingroup$

If you want all integers to be formatted in the same way, you can override the FortranForm formatting of Integer:

Unprotect[Integer];
Format[i_Integer, FortranForm] := Format[
    ToString @ i <> ".0_dp",
    OutputForm
]
Protect[Integer];

Then:

ToString[1*a + 2*b +3*c + 4*d, FortranForm]
"a + 2.0_dp*b + 3.0_dp*c + 4.0_dp*d"

If you want to retain the 1 before the a, just use HoldForm to prevent evaluation:

ToString[HoldForm[1*a + 2*b +3*c + 4*d], FortranForm]
"1.0_dp*a + 2.0_dp*b + 3.0_dp*c + 4.0_dp*d"
$\endgroup$
0
$\begingroup$

Try this:

ToString[(expr /. 
    Times[x_Integer, y_Symbol] :> 
     ToString[x, FortranForm] <> ".0_dp " <> 
      ToString[y, FortranForm]) /. a :> "1.0_dp a"]

(* "1.0_dp a + 2.0_dp b + 3.0_dp c + 4.0_dp d"  *)

Have fun!

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.