Forth
- Appeared in:
- 1970s
- Influenced by:
- Influenced:
- Paradigm:
- Typing discipline:
- File extensions:
- .fs
- Versions and implementations (Collapse all | Expand all):
Forth (“fourth” shortened to 5 characters) is an old stack-oriented programming language.
Elements of syntax:
Inline comments | / |
---|---|
Non-nestable comments | ( ... ) |
Case-sensitivity | no (depends on implementation) |
Comparison | < > |
Function definition | : f ... ; |
Function call | f |
Function call with no parameters | f |
If - then | if ... endif |
If - then - else | if ... else ... endif |
Links:
Examples:
Hello, World!:
Example for versions gforth 0.7.0Word ."
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.0This 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.0This 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.0This 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
." ..."
Comments
]]>blog comments powered by Disqus
]]>