Question

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?

Was it helpful?

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 ;

OTHER TIPS

I'm not sure how to use Gforth's floating point stack, so I can't give you the answer, but instead of using a loop, you can use the Pascal programming trick of defining exponentiation like so:

x^y = exp(y*ln(x))

Note...for more information, see this answer from the question on Exponentiation of real numbers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top