Search code examples
metapost

Strange Metapost parenthesis bug


When I compile the following Metapost file:

beginfig(1);
def f(expr n) =
  if n=0: 0
  else: 1
  fi;
enddef;
show f(0)+1;
endfig;
end

I expect to get the output 1 (since f(0) is equal to 0, f(0)+1 should be 1!). However, Metapost complains about an Isolated expression.

When I put the expression in parentheses: show (f(0)+1), things get even stranger. The error message becomes : Missing ')' has been inserted. (The first quote should be a backquote, but I couldn't figure out how to escape it). Where on earth was there a mismatched parenthesis??

Thanks for your help!


Solution

  • The def command just expands a name into its definition, so you get literally:

    show if 0=0: 0 else: 1;+1;
    

    The semicolon in the middle is what's wrong, so let us remove it:

    beginfig(1);
    def f(expr n) =
      if n=0: 0
      else: 1
      fi
    enddef;
    show f(0)+1;
    endfig;
    end
    

    This produces the correct expansion:

    show if 0=0: 0 else: 1+1;
    

    And outputs 1 as expected.


    On a side note, I'd recommend using begingroup...endgroup for heavier macro definitions, and at least parentheses for lighter ones: for example,

    def f = 1 + 2 enddef;
    show f * 2;
    

    gives 1 + 2 * 2, which is not the same as what is probably expected:

    def f = (1 + 2) enddef;
    show f * 2;
    

    which gives (1 + 2) * 2.