Blog (or) Scribble Pad

With Forth - 1



I've started learning the Forth programming language. If you are about to learn Forth, then pay attention when they say "It's a stack based programming language". At first, I thought this as some sort of technical shit boasting out the implementation of Forth or something as I'm a low life programmer. But after fiddling with it for a while (thanks to the "Implicit Data Passing" section of Thinking Forth by Leo Brodie) I finally understood what stack based programming is and now I've written my first working program in Forth which I was trying for the past few hours: a function to sum two numbers.

: ADD + ;
5 10 ADD CR .

Now, this stack based programming is exciting (I'm yet to know thier pros and cons). Here, in the above two lines of code, I'm assigning the '+' operator to the word 'ADD'. Then in the next line I'm adding the numbers 5 and 10 then printing them on the screen as the word 'ADD' means '+'. The second line of code is  equivalent to

5 10 + CR .

where 'CR' is carriage return and '.' is used to print the output value to screen. So, don't worry about 'CR' and '.'.

What I understood from the above: 5 is first stored (pushed) in to the stack and  then 10 is stored (pushed) above 5. With Last In First Out LIFO 'ADD' which  translates to '+' adds the last two values (by popping them out) of the stack and  puts (pushes) the output on the top of the stack. So, here we would be having 15  at the top of the stack which is printed out to us by '.' operator.

Now, I wanted to show how this program works to my friends by summing a pair of integers. But, it was painfull (& not so cool) to type 'CR .' at the  end of each function call to print the output of the function 'ADD' each time. Then  the below lines from Thinking Forth, by Leo Brodie, flashed into my brain (which won't happen very often),

The smallest atom of a Forth program is not a module or a subroutine or a  procedure, but a “word.”

and

Everything in Forth is a word.

So, here '+' should be a word, 'CR' should be a word and '.' should be a word too. And in Forth we can group together any number of words and assign it to a word.

: ADD + CR . ;
5 10 ADD

This is not only cool, but seems powerful to me. Now, I'm getting excited to  further dive into Forth.

Also, some of my friends argued that the below piece of code won't qualify for a function to which I wrote the below code, a function to sum four numbers.

: 4add + + +  cr . ;
9 8 1 2 4add

Which outputs 10