14.2 Stack instructions. 4tH 4tH Forth compiler
বিজ্ঞাপন
বিজ্ঞাপন
CHAPTER 14. PREPROCESSOR LIBRARIES
%.c : %.4th
4th cgq $< $@
%.c : %.hx
4th lgq $< $@
%.4th : %.4pp
pp4th -o $@ $<
241
Refer to your system documentation for more information. Finally (and this is very important), always include preprocessor libraries after including all other libraries. If you don’t, you risk that your macro’s are expanded while you’re loading 4tH code that wasn’t designed for it - which may have adverse effects. You don’t want to chase bugs that were never there, don’t you?
14.2
Stack instructions
What sets the 4tH preprocessor apart from all other preprocessors is its built-in string stack.
And of course, with a stack comes stack instructions. Some, like @drop, @dup, @nip and
@over are built-in, but some like @swap and @rot are missing. That is exactly what this library file provides. First of all, you have to include it: include 4pp/lib/standard.4pp
Don’t forget to use the .4pp extension or you’ll get an error message, since the preprocessor won’t be able to find the file. After that you’ll have a full range of stack instructions at your disposal to manipulate the string stack. It allows you to do things like this: include 4pp/lib/standard.4pp
:macro _fac >4> >3> @minus @add @sign @if @drop
>3> @mul >3> >>> 1 @add <3< _fac ;
:macro __fac >>> 1 @swap >>> 1 @add >>> 2 @max
<4< >>> 2 <3< _fac ;
:macro factorial >#> __fac @drop <1< #1# ;
." 10! = " factorial 10 . cr
Which is nothing less than calculating the factorial of 10 at compile time! Now let’s break this thing down, how does it work?
• factorial puts ”10” on the stack and calls __fac. After that, it takes the number from the string stack and prints it;
• __fac puts ”1” on the stack, swaps both values and puts ”1” on the stack once more.
Then it adds TOS and 2OS
4
, puts ”3” on the stack and takes the largest value (like
’MAX’). TOS is stored in register 4 and the value ”2” is stored in register 3. Then
_fac is called.
• _fac puts the contents of register 4 and 3 on the stack, negates TOS and adds TOS and 2OS. If the result of this subtraction is not zero, the contents of register 3 are thrown on the stack once more and multiplied. Finally, the contents of register 3 are incremented and a recursive call to _fac is made.
4
”TOS” means: ”top of stack” and 2OS: ”second of stack”. It is a common way to refer to the top two values.
ডাউনলোড
বিজ্ঞাপন