Reputation: 755
In Java it's possible to do the following:
int var = 5;
var += 2;
var -= 2;
var *= 2;
var /= 2;
Is it possible to do this in Forth?
variable var
3 var !
1 var +! //Increment
Is it possible to do the other operations like that in Forth? If not, any hints on how to?
Upvotes: 1
Views: 245
Reputation: 953
There is a fundamental reason why this can't be done in Forth. Let's have
int var, var1 ;
and Jave code :
'var = var1 ;
Apart from the matter that Forth wants the tokens separated by spaces, Forth wants a word always do the same, independant of context. In the Java code var is a left side and that means it must represent an address, where something is stored. On the right hand side var1 also represents an address. But Java magically fetches the content of the address! In Forth we don't deal in magic. We can't have it that var is now doing this and then doing that. The examples that you give are doable as long as you stay clear from the magic parts, as is explained in other answers.
[And of course Forth can also do magic. You could make an =-word that inspects whether the following word var is of type int and then fetches it. But that is not Forth, that is a Forth-implementation of Java.]
Upvotes: 0
Reputation: 14315
Except for decrementing with -2 var +!
, those other operations are not built in.
You can do this:
: -! ( x addr -- ) swap negate swap +! ;
: *! ( x addr -- ) tuck @ * swap ! ;
: /! ( n addr -- ) tuck @ / swap ! ;
Upvotes: 3