printf fussy about format string

24 views
Skip to first unread message

jfh

unread,
Oct 30, 2018, 5:50:17 PM10/30/18
to
Why is Maple happy with cat but not || in a format string?

|\^/| Maple 2017 (X86 64 LINUX)
._|\| |/|_. Copyright (c) Maplesoft, a division of Waterloo Maple Inc. 2017
\ MAPLE / All rights reserved. Maple is a trademark of
<____ ____> Waterloo Maple Inc.
| Type ? for help.
> with(StringTools):
> z1:=1+I;
z1 := 1 + I

> z2:=1-I;
z2 := 1 - I

> printf(cat(Repeat("%+12.5e*e^(I*%+12.5e) ",2),"\n"),
> abs(z1),argument(z1),abs(z2),argument(z2));
+1.41421e+00*e^(I*+7.85398e-01) +1.41421e+00*e^(I*-7.85398e-01)
> printf(Repeat("%+12.5e*e^(I*%+12.5e) ",2)||"\n",
> abs(z1),argument(z1),abs(z2),argument(z2));
Error, (in fprintf) format string expected
> z2:=1-I;




acer

unread,
Oct 31, 2018, 9:08:26 AM10/31/18
to
The problem is that `||` does not evaluate its first argument, so it concatenates "\n" with the unevaluated function call to `Repeat` rather than with its result.

Since you didn't supply the definition of `Repeat` I'll make one up in order to illustrate the point.

Repeat:=proc(s,n)
local i;
cat(seq(s,i=1..n));
end proc:

lprint( cat(Repeat("%+12.5e*e^(I*%+12.5e) ",2),"\n") );

"%+12.5e*e^(I*%+12.5e) %+12.5e*e^(I*%+12.5e) \n"

lprint( Repeat("%+12.5e*e^(I*%+12.5e) ",2)||"\n" );

Repeat("%+12.5e*e^(I*%+12.5e) ", 2) || "\n"

So in the second case `printf` is not receiving an actual string as its first argument.

As a general rule it's unwise to use `||` instead of `cat` unless one understands its evaluation rules.

Similarly it's unwise to use `$` unless one understands the difference between its evaluation rules and that of `seq`.
Reply all
Reply to author
Forward
0 new messages