You are viewing lukego

Luke's Weblog - Forth school [entries|archive|friends|userinfo]
Luke Gorrie

[ website | My Website ]
[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

Forth school [May. 22nd, 2009|07:32 am]
Previous Entry Add to Memories Share Next Entry
[Tags|, ]

I went to Forth school with Mitch Bradley yesterday. Here are a few cool new things I learned:
  • many: The word many repeats execution of the current line until a key is pressed.
    ok ." luke rules" cr  many
    luke rules
    luke rules
    luke rules
    
    ok see many
    : many   
       key? 0= if    
          0 >in ! 
       then  
    ; 
    
  • quine: Since we can introspect the input stream it's easy to write a program that prints itself to stdout.
    ok ( this is a quine ) source type
    ( this is a quine ) source type
    
  • patch: The word patch is a simple way to make binary patches to Forth words.
    ok : foo 1 + ;           
    ok see foo
    : foo   
       1 + 
    ; 
    ok 41 foo .
    42 
    
    ok patch - + foo
    ok see foo
    : foo   
       1 - 
    ; 
    ok 43 foo .
    42 
    
    ok patch 5 1 foo
    ok see foo
    : foo   
       5 - 
    ; 
    ok 47 foo .
    42 
    ok 
    
I love Forth.
LinkReply

Comments:
[User Picture]From: funos
2009-05-22 03:16 am (UTC)

(Link)

Nice!
[User Picture]From: darius
2009-05-22 07:13 am (UTC)

(Link)

many is cute. Funny how seeing "1 +" instead of "1+" still makes me twitch after so many years of no Forth.
[User Picture]From: funos
2009-05-22 12:15 pm (UTC)

(Link)

Looking at it a bit more...I don't see how 'many' does the repetition. (but writing to the input buffer to trigger key? is clever)
From: joshua.grams.myvidoop.com
2009-05-28 08:12 pm (UTC)

(Link)

Er...not quite. >IN is a variable which tells where the interpreter is in the current line. It doesn't have anything to do with KEY?, which returns a flag telling whether keyboard input is available. So 0 >IN ! resets the interpreter to the beginning of the line, and KEY? 0= IF ... THEN says "do this if no key has been pressed."
[User Picture]From: funos
2009-05-28 08:29 pm (UTC)

(Link)

Ahh...thanks for the clarification.
It's a nice trick, but then would 'many' be safely usable inside compiled code?
From: joshua.grams.myvidoop.com
2009-05-29 01:18 pm (UTC)

(Link)

No, it's just for use interactively. Maybe as a debugging aid or something? Probably just a cute trick.

Well...you could put it in another definition, but it's not a compiled looping construct, it would just cause that word to behave like many. That is, when it is interpreted it would send the interpreter back to the beginning of the line. And of course it wouldn't have any effect until the word returns, so it wouldn't (usually) matter where in the definition you put it. Here's a lousy example: :-)

: count-up dup . many cr 1+ ;

17 ( need a line-break here; you don't want to do 17 every time )
count-up

18
19
20
... until you press a key

--Josh