Gforth

Implementation of programming language Forth

Gforth is a Forth interpreter included in GNU project. It is written in C and Forth itself. Gforth aims to be ANS Forth-compliant and eventually to become a standard itself.

Examples:

Hello, World!:

Example for versions gforth 0.7.0

Word ." reads a double-quotes-delimited string and outputs it. The space character that separates ." and Hello doesn’t count as part of the string, it’s necessary to recognize ." as a word.

cr outputs a new line character and is an equivalent of nl in Prolog and endl in C++.

." Hello, World!" cr

Factorial:

Example for versions gforth 0.7.0

This example uses recursive factorial definition. Forth is a stack-oriented language, so all commands (words) perform stack manipulations. Thus, dup duplicates the topmost element of the stack, a constant pushes itself on the top of the stack, > compares second-topmost element to the topmost element and pushes the result, - subtracts topmost element from second-topmost, etc.

: fac recursive
  dup 1 > IF
    dup 1 - fac *
  else
    drop 1
  endif ;
 
: lp
  swap 1 + swap
  do
    i . i ." ! = " i fac . cr
  loop ;
 
16 0 lp

Fibonacci numbers:

Example for versions gforth 0.7.0

This example uses iterative definition of Fibonacci numbers.

: fib-iter
  0 1 rot 0 ?do over + swap loop drop ;
 
: lp
  1 do
    i dup fib-iter . ." , "
  loop drop ;
 
17 lp
." ..."

Fibonacci numbers:

Example for versions gforth 0.7.0

This example uses recursive definition of Fibonacci numbers.

: fib-rec
  dup 2 u< if exit then
  1- dup recurse  swap 1- recurse  + ;
 
: lp
  1 do
    i dup fib-rec . ." , "
  loop drop ;
 
17 lp
." ..."