Search code examples
forthgforth

Implementing exponentiation in Forth


I'm using Gforth to try to implement exponentiation. I understand, in theory, how a stack-based language is supposed to operate. However, I'm having difficulties with my implementation of it on Gforth.

Here's what I have right now:

: myexp
    1 swap ?do rot dup * rot rot loop ;

However, when I run it I see a stack underflow like:

3 2 myexp
:1: Stack underflow
3 2 >>>myexp<<<
Backtrace:
$7F645EFD6EF0 rot
$2
$1

Is Gforth's looping structure manipulating the stack when it loops?

I'm in the dark on how Forth works as most looping examples I've seen online are rather involved and confusing to someone new to Forth.

What is wrong with my implementation?


Solution

    • The 1 swap is wrong. ?do wants the lower bound at the top of the stack.
    • The loop body is wrong. The two bounds are removed from the data stack, so your use of rot to access the exponentiation base doesn't work.
    : myexp ( u1 u2 -- u3 ) \ u3 = u1^u2
       over swap 1 ?do over * loop nip ;