The problem with 4tH

18 views
Skip to first unread message

The Beez

unread,
May 11, 2024, 8:21:44 AMMay 11
to 4tH-compiler
Hi 4tH-ers!

I am producing my next YT video (yeah, it's been some time - be patient) and researching it I found this page: https://prog21.dadgum.com/33.html

The guy was trying to translate this into Forth:

void vadd(int *v1, int *v2, int *v3) 
{
  v3[0] = v1[0] + v2[0];
  v3[1] = v1[1] + v2[1];
  v3[2] = v1[2] + v2[2];
}

And what he came up with finally was this:

: vadd ( v1 v2 v2 -- )
  >r
  over 1st @ over 1st @ + r@ 1st ! 
  over 2nd @ over 2nd @ + r@ 2nd !
  over 3rd @ over 3rd @ + r@ 3rd !
  rdrop drop drop ;

Which is not bad by any measure - but I think he was stuck too much in C, and not quite thinking like a Forther. If so, you're thinking about the result and the stack. Not the way how to get there.

So I wondered - how would I solve it? Well - while I was add it, I was figuring out how to factor it better. And quickly I was developing a "vector" wordset, simplifying the entire program to a bunch of one-liners:

3 array a
3 array b
3 array c

: v! 3 0 do tuck i th ! loop drop ;
: .v 3 0 do dup  i th ? loop drop ;
: vadd >r 3 0 do over i th @ over i th @ + -rot loop drop drop spin r> v! ;

3 2 1 a v!
6 5 4 b v!

a b c vadd c .v

Now, the most obvious next move is to make the size of the vector into a constant. But we've got a solid foundation here. Also note the use of SPIN here. It supports my theory that once you have mastered a certain stack pattern in your head you tend to see it in the appropriate situations and use it.

There's already another: RISE, which does a b c -- b a c - but I haven't caught that one yet (meaning I haven't seen that pattern arise in my programs). I think it's the same for particular Factor patterns once you get the hang of it.

Hans Bezemer

The Beez

unread,
May 11, 2024, 8:29:55 AMMay 11
to 4tH-compiler

Now that I think of it..
: v+ 3 0 do over i th @ over i th @ + -rot loop drop drop spin ; ( 'v1 'v2 -- v3)
: vadd >r v+ r> v! ;
Reply all
Reply to author
Forward
0 new messages