Search code examples
forth

Rewriting a**2 + ab + c in FORTH


Chapter 2 Problem 4 of Starting FORTH (online here) asks you to write a definition for

a**2 + ab + c  ( c a b -- result )

The answer key says

: 2-4 OVER + * + ;

How is that the case, let's assume a=1, b=2, c=3

3 1 2  ok
OVER .s <4> 3 1 2 1  ok
+ .s <3> 3 1 3  ok
* .s <2> 3 3  ok
+ .s <1> 6  ok


Solution

  • This works because as mentioned in the comments, I was being math-stupid.

    I was seeing

    OVER .s <4> 3 1 2 1  ok
    + .s <3> 3 1 3  ok
    

    And being thrown for a loop. The problem is

    a**2 + ab + c  ( c a b -- result )
    

    is the same as

    a(a+b) + c  ( c a b -- result )
    

    which is the same as

    c + a(a+b)  ( c a b -- result )
    

    Which is essentially what they're doing. They move the forms around a bit

    c + a(a+b)
    c + a(b+a)
    

    You see that in the stack, which gets rearranged to this...

    c a b
    c a b a  -- after over
    

    Then they just run

    c a b a + * +
    

    Clever, thanks to Mateusz Piotrowski for pointing it out in the comments.