4

In section 4 of Starting Forth tutorial, the answer to the 5th question is:

: STAR   [CHAR] * EMIT ;
: STARS  ( #stars -- )  0 ?DO  STAR  LOOP ;
: STARS  ( n -- )  ?DUP IF  STARS  THEN ;

The third definition redefines STARS word using previous definition.

Interpreter says:

redefined STARS   ok

and as I type see:

SEE STARS
: STARS  
  ?dup 
  IF     STARS 
  THEN ; ok

Why the former definition is still alive as the word STARS has been replaced in the words dictionary? And is it possible to access/see the former definition?

2 Answers 2

4

The second definition of STARS hasn't replaced the first definition. It has hidden it. The second definition calls the first definition.

words 
STARS STARS STAR mov-regv-Iv mov-reg8-Ib xchg-ax jcc-short conditions...
\ Stars appears twice in the words listing

The forth interpreter searches for the latest definition of a word in the dictionary. In this case once it finds STARS it stops looking any further.

: STAR   [CHAR] * EMIT ;
: (STARS)  ( #stars -- )  0 ?DO  STAR  LOOP ;
: STARS  ( n -- )  ?DUP IF  (STARS)  THEN ;
see stars 
: STARS  
  ?dup 
  IF     (STARS) 
  THEN ; ok
see (stars) 
: (STARS)  
  0 
  ?DO    STAR 
  LOOP
  ; ok
words 
STARS (STARS) STAR mov-regv-Iv mov-reg8-Ib ...

By naming the first STARS as something else, here (STARS), the first definition can still be accessed.

This hiding can be useful with tables of constant data. I think in 'Starting Forth' there's an example of a sine lookup table. The table is called sine and the word to access the table is also called sine. This means nobody can accidentally write into the sine table after the second sine is defined.

Sign up to request clarification or add additional context in comments.

Comments

3

is it possible to access/see the former definition?

Yes, it is possible to access a shadowed definition using the word traverse-wordlist.

See also the word find-name-nth-in defined in How can I access a shadowed definition in Forth?

In Gforth, the word xt-see ( xt -- ) can be used to decompile a definition represented by xt (see the manual).

An example:

"STARS" 1 get-current find-name-nth-in ( nt|0 )
\ NB: it matches a word name case-sensitively
name>interpret xt-see
\ NB: this will fail if a word is not found

Concerning your answer to the question from the book.

If the statement "it always prints at least one star" and provided test case are correct (as the item 5 says), the initial version should be defined as:

: stars ( n -- )  1 max  0 do star loop ;

And your two definitions for stars are two independent solutions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.