• printf fussy about format string

    From jfh@21:1/5 to All on Tue Oct 30 14:50:16 2018
    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;

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From acer@21:1/5 to jfh on Wed Oct 31 06:08:25 2018
    On Tuesday, October 30, 2018 at 5:50:17 PM UTC-4, jfh wrote:
    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;

    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`.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)