]> gitweb.factorcode.org Git - factor.git/blob - basis/help/cookbook/cookbook.factor
Fix permission bits
[factor.git] / basis / help / cookbook / cookbook.factor
1 USING: help.markup help.syntax io kernel math namespaces parser
2 prettyprint sequences vocabs.loader namespaces stack-checker ;
3 IN: help.cookbook
4
5 ARTICLE: "cookbook-syntax" "Basic syntax cookbook"
6 "The following is a simple snippet of Factor code:"
7 { $example "10 sq 5 - ." "95" }
8 "You can click on it to evaluate it in the listener, and it will print the same output value as indicated above."
9 $nl
10 "Factor has a very simple syntax. Your program consists of " { $emphasis "words" } " and " { $emphasis "literals" } ". In the above snippet, the words are " { $link sq } ", " { $link - } " and " { $link . } ". The two integers 10 and 5 are literals."
11 $nl
12 "Factor evaluates code left to right, and stores intermediate values on a " { $emphasis "stack" } ". If you think of the stack as a pile of papers, then " { $emphasis "pushing" } " a value on the stack corresponds to placing a piece of paper at the top of the pile, while " { $emphasis "popping" } " a value corresponds to removing the topmost piece."
13 $nl
14 "All words except those which only push literals on the stack must have a " { $emphasis "stack effect declaration" } ", for example " { $snippet "( x y -- z )" } " denotes that a word takes two inputs, with " { $snippet "y" } " at the top of the stack, and returns one output. Stack effect declarations can be viewed by browsing source code, or using tools such as " { $link see } "; they are also checked by the compiler. See " { $link "effect-declaration" } "."
15 $nl
16 "Coming back to the example in the beginning of this article, the following series of steps occurs as the code is evaluated:"
17 { $table
18     { "Action" "Stack contents" }
19     { "10 is pushed on the stack." { $snippet "10" } }
20     { { "The " { $link sq } " word is executed. It pops one input from the stack - the integer 10 - and squares it, pushing the result." } { $snippet "100" } }
21     { { "5 is pushed on the stack." } { $snippet "100 5" } }
22     { { "The " { $link - } " word is executed. It pops two inputs from the stack - the integers 100 and 5 - and subtracts 5 from 100, pushing the result." } { $snippet "95" } }
23     { { "The " { $link . } " word is executed. It pops one input from the stack - the integer 95 - and prints it in the listener's output area." } { } }
24 }
25 "Factor supports many other data types:"
26 { $code
27     "10.5"
28     "\"character strings\""
29     "{ 1 2 3 }"
30     "! by the way, this is a comment"
31     "#! and so is this"
32 }
33 { $references
34     { "Factor's syntax can be extended, the parser can be called reflectively, and the " { $link . } " word is in fact a general facility for turning almost any object into a form which can be parsed back in again. If this interests you, consult the following sections:" }
35     "syntax"
36     "parser"
37     "prettyprint"
38 } ;
39
40 ARTICLE: "cookbook-colon-defs" "Shuffle word and definition cookbook"
41 "The " { $link dup } " word makes a copy of the value at the top of the stack:"
42 { $example "5 dup * ." "25" }
43 "The " { $link sq } " word is actually defined as follows:"
44 { $code ": sq ( x -- y ) dup * ;" }
45 "(You could have looked this up yourself by clicking on the " { $link sq } " word itself.)"
46 $nl
47 "Note the key elements in a word definition: The colon " { $link POSTPONE: : } " denotes the start of a word definition. The name of the new word must immediately follow. The word definition then continues on until the " { $link POSTPONE: ; } " token signifies the end of the definition. This type of word definition is called a " { $emphasis "compound definition." }
48 $nl
49 "Factor is all about code reuse through short and logical colon definitions. Breaking up a problem into small pieces which are easy to test is called " { $emphasis "factoring." }
50 $nl
51 "Another example of a colon definition:"
52 { $code ": neg ( x -- -x ) 0 swap - ;" }
53 "Here the " { $link swap } " shuffle word is used to interchange the top two stack elements. Note the difference that " { $link swap } " makes in the following two snippets:"
54 { $code
55     "5 0 -       ! Computes 5-0"
56     "5 0 swap -  ! Computes 0-5"
57 }
58 "Also, in the above example a stack effect declaration is written between " { $snippet "(" } " and " { $snippet ")" } " with a mnemonic description of what the word does to the stack. See " { $link "effect-declaration" } " for details."
59 { $curious
60     "This syntax will be familiar to anybody who has used Forth before. However the behavior is slightly different. In most Forth systems, the below code prints 2, because the definition of " { $snippet "b" } " still refers to the previous definition of " { $snippet "a" } ":"
61     { $code
62         ": a 1 ;"
63         ": b ( -- x ) a 1 + ;"
64         ": a 2 ;"
65         "b ."
66     }
67     "In Factor, this example will print 3 since word redefinition is explicitly supported."
68     $nl
69     "Indeed, redefining a word twice in the same source file is an error; this is almost always a mistake since there's no way to call the first definition. See " { $link "definition-checking" } "."
70 }
71 { $references
72     { "A whole slew of shuffle words can be used to rearrange the stack. There are forms of word definition other than colon definition, words can be defined entirely at runtime, and word definitions can be " { $emphasis "annotated" } " with tracing calls and breakpoints without modifying the source code." }
73     "shuffle-words"
74     "words"
75     "generic"
76     "tools"
77 } ;
78
79 ARTICLE: "cookbook-combinators" "Control flow cookbook"
80 "A " { $emphasis "quotation" } " is an object containing code which can be evaluated."
81 { $code
82     "2 2 + .     ! Prints 4"
83     "[ 2 2 + . ] ! Pushes a quotation"
84 }
85 "The quotation pushed by the second example will print 4 when called by " { $link call } "."
86 $nl
87 "Quotations are used to implement control flow. For example, conditional execution is done with " { $link if } ":"
88 { $code
89     ": sign-test ( n -- )"
90     "    dup 0 < ["
91     "        drop \"negative\""
92     "    ] ["
93     "        zero? [ \"zero\" ] [ \"positive\" ] if"
94     "    ] if print ;"
95 }
96 "The " { $link if } " word takes a boolean, a true quotation, and a false quotation, and executes one of the two quotations depending on the value of the boolean. In Factor, any object not equal to the special value " { $link f } " is considered true, while " { $link f } " is false."
97 $nl
98 "Another useful form of control flow is iteration. You can do something several times:"
99 { $code "10 [ \"Factor rocks!\" print ] times" }
100 "Now we can look at a new data type, the array:"
101 { $code "{ 1 2 3 }" }
102 "An array looks like a quotation except it cannot be evaluated; it simply stores data."
103 $nl
104 "You can perform an operation on each element of an array:"
105 { $example
106     "{ 1 2 3 } [ \"The number is \" write . ] each"
107     "The number is 1"
108     "The number is 2"
109     "The number is 3"
110 }
111 "You can transform each element, collecting the results in a new array:"
112 { $example "{ 5 12 0 -12 -5 } [ sq ] map ." "{ 25 144 0 144 25 }" }
113 "You can create a new array, only containing elements which satisfy some condition:"
114 { $example
115     ": negative? ( n -- ? ) 0 < ;"
116     "{ -12 10 16 0 -1 -3 -9 } [ negative? ] filter ."
117     "{ -12 -1 -3 -9 }"
118 }
119 { $references
120     { "Since quotations are objects, they can be constructed and taken apart at will. You can write code that writes code. Arrays are just one of the various types of sequences, and the sequence operations such as " { $link each } " and " { $link map } " operate on all types of sequences. There are many more sequence iteration operations than the ones above, too." }
121     "dataflow"
122     "sequences"
123 } ;
124
125 ARTICLE: "cookbook-variables" "Variables cookbook"
126 "Before using a variable, you must define a symbol for it:"
127 { $code "SYMBOL: name" }
128 "A symbol is a word which pushes itself on the stack when executed. Try it:"
129 { $example "SYMBOL: foo" "foo ." "foo" }
130 "Symbols can be passed to the " { $link get } " and " { $link set } " words to read and write variable values:"
131 { $example "\"Slava\" name set" "name get print" "Slava" }
132 "If you set variables inside a " { $link with-scope } ", their values will be lost after leaving the scope:"
133 { $example
134     ": print-name name get print ;"
135     "\"Slava\" name set"
136     "["
137     "    \"Diana\" name set"
138     "    \"There, the name is \" write  print-name"
139     "] with-scope"
140     "\"Here, the name is \" write  print-name"
141     "There, the name is Diana\nHere, the name is Slava"
142 }
143 { $curious
144     "Variables are dynamically-scoped in Factor."
145 }
146 { $references
147     "There is a lot more to be said about variables and namespaces."
148     "namespaces"
149 } ;
150
151 ARTICLE: "cookbook-vocabs" "Vocabularies cookbook"
152 "Rather than being in one flat list, words belong to vocabularies; every word is contained in exactly one. When parsing a word name, the parser searches the " { $emphasis "vocabulary search path" } ". When working at the listener, a useful set of vocabularies is already available. In a source file, all used vocabularies must be imported."
153 $nl
154 "For example, a source file containing the following code will print a parse error if you try loading it:"
155 { $code "\"Hello world\" print" }
156 "The " { $link print } " word is contained inside the " { $vocab-link "io" } " vocabulary, which is available in the listener but must be explicitly added to the search path in source files:"
157 { $code
158     "USE: io"
159     "\"Hello world\" print"
160 }
161 "Typically a source file will refer to words in multiple vocabularies, and they can all be added to the search path in one go:"
162 { $code "USING: arrays kernel math ;" }
163 "New words go into the " { $vocab-link "scratchpad" } " vocabulary by default. You can change this with " { $link POSTPONE: IN: } ":"
164 { $code
165     "IN: time-machine"
166     ": time-travel ( when what -- ) frob fizz flap ;"
167 }
168 "Note that words must be defined before being referenced. The following is generally invalid:"
169 { $code
170     ": frob accelerate particles ;"
171     ": accelerate accelerator on ;"
172     ": particles [ (particles) ] each ;"
173 }
174 "You would have to place the first definition after the two others for the parser to accept the file."
175 { $references
176     { }
177     "vocabulary-search"
178     "words"
179     "parser"
180 } ;
181
182 ARTICLE: "cookbook-io" "Input and output cookbook"
183 "Ask the user for their age, and print it back:"
184 { $code
185     "USING: io math.parser ;"
186     ": ask-age ( -- ) \"How old are you?\" print ;"
187     ": read-age ( -- n ) readln string>number ;"
188     ": print-age ( n -- )"
189     "    \"You are \" write"
190     "    number>string write"
191     "    \" years old.\" print ;"
192     ": example ( -- ) ask-age read-age print-age ;"
193     "example"
194 }
195 "Print the lines of a file in sorted order:"
196 { $code
197     "USING: io io.encodings.utf8 io.files sequences sorting ;"
198     "\"lines.txt\" utf8 file-lines natural-sort [ print ] each"
199 }
200 "Read 1024 bytes from a file:"
201 { $code
202     "USING: io io.encodings.binary io.files ;"
203     "\"data.bin\" binary [ 1024 read ] with-file-reader"
204 }
205 "Convert a file of 4-byte cells from little to big endian or vice versa, by directly mapping it into memory and operating on it with sequence words:"
206 { $code
207     "USING: accessors grouping io.files io.mmap kernel sequences ;"
208     "\"mydata.dat\" dup file-info size>> ["
209     "    4 <sliced-groups> [ reverse-here ] change-each"
210     "] with-mapped-file"
211 }
212 "Send some bytes to a remote host:"
213 { $code
214     "USING: io io.encodings.ascii io.sockets strings ;"
215     "\"myhost\" 1033 <inet> ascii"
216     "[ B{ 12 17 102 } write ] with-client"
217 }
218 { $references
219     { }
220     "number-strings"
221     "io"
222 } ;
223
224 ARTICLE: "cookbook-compiler" "Compiler cookbook"
225 "Factor includes two compilers which work behind the scenes. Words are always compiled, and the compilers do not have to be invoked explicitly. For the most part, compilation is a fully transparent process. However, there are a few things worth knowing about the compilation process."
226 $nl
227 "The optimizing compiler trades off compile time for performance of generated code, so loading certain vocabularies might take a while. Saving the image after loading vocabularies can save you a lot of time that you would spend waiting for the same code to load in every coding session; see " { $link "images" } " for information."
228 $nl
229 "After loading a vocabulary, you might see messages like:"
230 { $code
231     ":errors - print 2 compiler errors."
232     ":warnings - print 50 compiler warnings."
233 }
234 "These warnings arise from the compiler's stack effect checker. Warnings are non-fatal conditions -- not all code has a static stack effect, so you try to minimize warnings but understand that in many cases they cannot be eliminated. Errors indicate programming mistakes, such as erroneous stack effect declarations."
235 { $references
236     "To learn more about the compiler and static stack effect inference, read these articles:"
237     "compiler"
238     "compiler-errors"
239     "inference"
240 } ;
241
242 ARTICLE: "cookbook-application" "Application cookbook"
243 "Vocabularies can define a main entry point:"
244 { $code "IN: game-of-life"
245 "..."
246 ": play-life ... ;"
247 ""
248 "MAIN: play-life"
249 }
250 "See " { $link POSTPONE: MAIN: } " for details. The " { $link run } " word loads a vocabulary if necessary, and calls its main entry point; try the following, it's fun:"
251 { $code "\"tetris\" run" }
252 "Factor can deploy stand-alone executables; they do not have any external dependencies and consist entirely of compiled native machine code:"
253 { $code "\"tetris\" deploy-tool" }
254 { $references
255     { }
256     "vocabs.loader"
257     "tools.deploy"
258     "ui.tools.deploy"
259     "cookbook-scripts"
260 } ;
261
262 ARTICLE: "cookbook-scripts" "Scripting cookbook"
263 "Factor can be used for command-line scripting on Unix-like systems."
264 $nl
265 "A text file can begin with a comment like the following, and made executable:"
266 { $code "#! /usr/bin/env factor -script" }
267 "Running the text file will run it through Factor, assuming the " { $snippet "factor" } " binary is in your " { $snippet "$PATH" } "."
268 $nl
269 "The space between " { $snippet "#!" } " and " { $snippet "/usr/bin/env" } " is necessary, since " { $link POSTPONE: #! } " is a parsing word, and a syntax error would otherwise result. The " { $snippet "-script" } " switch suppresses compiler messages, and exits Factor when the script finishes."
270 { $references
271     { }
272     "cli"
273     "cookbook-application"
274 } ;
275
276 ARTICLE: "cookbook-philosophy" "Factor philosophy"
277 "Learning a stack language is like learning to ride a bicycle: it takes a bit of practice and you might graze your knees a couple of times, but once you get the hang of it, it becomes second nature."
278 $nl
279 "The most common difficulty encountered by beginners is trouble reading and writing code as a result of trying to place too many values on the stack at a time."
280 $nl
281 "Keep the following guidelines in mind to avoid losing your sense of balance:"
282 { $list
283     "Simplify, simplify, simplify. Break your program up into small words which operate on a few values at a time. Most word definitions should fit on a single line; very rarely should they exceed two or three lines."
284     "In addition to keeping your words short, keep them meaningful. Give them good names, and make sure each word only does one thing. Try documenting your words; if the documentation for a word is unclear or complex, chances are the word definition is too. Don't be afraid to refactor your code."
285     "If your code looks repetitive, factor it some more."
286     "If after factoring, your code still looks repetitive, introduce combinators."
287     "If after introducing combinators, your code still looks repetitive, look into using meta-programming techniques."
288     "Try to place items on the stack in the order in which they are needed. If everything is in the correct order, no shuffling needs to be performed."
289     "If you find yourself writing a stack comment in the middle of a word, break the word up."
290     { "Use " { $link "cleave-combinators" } " and " { $link "spread-combinators" } " instead of " { $link "shuffle-words" } " to give your code more structure." }
291     { "Not everything has to go on the stack. The " { $vocab-link "namespaces" } " vocabulary provides dynamically-scoped variables, and the " { $vocab-link "locals" } " vocabulary provides lexically-scoped variables. Learn both and use them where they make sense, but keep in mind that overuse of variables makes code harder to factor." }
292     "Every time you define a word which simply manipulates sequences, hashtables or objects in an abstract way which is not related to your program domain, check the library to see if you can reuse an existing definition."
293     { "Learn to use the " { $link "inference" } " tool." }
294     { "Write unit tests. Factor provides good support for unit testing; see " { $link "tools.test" } ". Once your program has a good test suite you can refactor with confidence and catch regressions early." }
295     "Don't write Factor as if it were C. Imperative programming and indexed loops are almost always not the most idiomatic solution."
296     { "Use sequences, assocs and objects to group related data. Object allocation is very cheap. Don't be afraid to create tuples, pairs and triples. Don't be afraid of operations which allocate new objects either, such as " { $link append } "." }
297     { "If you find yourself writing a loop with a sequence and an index, there's almost always a better way. Learn the " { $link "sequences-combinators" } " by heart." }
298     { "If you find yourself writing a heavily nested loop which performs several steps on each iteration, there is almost always a better way. Break the problem down into a series of passes over the data instead, gradually transforming it into the desired result with a series of simple loops. Factor the loops out and reuse them. If you're working on anything math-related, learn " { $link "math-vectors" } " by heart." }
299     { "If you find yourself wishing you could iterate over the datastack, or capture the contents of the datastack into a sequence, or push each element of a sequence onto the datastack, there is almost always a better way. Use " { $link "sequences" } " instead." }
300     "Don't use meta-programming if there's a simpler way."
301     "Don't worry about efficiency unless your program is too slow. Don't prefer complex code to simple code just because you feel it will be more efficient. The Factor compiler is designed to make idiomatic code run fast."
302     { "None of the above are hard-and-fast rules: there are exceptions to all of them. But one rule unconditionally holds: " { $emphasis "there is always a simpler way" } "." }
303 }
304 "Factor tries to implement as much of itself as possible, because this improves simplicity and performance. One consequence is that Factor exposes its internals for extension and study. You even have the option of using low-level features not usually found in high-level languages, such manual memory management, pointer arithmetic, and inline assembly code."
305 $nl
306 "Unsafe features are tucked away so that you will not invoke them by accident, or have to use them to solve conventional programming problems. However when the need arises, unsafe features are invaluable, for example you might have to do some pointer arithmetic when interfacing directly with C libraries." ;
307 ARTICLE: "cookbook-pitfalls" "Pitfalls to avoid"
308 "Factor is a very clean and consistent language. However, it has some limitations and leaky abstractions you should keep in mind, as well as behaviors which differ from other languages you may be used to."
309 { $list
310     "Factor only makes use of one native thread, and Factor threads are scheduled co-operatively. C library calls block the entire VM."
311     "Factor does not hide anything from the programmer, all internals are exposed. It is your responsibility to avoid writing fragile code which depends too much on implementation detail."
312     { "When a source file uses two vocabularies which define words with the same name, the order of the vocabularies in the " { $link POSTPONE: USE: } " or " { $link POSTPONE: USING: } " forms is important. The parser prints warnings when vocabularies shadow words from other vocabularies; see " { $link "vocabulary-search-shadow" } ". The " { $vocab-link "qualified" } " vocabulary implements qualified naming, which can be used to resolve ambiguities." }
313     { "If a literal object appears in a word definition, the object itself is pushed on the stack when the word executes, not a copy. If you intend to mutate this object, you must " { $link clone } " it first. See " { $link "syntax-literals" } "." }
314     { "For a discussion of potential issues surrounding the " { $link f } " object, see " { $link "booleans" } "." }
315     { "Factor's object system is quite flexible. Careless usage of union, mixin and predicate classes can lead to similar problems to those caused by ``multiple inheritance'' in other languages. In particular, it is possible to have two classes such that they have a non-empty intersection and yet neither is a subclass of the other. If a generic word defines methods on two such classes, various disambiguation rules are applied to ensure method dispatch remains deterministic, however they may not be what you expect. See " { $link "method-order" } " for details." }
316     { "Performance-sensitive code should have a static stack effect so that it can be compiled by the optimizing word compiler, which generates more efficient code than the non-optimizing quotation compiler. See " { $link "inference" } " and " { $link "compiler" } "."
317     $nl
318     "This means that methods defined on performance sensitive, frequently-called core generic words such as " { $link nth } " should have static stack effects which are consistent with each other, since a generic word will only have a static stack effect if all methods do."
319     $nl
320     "Unit tests for the " { $vocab-link "stack-checker" } " vocabulary can be used to ensure that any methods your vocabulary defines on core generic words have static stack effects:"
321     { $code "\"stack-checker\" test" }
322     "In general, you should strive to write code with inferable stack effects, even for sections of a program which are not performance sensitive; the " { $link infer. } " tool together with the optimizing compiler's error reporting can catch many bugs ahead of time." }
323     { "Be careful when calling words which access variables from a " { $link make-assoc } " which constructs an assoc with arbitrary keys, since those keys might shadow variables." }
324     { "If " { $link run-file } " throws a stack depth assertion, it means that the top-level form in the file left behind values on the stack. The stack depth is compared before and after loading a source file, since this type of situation is almost always an error. If you have a legitimate need to load a source file which returns data in some manner, define a word in the source file which produces this data on the stack and call the word after loading the file." }
325 } ;
326
327 ARTICLE: "cookbook" "Factor cookbook"
328 "The Factor cookbook is a high-level overview of the most important concepts required to program in Factor."
329 { $subsection "cookbook-syntax" }
330 { $subsection "cookbook-colon-defs" }
331 { $subsection "cookbook-combinators" }
332 { $subsection "cookbook-variables" }
333 { $subsection "cookbook-vocabs" }
334 { $subsection "cookbook-io" }
335 { $subsection "cookbook-application" }
336 { $subsection "cookbook-scripts" }
337 { $subsection "cookbook-compiler" }
338 { $subsection "cookbook-philosophy" }
339 { $subsection "cookbook-pitfalls" } ;
340
341 ABOUT: "cookbook"