what do these mean

Terry Reedy tjreedy at udel.edu
Sun May 20 14:38:25 EDT 2012


On 5/20/2012 1:16 PM, Ian Kelly wrote:
> On Sun, May 20, 2012 at 10:52 AM, e-mail mgbg25171
> <mgbg25171 at blueyonder.co.uk>  wrote:
>> There's a little forth program written in python here
>> #http://openbookproject.net/py4fun/forth/forth.py
>> I'm struggling to understand what these lines mean.
>>
>> def rJnz (cod,p) : return (cod[p],p+1)[ds.pop()]
>> def rJz  (cod,p) : return (p+1,cod[p])[ds.pop()==0]
>
> rJz is the jump-if-zero instruction used by the If and Until
> constructs.  It creates a tuple containing the next instruction and
> the instruction to jump to.  Which element of the tuple to return is
> determined by the expression "ds.pop()==0", which is True (i.e. 1) if
> the top of the stack is 0, or False (i.e. 0) if it is not.
>
> rJnz appears to be a complementary jump-if-nonzero instruction that is
> never actually used by the program and appears to be buggy in any
> case.  It has the order of the tuple backwards, and the "ds.pop()"
> expression makes the false assumption that the item at the top of the
> stack is already 0 or 1 and not something else.

Would not the order be correct if 'ds.pop()' became 'ds.pop == 0'?
Admittedly, (p+1,cod[p])[ds.pop()!=0] would more clearly be jump if not 
0. If course, this just goes to show what code should be unit-tested. It 
is so easy to mis-type and not notice even when the code in ones head is 
correct and even pretty trivial.

-- 
Terry Jan Reedy




More information about the Python-list mailing list