Update
[less_retarded_wiki.git] / forth.md
blob49e381f3f908ea7c0f90e19e29b99dfcb5c5cdd5
1 # Forth
3 { I'm a bit ashamed but I'm not really "fluent" at Forth, I just played around with it for a bit. Yes, I'm planning to get into it more after I do the other million things on my TODO list. Let me know if there is some BS, thank u <3 ~drummyfish }
5 Forth ("fourth generation" shortened to four characters due to technical limitations) is a very good, extremely [minimal](minimalism.md) [stack](stack.md)-based untyped [programming language](programming_language.md) that uses [postfix](notation.md) (reverse Polish) notation. Its vanilla form is super simple, it's miles simpler than [C](c.md), it's very [elegant](elegant.md) and its compiler/interpreter can be made very easily, giving it high practical freedom (i.e. not being practically controlled by any central organization). As of writing this the smallest Forth implementation, [milliforth](milliforth.md), has just **340 bytes** (!!!) of [machine code](machine_code.md), that's just incredible. Forth is used e.g. in [space](space.md) technology (e.g. [RTX2010](rtx2010.md), a radiation hardened space computer directly executing Forth) and [embedded](embedded.md) systems as a way to write efficient [low level](low_level.md) programs that are, unlike those written in [assembly](assembly.md), [portable](portability.md) (fun fact: there even exist computers directly running Forth in hardware). Forth was the main influence for [Comun](comun.md), the [LRS](lrs.md) programming language, it is also used by [Collapse OS](collapseos.md) and [Dusk OS](duskos.md) as the main language. In its minimalism Forth competes a bit with [Lisp](lisp.md).
7 { There used to be a nice Forth wiki at wiki.forthfreak.net, now it has to be accessed via archive as it's dead. ~drummyfish }
9 { There is also some discussion about how low level Forth really is, if it really is a language or something like a "metalanguage", or an "environment" to create your own language by defining your own words. Now this is not a place to go very deep on this but kind of a sum up may be this: Forth in its base version is very low level, however it's very extensible and many extend it to some kind of much higher level language, hence the debates. ~drummyfish }
11 It is usually presented as [interpreted](interpreter.md) language but may as well be [compiled](compiler.md), in fact it maps pretty nicely to [assembly](assembly.md). Even if interpreted, it can still be very fast. Forth systems traditionally include not just a compiler/interpreter but also an **interactive environment**, kind of [REPL](repl.md) language shell.
13 There are several Forth standards, most notably ANSI Forth from 1994 (the document is [proprietary](proprietary.md), sharing is allowed, 640 kB as txt). Besides others it also allows Forth to include optional [floating point](float.md) support.
15 A [free](free_software.md) implementation is e.g. GNU Forth ([gforth](gforth.md)) or [pforth](pforth.md) (a possibly better option by LRS standards, favors [portability](portability.md) over performance).
17 Forth was invented by Charles Moore in 1968, for programming radio telescopes.
19 ## Language
21 Forth is case-insensitive (this may however not be the case in some implementations).
23 The language operates on an evaluation **[stack](stack.md)**: e.g. the operation + takes the two values at the top of the stack, adds them together and pushed the result back on the stack. Besides this there are also some "advanced" features like variables living outside the stack, if you want to use them.
25 The stack is composed of **cells**: the size and internal representation of the cell is implementation defined. There are no data types, or rather everything is just of type signed int.
27 Basic abstraction of Forth is so called **word**: a word is simply a string without spaces like `abc` or `1mm#3`. A word represents some operation on stack (and possible other effect such as printing to the console), for example the word `1` adds the number 1 on top of the stack, the word `+` performs the addition on top of the stack etc. The programmer can define his own words which can be seen as "[functions](function.md)" or rather procedures or macros (words don't return anything or take any arguments, they all just invoke some operations on the stack). A word is defined like this:
29 ```
30 : myword operation1 operation2 ... ;
31 ```
33 For example a word that computes and average of the two values on top of the stack can be defined as:
35 ```
36 : average + 2 / ;
37 ```
39 Built-in words include:
41 ```
42 GENERAL:
44 +           add                 a b -> (a + b)
45 -           subtract            a b -> (b - a)
46 *           multiply            a b -> (a * b)
47 /           divide              a b -> (b / a)
48 =           equals              a b -> (-1 if a = b else 0)
49 <           less than           a b -> (-1 if a < b else 0)
50 >           greater than        a b -> (-1 if a > b else 0)
51 mod         modulo              a b -> (b % a)
52 dup         duplicate             a -> a a
53 drop        pop stack top         a ->
54 swap        swap items          a b -> b a
55 rot         rotate 3          a b c -> b c a
56 .           print top & pop
57 key         read char on top
58 .s          print stack
59 emit        print char & pop
60 cr          print newline
61 cells       times cell width      a -> (a * cell width in bytes)
62 depth       pop all & get d.  a ... -> (previous stack size)
63 bye         quit
65 VARIABLES/CONSTS:
67 variable X      creates var named X (X is a word that pushed its addr)
68 N X !           stores value N to variable X
69 N X +!          adds value N to variable X
70 X @             pushes value of variable X to stack
71 N constant C    creates constant C with value N
72 C               pushes the value of constant C
74 SPECIAL:
76 ( )                   comment (inline)
77 \                     comment (until newline)
78 ." S "                print string S
79 X if C then           if X, execute C // only in word def.
80 X if C1 else C2 then  if X, execute C1 else C2 // only in word def.
81 do C loop             loops from stack top value to stack second from,
82                       top, special word "i" will hold the iteration val.
83 begin C until         like do/loop but keeps looping as long as top = 0
84 begin C while         like begin/until but loops as long as top != 0
85 allot                 allocates memory, can be used for arrays
86 recurse               recursively call the word currently being defined
88 ```
90 example programs:
92 ```
93 100 1 2 + 7 * / . \ computes and prints 100 / ((1 + 2) * 7)
94 ```
96 ```
97 cr ." hey bitch " cr \ prints: hey bitch
98 ```
101 : myloop 5 0 do i . loop ; myloop \ prints 0 1 2 3 4
104 ## How To
106 Source code files usually have `.fs` extension. We can use mentioned gforth to run our files. Let's create file `my.fs`; in it we write: { Hope the code is OK, I never actually programmed in Forth before. ~drummyfish }
109 : factorial
110   dup 1 > if
111     dup 1 - recurse *
112   else
113     drop 1
114   then
117 5 factorial .
122 We can run this simply with `gforth my.fs`, the programs should write `120`.
124 ## See Also
126 - [Lisp](lisp.md)
127 - [comun](comun.md)
128 - [Tcl](tcl.md)