]> gitweb.factorcode.org Git - factor.git/blob - basis/help/tour/tour.factor
docs: fix spacing
[factor.git] / basis / help / tour / tour.factor
1 ! Copyright (C) 2022 Raghu Ranganathan and Andrea Ferreti.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: alien.c-types arrays assocs command-line continuations
4 editors help help.markup help.syntax help.vocabs inspector io
5 io.directories io.files io.files.types kernel lexer math
6 math.factorials math.functions math.primes memory namespaces
7 parser prettyprint ranges see sequences stack-checker strings
8 threads tools.crossref tools.test tools.time ui.gadgets.panes
9 ui.tools.deploy vocabs vocabs.loader vocabs.refresh words
10 io.servers http io.sockets io.launcher channels 
11 concurrency.distributed channels.remote help.cookbook
12 splitting.private ;
13 IN: help.tour
14
15 ARTICLE: "tour-concatenative" "Concatenative Languages"
16 Factor is a { $emphasis concatenative } programming language in the spirit of Forth. What is a concatenative language?
17
18 To understand concatenative programming, imagine a world where every value is a function, and the only operation
19 allowed is function composition. Since function composition is so pervasive, it is implicit, and functions can be 
20 juxtaposed in order to compose them. So if { $snippet "f" } and { $snippet "g" } are two functions, their composition is just { $snippet "f g" } (unlike in 
21 mathematical notation, functions are read from left to right, so this means first execute { $snippet "f" } , then execute { $snippet "g" } ).
22
23 This requires some explanation, since we know functions often have multiple inputs and outputs, and it is not always 
24 the case that the output of { $snippet "f" } matches the input of { $snippet "g" } . For instance, { $snippet "g" } may need access to values computed by earlier 
25 functions. But the only thing that { $snippet "g" } can see is the output of { $snippet "f" } , so the output of { $snippet "f" } is the whole state of the 
26 world as far as { $snippet "g" } is concerned. To make this work, functions have to thread the global state, passing it to each other.
27
28 There are various ways this global state can be encoded. The most naive would use a hashmap that maps variable names 
29 to their values. This turns out to be too flexible: if every function can access any piece of global state, there is 
30 little control on what functions can do, little encapsulation, and ultimately programs become an unstructured mess of 
31 routines mutating global variables.
32
33 It works well in practice to represent the state of the world as a stack. Functions can only refer to the topmost 
34 element of the stack, so that elements below it are effectively out of scope. If a few primitives are given to manipulate a 
35 few elements on the stack (e.g., { $link swap } , that exchanges the top two elements on the stack), then it becomes possible to 
36 refer to values down the stack, but the farther the value is down the stack, the harder it becomes to refer to it.
37
38 So, functions are encouraged to stay small and only refer to the top two or three elements on the stack. In a sense, 
39 there is no distinction between local and global variables, but values can be more or less local depending on their 
40 distance from the top of the stack.
41
42 Notice that if every function takes the state of the whole world and returns the next state, its input is never used 
43 anymore. So, even though it is convenient to think of pure functions as receiving a stack as input and outputting a stack,
44 the semantics of the language can be implemented more efficiently by mutating a single stack.
45 ;
46
47 ARTICLE: "tour-stack" "Playing with the stack"
48
49 Let us start looking what Factor actually feels like. Our first words will be literals, like { $snippet "3" } , { $snippet "12.58" } or 
50 { $snippet "\"Chuck Norris\"" } . Literals can be thought as functions that push themselves on the stack. Try writing { $snippet "5" } in the listener and 
51 then press enter to confirm. You will see that the stack, initially empty, now looks like
52
53 { $code "5" }
54
55 You can enter more than one number, separated by spaces, like { $snippet "7 3 1" } , and get
56
57 { $code "5
58 7
59 3
60 1"
61 }
62
63 (the interface shows the top of the stack on the bottom). What about operations? If you write { $snippet "+" } , you will run the 
64 { $snippet "+" } function, which pops the two topmost elements and pushes their sum, leaving us with
65 { $code "5
66 7
67 4"
68 }
69 You can put additional inputs in a single line, so for instance { $snippet "- *" } will leave the single number { $snippet "15" } on the stack (do you see why?).
70
71 You may end up pushing many values to the stack, or end up with an incorrect result. You can then clear the stack with the
72 keystroke { $snippet "Alt+Shift+K" } on Linux/Windows or { $snippet "Cmd+Shift+K" } on MacOS.
73
74 The function { $snippet "." } (a period or a dot) prints the item at the top of the stack, while popping it out of the stack, leaving the stack empty.
75
76 If we write everything on one line, our program so far looks like
77
78 { $code "5 7 3 1 + - * ." }
79
80 which shows Factor's peculiar way of doing arithmetic by putting the arguments first and the operator last - a 
81 convention which is called Reverse Polish Notation (RPN). Notice that 
82 RPN requires no parenthesis, unlike the polish notation of Lisps where 
83 the operator comes first, and RPN requires no precedence rules, unlike the infix notation
84 used in most programming languages and in everyday arithmetic. For instance in any Lisp, the same 
85 computation would be written as
86
87 { $code "(* 5 (- 7 (+ 3 1)))" }
88
89 and in familiar infix notation
90
91 { $code "(7 - (3 + 1)) * 5" }
92
93 Also notice that we have been able to split our computation onto many lines or combine it onto fewer lines rather arbitrarily, and that each line made sense in itself.
94 ;
95
96 ARTICLE: "tour-first-word" "Defining our first word" 
97
98 We will now define our first function. Factor has slightly odd naming of functions: since functions are read from left 
99 to right, they are simply called { $strong "words" } , and this is what we'll call them from now on. Modules in Factor define 
100 words in terms of previous words and these sets of words are then called { $strong "vocabularies" } .
101
102 Suppose we want to compute the factorial. To start with a concrete example, we'll compute the factorial of { $snippet "10" }
103 , so we start by writing { $snippet "10" }  on the stack. Now, the factorial is the product of the numbers from { 
104 $snippet "1" }  to { $snippet "10" } , so we should produce such a list of numbers first.
105
106 The word to produce a range is called { $link [a..b] }  (tokenization is trivial in Factor because words are 
107 always separated by spaces, so this allows you to use any combination of non-whitespace characters as the name of a word; 
108 there are no semantics to the { $snippet "[" } , the { $snippet ".." }  and the { $snippet "]" }  in { $link [a..b] }  
109 since it is just a token like { $snippet "foo" }  or { $snippet "bar" } ).
110
111 The range we want starts with { $snippet "1" } , so we can use the simpler word { $link [1..b] }  that assumes the 
112 range starts at { $snippet "1" }  and only expects the value at the top of the range to be on the stack. If you write { 
113 $link [1..b] }  in the listener, Factor will prompt you with a choice, because the word { $link [1..b] }  is 
114 not imported by default. Factor is able to suggest you import the { $vocab-link "ranges" }  vocabulary, so choose that 
115 option and proceed.
116
117 You should now have on your stack a rather opaque structure which looks like
118
119 { $code "T{ range f 1 10 1 }" }
120
121 This is because our range functions are lazy and only create the range when we attempt to use it. To confirm that we 
122 actually created the list of numbers from { $snippet "1" }  to { $snippet "10" } , we convert the lazy response on the 
123 stack into an array using the word { $link >array } . Enter that word and your stack should now look like
124
125 { $code "{ 1 2 3 4 5 6 7 8 9 10 }" }
126
127 which is promising!
128
129 Next, we want to take the product of those numbers. In many functional languages, this could be done with a function 
130 called reduce or fold. Let's look for one. Pressing { $snippet "F1" }  in the listener will open a contextual help system
131 , where you can search for { $link reduce } . It turns out that { $link reduce }  is actually the word we are 
132 looking for, but at this point it may not be obvious how to use it.
133
134 Try writing { $snippet "1 [ * ] reduce" }  and look at the output: it is indeed the factorial of { $snippet "10" } . 
135 Now, { $link reduce }  usually takes three arguments: a sequence (and we had one on the stack), a starting value i
136 (this is the { $snippet "1" }  we put on the stack next) and a binary operation. This must certainly be the { $link * } 
137 , but what about those square brackets around the { $link * } ?
138
139 If we had written just { $link * } , Factor would have tried to apply multiplication to the topmost two elements 
140 on the stack, which is not what we wanted. What we need is a way to get a word onto the stack without applying it. 
141 Keeping to our textual metaphor, this mechanism is called a { $strong "quotation" } . To quote one or more words, you just surround them 
142 with { $link POSTPONE: [ }  and { $link POSTPONE: ] }  (leaving spaces!). What you get is an anonymous function, which can be
143 shuffled around, manipulated and called.
144
145 Let's type the word { $link drop }  into the listener to empty the stack, and try writing what we have done so 
146 far in a single line: { $snippet "10 [1..b] 1 [ * ] reduce" } . This will leave { $snippet "3628800" }  on the stack as 
147 expected.
148
149 We now want to define a word for factorial that can be used whenever we want a factorial. We will call our word { $snippet "fact" }
150 "(" although { $snippet "!" }  is customarily used as the symbol for factorial, in Factor { $snippet "!" }  
151 is the word used for comments ")" . To define it, we first need to use the word { $link POSTPONE: : } . Then we put the name of 
152 the word being defined, then the { $strong "stack effects" }  and finally the body, ending with the { $link POSTPONE: ; }  word:
153
154 { $code ": fact ( n -- n! ) [1..b] 1 [ * ] reduce ;" }
155
156 What is a stack effect? In our case it is { $snippet "( n -- n! )" } . Stack effects are how you document the 
157 inputs from the stack and outputs to the stack for your word. You can use any identifier to name the stack elements, here we 
158 use { $snippet "n" } . Factor will perform a consistency check that the number of inputs and outputs you specify agrees 
159 with what the body does.
160
161 If you try to write
162
163 { $code ": fact ( m n -- ..b ) [1..b] 1 [ * ] reduce ;" }
164
165 Factor will signal an error that the 2 inputs { $snippet "m" }  and { $snippet "n" } are not consistent with the 
166 body of the word. To restore the previous correct definition press { $snippet "Ctrl+P" }  two times to get back to the 
167 previous input and then enter it.
168
169 The stack effects in definitions  act both as a documentation tool and as a very simple type system, which helps to catch a few errors.
170
171 In any case, you have succesfully defined your first word: if you write { $snippet "10 fact" }  in the listener you 
172 can prove it.
173
174 Notice that the { $snippet "1 [ * ] reduce" }  part of the definition sort of makes sense on its own, being the product of a sequence. The nice thing about a concatenative language is that we can just factor this part out and write
175
176 { $code ": prod ( {x1,...,xn} -- x1*...*xn ) 1 [ * ] reduce ;
177
178 : fact ( n -- n! ) [1..b] prod ;" }
179
180 Our definitions have become simpler and there was no need to pass parameters, rename local variables, or do anything 
181 else that would have been necessary to refactor our function in most languages.
182
183 Of course, Factor already has a word for calculating factorial (there is a whole { $vocab-link "math.factorials" }  
184 vocabulary, including many variants of the usual factorial) and a word for calculating product "(" { $link product }  in the 
185 { $vocab-link "sequences" }  vocabulary), but as it often happens, introductory examples overlap with the standard library.
186 ;
187
188 ARTICLE: "tour-parsing-words" "Parsing Words"
189 If you've been paying close attention so far, you will realize that you have been lied to. { $emphasis "Most" } words act on the stack in order
190 , but there a few words like { $link POSTPONE: [ } , { $link POSTPONE: ] } , { $link POSTPONE: : } and { $link POSTPONE: ; } that don't seem to follow this rule.
191
192 These are { $strong "parsing words" }  and they behave differently from ordinary words like { $snippet "5" } , { $link [1..b] } or { $link drop } . We will cover 
193 these in more detail when we talk about metaprogramming, but for now it is enough to know that parsing words are special.
194
195 They are not defined using the { $link POSTPONE: : } word, but with the word { $link POSTPONE: SYNTAX: } instead. When a parsing words is encountered, it 
196 can interact with the parser using a well-defined API to influence how successive words are parsed. For instance { $link POSTPONE: : } 
197 asks for the next token from the parser until { $link POSTPONE: ; } is found and tries to compile that stream of tokens into a word 
198 definition.
199
200 A common use of parsing words is to define literals. For instance { $link POSTPONE: { } is a parsing word that starts an array 
201 definition and is terminated by { $link POSTPONE: } } . Everything in-between is part of the array. An example of array that we have seen before is 
202 { $snippet "{ 1 2 3 4 5 6 7 8 9 10 } " } .
203
204 There are also literals for hashmaps, { $snippet "H{ { \"Perl\" \"Larry Wall\" } { \"Factor\" \"Slava Pestov\" } { \"Scala\" \"Martin Odersky\" } } " }
205 , and byte arrays, { $snippet "B{ 1 14 18 23 } " } .
206
207 Other uses of parsing words include the module system, the object-oriented features of Factor, enums, memoized functions
208 , privacy modifiers and more. In theory, even { $link POSTPONE: SYNTAX: } can be defined in terms of itself, but the 
209 system has to be bootstrapped somehow.
210
211 ;
212
213 ARTICLE: "tour-stack-shuffling" "Stack Shuffling"
214 Now that you know the basics of Factor, you may want to start assembling more complex words. This may sometimes 
215 require you to use variables that are not on top of the stack, or to use variables more than once. There are a few words that 
216 can be used to help with this. I mention them now since you need to be aware of them, but I warn you that using too many 
217 of these words to manipulate the stack will cause your code to quickly become harder to read and write. Stack shuffling 
218 requires mentally simulating moving values on a stack, which is not a natural way to program. In the next section we'll 
219 see a much more effective way to handle most needs.
220
221 Here is a list of the most common shuffling words together with their effect on the stack. Try them in the listener to 
222 get a feel for how they manipulate the stack.
223
224 { $subsections
225   dup
226   drop
227   swap
228   over
229   dupd
230   swapd
231   nip
232   rot
233   -rot
234   2dup
235 }
236
237 For a deeper look at stack shuffling, see the { $link "cookbook-colon-defs" } .
238 ;
239
240 ARTICLE: "tour-combinators" "Combinators"
241
242 Although the words mentioned in the previous paragraph are occasionally useful (especially the simpler { $link dup } , { $link drop }  
243 and { $link swap } ), you should write code that does as little stack shuffling as possible. This requires practice getting the 
244 function arguments in the right order. Nevertheless, there are certain common patterns of needed stack manipulation that 
245 are better abstracted away into their own words.
246
247 Suppose we want to define a word to determine whether a given number { $snippet "n" }  is prime. A simple algorithm is to test each 
248 number from { $snippet "2" }  to the square root of { $snippet "n" }  and see whether it is a divisor of { $snippet "n" } . In this case, { $snippet "n" }  is used in two places: as an upper bound for the sequence, and as the number to test for divisibility.
249
250 The word { $link bi }  applies two different quotations to the single element on the stack above them, and this is precisely 
251 what we need. For instance { $snippet "5 [ 2 * ] [ 3 + ] bi" }  yields
252 { $code "
253 10
254 8
255 " }
256
257 { $link bi }  applies the quotation { $snippet "[ 2 * ]" }  to the value { $snippet "5" }  and then the quotation { $snippet "[ 3 + ]" }  to the value { $snippet "5" }  leaving us 
258 with { $snippet "10" }  and then { $snippet "8" }  on the stack. Without { $link bi } , we would have to first { $link dup }  { $snippet "5" } , then multiply, and then { $link swap }  the 
259 result of the multiplication with the second { $snippet "5" } , so we could do the addition
260
261 { $code "
262 5 dup 2 * swap 3 +
263 " }
264
265 You can see that { $link bi }  replaces a common pattern of { $link dup } , then calculate, then { $link swap }  and calculate again.
266
267 To continue our prime example, we need a way to make a range starting from { $snippet "2" } . We can define our own word for this { $snippet "[2..b]" } , using the { $link [a..b] } word:
268
269 { $code "
270 : [2..b] ( n -- {2,...,n} ) 2 swap [a..b] ; inline
271 " }
272
273 What's up with that { $snippet "inline" }  word? This is one of the modifiers we can use after defining a word, another one being 
274 { $snippet "recursive" } . This will allow us to have the definition of a short word inlined wherever it is used, rather than incurring 
275 a function call.
276
277 Try our new { $snippet "[2..b]" }  word and see that it works:
278
279 { $code "
280 6 [2..b] >array .
281 " }
282
283 Using { $snippet "[2..b]" }  to produce the range of numbers from { $snippet "2" }  to the square root of an { $snippet "n" }  that is already on the stack is 
284 easy: { $snippet "sqrt floor [2..b]" }  (technically { $link floor }  isn't necessary here, as { $link [a..b] }  works for non-integer bounds). Let's try 
285 that out
286
287 { $code "
288 16 sqrt [2..b] >array .
289 " }
290
291 Now, we need a word to test for divisibility. A quick search in the online help shows that { $link divisor? }  is the word we 
292 want. It will help to have the arguments for testing divisibility in the other direction, so we define { $snippet "multiple?" } ":"
293
294 { $code "
295 : multiple? ( a b -- ? ) swap divisor? ; inline
296 " }
297
298 We can verify that both of these return { $link t } .
299
300 { $code "
301 9 3 divisor? .
302 3 9 multiple? .
303 " }
304
305 Since we're going to use { $link bi } in our { $snippet "prime?" }  definition, we need a second quotation. Our second 
306 quotation needs to test for a value in the range being a divisor of { $snippet "n" }  - in other words we need to partially apply the word  { $snippet "multiple?" } . This can be done with the word { $link curry } , like this: { $snippet "[ multiple? ] curry" } .
307
308 Finally, once we have the range of potential divisors and the test function on the stack, we can test whether any 
309 element satisfied divisibility with { $link any? }  and then negate that answer with { $link not } . Our full definition of { $snippet "prime" }  looks like
310
311 { $code "
312 : prime? ( n -- ? )
313     [ sqrt [2..b] ] [ [ multiple? ] curry ] bi any? not ;
314 " }
315
316 Altough the definition of { $snippet "prime" }  is complicated, the stack shuffling is minimal and is only used in the small helper 
317 functions, which are simpler to reason about than { $snippet "prime?" } .
318
319 Notice that { $snippet "prime?" }  uses two levels of quotation nesting since { $link bi }  operates on two quotations, and our second 
320 quotation contains the word { $link curry } , which also operates on a quotation. In general, Factor words tend to be rather shallow, 
321 using one level of nesting for each higher-order function, unlike Lisps or more generally languages based on the lambda 
322 calculus, which use one level of nesting for each function, higher-order or not.
323
324 { $link bi } and its relative { $link tri } are a small subset of the shuffle words you will use in Factor. You ahouls also become familiar with 
325 { $link bi } , { $link tri } , and { $link bi@ } by reading about them in the online help and trying them out in the listener.
326
327 ;
328
329 ARTICLE: "tour-vocabularies" "Vocabularies"
330
331 It is now time to start writing your functions in files and learn how to import them in the listener. Factor organizes 
332 words into nested namespaces called { $strong "vocabularies" } . You can import all names from a vocabulary with the word { $link POSTPONE: USE: } . 
333 In fact, you may have seen something like
334
335 { $code "USE: ranges" }
336
337 when you asked the listener to import the word { $link [1..b] } for you. You can also use more than one vocabulary at a time 
338 with the word { $link  POSTPONE: USING: } , which is followed by a list of vocabularies and terminated by { $link POSTPONE: ; } , like
339
340 { $code "USING: ranges sequences ;" }
341
342 Finally, you define the vocabulary where your definitions are stored with the word { $link POSTPONE: IN: } . If you search the online 
343 help for a word you have defined so far, like { $link prime? } , you will see that your definitions have been grouped under the 
344 default { $vocab-link "scratchpad" } vocabulary. By the way, this shows that the online help automatically collects information about your 
345 own words, which is a very useful feature.
346
347 There are a few more words, like { $link POSTPONE: QUALIFIED: } , { $link POSTPONE: FROM: } , { $link POSTPONE: EXCLUDE: } and { $link POSTPONE: RENAME: } , that allow more fine-grained control 
348 over the imports, but { $link POSTPONE: USING: } is the most common.
349
350 On disk, vocabularies are stored under a few root directories, much like with the classpath in JVM languages. By 
351 default, the system starts looking up into the directories { $snippet "basis" } , { $snippet "core" } , { $snippet "extra" } , { $snippet "work" } under the Factor home. You can 
352 add more, both at runtime with the word { $link add-vocab-root } , and by creating a configuration file { $snippet ".factor-rc" } , but for now 
353 we will store our vocabularies under the { $snippet "work" } directory, which is reserved for the user.
354
355 Generate a template for a vocabulary writing
356
357 { $code "USE: tools.scaffold
358 \"github.tutorial\" scaffold-work" }
359
360 You will find a file { $snippet "work/github/tutorial/tutorial.factor" } containing an empty vocabulary. Factor integrates with 
361 many editors, so you can try { $snippet "\"github.tutorial\" edit" } ":" this will prompt you to choose your favourite editor, and use that 
362 editor to open the newly created vocabulary.
363
364 You can add the definitions of the previous paragraph, so that it looks like
365
366 { $code "
367 ! Copyright (C) 2014 Andrea Ferretti.
368 ! See https://factorcode.org/license.txt for BSD license.
369 USING: ;
370 IN: github.tutorial
371
372 : [2..b] ( n -- {2,...,n} ) 2 swap [a..b] ; inline
373
374 : multiple? ( a b -- ? ) swap divisor? ; inline
375
376 : prime? ( n -- ? )
377     [ sqrt [2..b] ] [ [ multiple? ] curry ] bi any? not ;
378 " }
379
380 Since the vocabulary was already loaded when you scaffolded it, we need a way to refresh it from disk. You can do this 
381 with { $snippet "\"github.tutorial\" refresh" } . There is also a { $link refresh-all } word, with a shortcut { $snippet "F2" } .
382
383 You will be prompted a few times to use vocabularies, since your { $link POSTPONE: USING: } statement is empty. After having accepted 
384 all of them, Factor suggests you a new header with all the needed imports:
385
386 { $code "
387 USING: kernel math.functions ranges sequences ;
388 IN: github.tutorial
389 " }
390
391 Now that you have some words in your vocabulary, you can edit, say, the { $snippet "multiple?" } word with { $snippet "\\ multiple? edit" } . You 
392 will find your editor open on the relevant line of the right file. This also works for words in the Factor distribution, 
393 although it may be a bad idea to modify them.
394
395 This { $link POSTPONE: \ } word requires a little explanation. It works like a sort of escape, allowing us to put a reference to the 
396 next word on the stack, without executing it. This is exactly what we need, because { $link edit } is a word that takes words 
397 themselves as arguments. This mechanism is similar to quotations, but while a quotation creates a new anonymous function, 
398 here we are directly refering to the word { $snippet "multiple?" } .
399
400 Back to our task, you may notice that the words { $snippet "[2..b]" } and { $snippet "multiple?" } are just helper functions that you may not 
401 want to expose directly. To hide them from view, you can wrap them in a private block like this
402
403 { $code "
404 <PRIVATE
405
406 : [2..b] ( n -- {2,...,n} ) 2 swap [a..b] ; inline
407
408 : multiple? ( a b -- ? ) swap divisor? ; inline
409
410 PRIVATE>
411 " }
412
413 After making this change and refreshed the vocabulary, you will see that the listener is not able to refer to words 
414 like { $snippet "[2..b]" } anymore. The { $link POSTPONE: <PRIVATE } word works by putting all definitions in the private block under a different 
415 vocabulary, in our case { $snippet "github.tutorial.private" } .
416
417 You can have more than one { $link POSTPONE: <PRIVATE } block in a vocabulary, so feel free to organize them as you find necessary.
418
419 It is still possible to refer to words in private vocabularies, as you can confirm by searching for { $snippet "[2..b]" } in the 
420 browser, but of course this is discouraged, since people do not guarantee any API stability for private words. Words 
421 under { $snippet "github.tutorial" } can refer to words in { $snippet "github.tutorial.private" } directly, like { $link prime? } does.
422
423 ;
424
425 ARTICLE: "tour-tests-docs" "Tests and Documentation"
426
427 This is a good time to start writing some unit tests. You can create a skeleton with
428 { $code "
429 \"github.tutorial\" scaffold-tests
430 " }
431 You will find a generated file under { $snippet "work/github/tutorial/tutorial-tests.factor" } , that you can open with 
432 { $snippet "\"github.tutorial\" edit-tests" } . Notice the line
433
434 { $code "
435 USING: tools.test github.tutorial ;
436 " }
437 that imports the unit testing module as well as your own. We will only test the public { $snippet "prime?" }  function.
438
439 Tests are written using the { $link POSTPONE: unit-test }  word, which expects two quotations: the first one containing the expected 
440 outputs, and the second one containing the words to run in order to get that output. Add these lines to 
441 { $snippet "github.tutorial-tests" } ":"
442
443 { $code "
444 { t } [ 2 prime? ] unit-test
445 { t } [ 13 prime? ] unit-test
446 { t } [ 29 prime? ] unit-test
447 { f } [ 15 prime? ] unit-test
448 { f } [ 377 prime? ] unit-test
449 { f } [ 1 prime? ] unit-test
450 { t } [ 20750750228539 prime? ] unit-test
451 " }
452
453 You can now run the tests with { $snippet "\"github.tutorial\" test" } . You will see that we have actually made a mistake, and 
454 pressing { $snippet "F3" }  will show more details. It seems that our assertions fails for { $snippet "2" } .
455
456 In fact, if you manually try to run our functions for { $snippet "2" } , you will see that our definition of { $snippet "[2..b]" }  returns { $snippet "{ 2 }" }  
457 for { $snippet "2 sqrt" } , due to the fact that the square root of two is less than two, so we get a descending interval. Try making a 
458 fix so that the tests now pass.
459
460 There are a few more words to test errors and inference of stack effects. Using { $link POSTPONE: unit-test }  suffices for now, but later on 
461 you may want to check the main documentation on { $link "tools.test" } .
462
463 We can also add some documentation to our vocabulary. Autogenerated documentation is always available for user-defined 
464 words (even in the listener), but we can write some useful comments manually, or even add custom articles that will 
465 appear in the online help. Predictably, we start with { $snippet "\"github.tutorial\" scaffold-docs" }  and 
466 { $snippet "\"github.tutorial\" edit-docs" } .
467
468 The generated file { $snippet "work/github/tutorial-docs.factor" }  imports { $vocab-link "help.markup" } and { $vocab-link "help.syntax" } . These two vocabularies 
469 define words to generate documentation. The actual help page is generated by the { $link POSTPONE: HELP: }  parsing word.
470
471 The arguments to { $link POSTPONE: HELP: }  are nested array of the form { $snippet "{ $directive content... }" } . In particular, you see here the 
472 directives { $link $values } and { $link $description } , but a few more exist, such as { $link $errors } , { $link $examples }  and { $link $see-also } .
473
474 Notice that the type of the output { $snippet "?" }  has been inferred to be boolean. Change the first lines to look like
475
476 { $code "
477 USING: help.markup help.syntax kernel math ;
478 IN: github.tutorial
479
480 HELP: prime?
481 { $values
482     { \"n\" fixnum }
483     { \"?\" boolean }
484 }
485 { $description \"Tests if n is prime. n is assumed to be a positive integer.\" } ;
486 " }
487
488 and refresh the { $snippet "github.tutorial" }  vocabulary. If you now look at the help for { $snippet "prime?" } , for instance with 
489 { $snippet "\\ prime? help" } , you will see the updated documentation.
490
491 You can also render the directives in the listener for quicker feedback. For instance, try writing
492
493 { $code "
494 { $values
495     { \"n\" integer }
496     { \"?\" boolean }
497 } print-content
498 " }
499
500 The help markup contains a lot of possible directives, and you can use them to write stand-alone articles in the help 
501 system. Have a look at some more with { $snippet "\"element-types\" help" } .
502 ;
503
504 ARTICLE: "tour-objects" "The Object System"
505
506 Although it is not apparent from what we have said so far, Factor has object-oriented features, and many core words 
507 are actually method invocations. To better understand how objects behave in Factor, a quote is in order:
508 $nl
509 { $emphasis "\"I invented the term Object-Oriented and I can tell you I did not have C++ in mind.\"
510   -Alan Kay" }
511 $nl
512 The term object-oriented has as many different meanings as people using it. One point of view - which was actually 
513 central to the work of Alan Kay - is that it is about late binding of function names. In Smalltalk, the language where this 
514 concept was born, people do not talk about calling a method, but rather sending a message to an object. It is up to the 
515 object to decide how to respond to this message, and the caller should not know about the implementation. For instance, 
516 one can send the message { $link map } both to an array and a vector, but internally the operation will be handled 
517 differently.
518
519 The binding of the message name to the method implementation is dynamic, and this is regarded as the core strength of 
520 objects. As a result, fairly complex systems can evolve from the cooperation of independent objects that do not mess with 
521 each other's internals.
522
523 To be fair, Factor is very different from Smalltalk, but still there is the concept of classes, and generic words can 
524 defined having different implementations on different classes.
525
526 Some classes are builtin in Factor, such as { $link string } , { $link boolean } , { $link fixnum } or { $link word } . Next, the most common way to 
527 define a class is as a { $strong "tuple" } . Tuples are defined with the { $link POSTPONE: TUPLE: } parsing word, followed by the tuple name and the 
528 fields of the class that we want to define, which are called { $strong "slots" }  in Factor parlance.
529
530 Let us define a class for movies:
531
532 { $code "
533 TUPLE: movie title director actors ;
534 " }
535
536 This also generates setters { $snippet ">>title" } , { $snippet ">>director" } and { $snippet ">>actors" } and getters { $snippet "title>>" } , { $snippet "director>>" } and { $snippet "actors>>" } . 
537 For instance, we can create a new movie with
538
539 { $code "
540 movie new
541     \"The prestige\" >>title
542     \"Christopher Nolan\" >>director
543     { \"Hugh Jackman\" \"Christian Bale\" \"Scarlett Johansson\" } >>actors
544 " }
545
546 We can also shorten this to
547
548 { $code "
549 \"The prestige\" \"Christopher Nolan\"
550 { \"Hugh Jackman\" \"Christian Bale\" \"Scarlett Johansson\" }
551 movie boa
552 " }
553
554 The word { $link boa } stands for 'by-order-of-arguments'. It is a constructor that fills the slots of the tuple with the 
555 items on the stack in order. { $snippet "movie boa" } is called a { $strong "boa constructor" } , a pun on the Boa Constrictor. It is customary to 
556 define a most common constructor called { $snippet "<movie>" } , which in our case could be simply
557
558 { $code "
559 : <movie> ( title director actors -- movie ) movie boa ;
560 " }
561 In fact, boa constructor are so common, that the above line can be shortened to
562
563 { $code "
564 C: <movie> movie
565 " }
566
567 In other cases, you may want to use some defaults, or compute some fields.
568
569 The functional minded will be worried about the mutability of tuples. Actually, slots can be declared to be "read-only" 
570 with { $snippet "{ slot-name read-only } " } . In this case, the field setter will not be generated, and the value must be set a the 
571 beginning with a boa constructor. Other valid slot modifiers are { $link POSTPONE: initial: } - to declare a default value - and a class word
572 , such as { $snippet "integer" } , to restrict the values that can be inserted.
573
574 As an example, we define another tuple class for rock bands
575
576 { $code "
577 TUPLE: band
578     { keyboards string read-only }
579     { guitar string read-only }
580     { bass string read-only }
581     { drums string read-only } ;
582
583 : <band> ( keyboards guitar bass drums -- band ) band boa ;
584 " }
585
586 together with one instance
587
588 { $code "
589 \"Richard Wright\" \"David Gilmour\" \"Roger Waters\" \"Nick Mason\" <band>
590 " }
591
592 Now, of course everyone knows that the star in a movie is the first actor, while in a rock band it is the bass player. 
593 To encode this, we first define a { $strong "generic word" } 
594
595 { $code "
596 GENERIC: star ( item -- star )
597 " }
598
599 As you can see, it is declared with the parsing word { $link POSTPONE: GENERIC: } and declares its stack effects but it has no 
600 implementation right now, hence no need for the closing { $link POSTPONE: ; } . Generic words are used to perform dynamic dispatch. We can define 
601 implementations for various classes using the word { $link POSTPONE: M: }
602
603 { $code "
604 M: movie star actors>> first ;
605
606 M: band star bass>> ;
607 " }
608
609 If you write { $snippet "star ." } two times, you can see the different effect of calling a generic word on instances of different 
610 classes.
611
612 Builtin and tuple classes are not all that there is to the object system: more classes can be defined with set 
613 operations like { $link POSTPONE: UNION: } and { $link POSTPONE: INTERSECTION: } . Another way to define a class is as a { $strong "mixin" } .
614
615 Mixins are defined with the { $link POSTPONE: MIXIN: } word, and existing classes can be added to the mixin like so:
616
617 { $code "
618 INSTANCE: class mixin
619 " }
620
621 Methods defined on the mixin will then be available on all classes that belong to the mixin. If you are familiar with 
622 Haskell typeclasses, you will recognize a resemblance, although Haskell enforces at compile time that instance of 
623 typeclasses implement certain functions, while in Factor this is informally specified in documentation.
624
625 Two important examples of mixins are { $link sequence } and { $link assoc } . The former defines a protocol that is available to all 
626 concrete sequences, such as strings, linked lists or arrays, while the latter defines a protocol for associative arrays, 
627 such as hashtables or association lists.
628
629 This enables all sequences in Factor to be acted upon with a common set of words, while differing in implementation 
630 and minimizing code repetition (because only few primitives are needed, and other operations are defined for the { $link sequence }
631  class). The most common operations you will use on sequences are { $link map } , { $link filter } and { $link reduce } , but there are many more 
632 - as you can see with { $snippet "\"sequences\" help" } .
633 ;
634
635 ARTICLE: "tour-tools" "Learning the Tools"
636
637 A big part of the productivity of Factor comes from the deep integration of the language and libraries with the tools around 
638 them, which are embodied in the listener. Many functions of the listener can be used programmatically, and vice versa.
639 You have seen some examples of this:
640
641 { $list
642   { "The help is navigable online, but you can also invoke it with " { $link help } " and print help items with " { $link print-content } " ; " }
643   { "The " { $snippet "F2" } " shortcut or the words " { $link refresh } " and " { $link refresh-all } " can be used to refresh vocabularies from disk while continuing working in the listener;" }
644   { "The " { $link edit } " word gives you editor integration, but you can also click on file names in the help pages for vocabularies to open them." }
645 }
646
647 The refresh is an efficient mechanism. Whenever a word is redefined, words that depend on it are recompiled against the new 
648 defition. You can check by yourself doing
649
650 { $code "
651 : inc ( x -- y ) 1 + ;
652 : inc-print ( x -- ) inc . ;
653
654 5 inc-print
655 " }
656
657 and then
658
659 { $code "
660 : inc ( x -- y ) 2 + ;
661
662 5 inc-print
663 " }
664
665 This allows you to keep a listener open, improve your definitions, periodically save your definitions to a file 
666 and refresh to view your changes, without ever having to reload Factor.
667
668 You can also save the state of your current session with the word { $link save-image } and later restore it by starting Factor with
669
670 { $code "
671 ./factor -i=path-to-image
672 " }
673
674 In fact, Factor is image-based and only uses files when loading and refreshing vocabularies.
675
676 The power of the listener does not end here. Elements of the stack can be inspected by clicking on them, or by calling the 
677 word { $link inspector } . For instance try writing
678
679 { $code "
680 TUPLE: trilogy first second third ;
681
682 : <trilogy> ( first second third -- trilogy ) trilogy boa ;
683
684 \"A new hope\" \"The Empire strikes back\" \"Return of the Jedi\" <trilogy>
685 \"George Lucas\" 2array
686 " }
687
688 You will get an item that looks like
689
690 { $code "
691 { ~trilogy~ \"George Lucas\" }
692 " }
693
694 on the stack. Try clicking on it: you will be able to see the slots of the array. You can inspect a slot shown in the inspector by double clicking on it. This is extremely useful for interactive prototyping. Special objects can customize the inspector 
695 by implementing the { $link content-gadget } method.
696
697 There is another inspector for errors. Whenever an error arises, it can be inspected with { $snippet "F3" } . This allows you to investigate 
698 exceptions, bad stack effect declarations and so on. The debugger allows you to step into code, both forwards and 
699 backwards, and you should take a moment to get some familiarity with it. You can also trigger the debugger manually, by 
700 entering some code in the listener and pressing { $snippet "Ctrl+w" } .
701
702 The listener has provisions for benchmarking code. As an example, here is an intentionally inefficient Fibonacci:
703
704 { $code "
705 DEFER: fib-rec
706 : fib ( n -- f(n) ) dup 2 < [ ] [ fib-rec ] if ;
707 : fib-rec ( n -- f(n) ) [ 1 - fib ] [ 2 - fib ] bi + ;
708 " }
709
710 (notice the use of { $link POSTPONE: DEFER: } to define two mutually "recursive" words). You can benchmark the running time writing { $snippet "40 fib" }  
711 and then pressing Ctrl+t instead of Enter. You will get timing information, as well as other statistics. Programmatically
712 , you can use the { $link time } word on a quotation to do the same.
713
714 You can also add watches on words, to print inputs and outputs on entry and exit. Try writing
715
716 { $code "
717 \\ fib watch
718 " }
719
720 and then run { $snippet "10 fib" }  to see what happens. You can then remove the watch with { $snippet "\\ fib reset" } .
721
722 Another useful tool is the { $vocab-link "lint" }  vocabulary. This scans word definitions to find duplicated code that can be factored 
723 out. As an example, let us define a word to check if a string starts with another one. Create a test vocabulary
724
725 { $code "
726 \"lintme\" scaffold-work
727 " }
728
729 and add the following definition:
730
731 { $code "
732 USING: kernel sequences ;
733 IN: lintme
734
735 : startswith? ( str sub -- ? ) dup length swapd head = ;
736 " }
737
738 Load the lint tool with { $snippet "USE: lint" }  and write { $snippet "\"lintme\" lint-vocab" } . You will get a report mentioning that the word sequence 
739 { $snippet "length swapd" }  is already used in the word { $link (split) } of { $vocab-link "splitting.private" } , hence it could be factored out.
740
741 Modifying the source of a word in the standard library is unadvisable - let alone a private one - but 
742 in more complex cases the lint tool can help you prevent code duplication. It is not unusual that Factor has a word that does exactly what you want, owing to its massive standard library. It is a good idea to lint your vocabularies from 
743 time to time, to avoid code duplication and as a good way to discover library words that you may have accidentally redefined
744 .
745
746 Finally, there are a few utilities to inspect words. You can see the definition of a word in the help tool, but a quicker 
747 way can be { $link see } . Or, vice versa, you may use { $link usage. } to inspect the callers of a given word. Try { $snippet "\\ reverse see" }  and 
748 { $snippet "\\ reverse usage." } .
749 ;
750
751 ARTICLE: "tour-metaprogramming" "Metaprogramming"
752
753 We now venture into the metaprogramming world, and write our first parsing word. By now, you have seen a lot of 
754 parsing words, such as { $link POSTPONE: [ } . { $link POSTPONE: { } , { $link POSTPONE: H{ } , { $link POSTPONE: USE: } , { $link POSTPONE: IN: } , { $link POSTPONE: <PRIVATE } , { $link POSTPONE: GENERIC: } and so on. Each of those is defined with the 
755 parsing word { $link POSTPONE: SYNTAX: } and interacts with Factor's parser.
756
757 The parser accumulates tokens onto an accumulator vector, unless it finds a parsing word, which is executed immediately.
758  Since parsing words execute at compile time, they cannot interact with the stack, but they have access to the 
759 accumulator vector. Their stack effect must be { $snippet "( accum -- accum )" } . Usually what they do is ask the parser for some more tokens,
760  do something with them, and finally push a result on the accumulator vector with the word { $snippet "suffix!" } .
761
762 As an example, we will define a literal for DNA sequences. A DNA sequence is a sequence of one of the bases cytosine, 
763 guanine, adenine and thymine, which we will denote by the letters c, g, a, t. Since there are four possible bases, we 
764 can encode each with two bits. Let use define a word that operates on characters:
765
766 { $code "
767 : dna>bits ( token -- bits ) {
768     { CHAR: a [ { f f } ] }
769     { CHAR: c [ { t t } ] }
770     { CHAR: g [ { f t } ] }
771     { CHAR: t [ { t f } ] }
772 } case ;
773 " }
774
775 where the first bit represents whether the basis is a purine or a pyrimidine, and the second one identifies bases that 
776 pair together.
777
778 Our aim is to read a sequence of letters a, c, g, "t" - possibly with spaces - and convert them to a bit array. Factor 
779 supports bit arrays, and literal bit arrays look like { $snippet "?{ f f t }" } .
780
781 Our syntax for DNA will start with { $snippet "DNA{" } and get all tokens until the closing token { $snippet "}" } is found. The intermediate 
782 tokens will be put into a string, and using our function { $snippet "dna>bits" } we will map this string into a bit array. To read 
783 tokens, we will use the word { $link parse-tokens } . There are a few higher-level words to interact with the parser, such as { $link parse-until }
784 and { $link parse-literal } , but we cannot apply them in our case, since the tokens we will find are just sequences of a 
785 c g t, instead of valid Factor words. Let us start with a simple approximation that just reads tokens between our 
786 delimiters and outputs the string obtained by concatenation
787
788 { $code "
789 SYNTAX: DNA{ \"}\" parse-tokens concat suffix! ;
790 " }
791
792 You can test the effect by doing { $snippet "DNA{ a ccg t a g }" } , which should output { $snippet "\"accgtag\"" } . As a second approximation, we 
793 transform each letter into a boolean pair:
794
795 { $code "
796 SYNTAX: DNA{ \"}\" parse-tokens concat
797     [ dna>bits ] { } map-as suffix! ;
798 " }
799
800 Notice the use of { $link map-as } instead of { $link map } . Since the target collection is not a string, we did not use { $link map } , which 
801 preserves the type, but { $link map-as } , which take as an additional argument an examplar of the target collection - here { $snippet "{ }" } .
802 Our "final" version flattens the array of pairs with { $link concat } and finally makes into a bit array:
803
804 { $code "
805 SYNTAX: DNA{ \"}\" parse-tokens concat
806     [ dna>bits ] { } map-as
807     concat >bit-array suffix! ;
808 " }
809
810 If you try it with { $snippet "DNA{ a ccg t a g }" } you should get
811
812 { $code "
813 { $snippet \"?{ f f t t t t f t t f f f f t }\" }
814 " }
815
816 Let us try an example from the { $url
817 "https://re-factor.blogspot.com/2014/06/swift-ranges.html" "Re: Factor" } blog,
818 which adds infix syntax for ranges. Until now, we have used { $link [a..b] } to create a range. We can make a 
819 syntax that is friendlier to people coming from other languages using { $snippet "..." } as an infix word.
820
821 We can use { $link scan-object } to ask the parser for the next parsed object, and { $link unclip-last } to get the top element from 
822 the accumulator vector. This way, we can define { $snippet "..." } simply with
823
824 { $code "
825 SYNTAX: ... unclip-last scan-object [a..b] suffix! ;
826 " }
827
828 You can try it with { $snippet "12 ... 18 >array" } .
829
830 We only scratched the surface of parsing words; in general, they allow you to perform arbitrary computations at 
831 compile time, enabling powerful forms of metaprogramming.
832
833 In a sense, Factor syntax is completely flat, and parsing words allow you to introduce syntaxes more complex than a 
834 stream of tokens to be used locally. This lets any programmer expand the language by adding these syntactic features in libraries
835 . In principle, it would even be possible to have an external language compile to Factor -- say JavaScript -- and embed it 
836 as a domain-specific language in the boundaries of a { $snippet "<JS ... JS>" } parsing word. Some taste is needed not to abuse too much of 
837 this to introduce styles that are much too alien in the concatenative world.
838 ;
839
840 ARTICLE: "tour-stack-ne" "When the stack is not enough"
841
842 Until now we have cheated a bit, and tried to avoid writing examples that would have been too complex to write in 
843 concatenative style. Truth is, you { $emphasis "will" } find occasions where this is too restrictive. Parsing words can ease some of these restrictions, and Factor comes with a few to handle the most common annoyances.
844
845 One thing you may want to do is to actually name local variables. The { $link POSTPONE: :: } word works like { $link POSTPONE: : } , but allows you to 
846 actually bind the name of stack parameters to variables, so that you can use them multiple times, in the order you want. For 
847 instance, let us define a word to solve quadratic equations. I will spare you the purely stack-based version, and 
848 present you a version with locals (this will require the { $vocab-link "locals" } vocabulary):
849
850 { $code "
851 :: solveq ( a b c -- x )
852     b neg
853     b b * 4 a c * * - sqrt
854     +
855     2 a * / ;" }
856
857 In this case we have chosen the + sign, but we can do better and output both solutions:
858
859 { $code "
860 :: solveq ( a b c -- x1 x2 )
861     b neg
862     b b * 4 a c * * - sqrt
863     [ + ] [ - ] 2bi
864     [ 2 a * / ] bi@ ;" }
865
866 You can check that this definition works with something like { $snippet "2 -16 30 solveq" } , which should output both { $snippet "3.0" } and { $snippet "5.0" } . 
867 Apart from being written in RPN style, our first version of { $snippet "solveq" } looks exactly the same it would in a language 
868 with local variables. For the second definition, we apply both the { $link + }  and { $link - }  operations to -b and delta, using the 
869 combinator { $link 2bi } , and then divide both results by 2a using { $link bi@ } .
870
871 There is also support for locals in quotations - using { $link POSTPONE: [| } - and methods - using { $link POSTPONE: M:: } - and one can also create a 
872 scope where to bind local variables outside definitions using { $link POSTPONE: [let } . Of course, all of these are actually compiled to 
873 concatenative code with some stack shuffling. I encourage you to browse examples for these words, but bear in mind that 
874 their usage in practice is actually much less prominent than one would expect - about 1% of Factor's own codebase.
875
876 Another common case happens when you need to add values to a quotation in specific places. You can partially apply a quotation using { $link curry } . This assumes that the value you are 
877 applying should appear leftmost in the quotation; in the other cases you need some stack shuffling. The word { $link with }  is a 
878 sort of partial application with a hole. It also curries a quotation, but uses the third element on the stack instead 
879 of the second. Also, the resulting curried quotation will be applied to an element inserting it in the second position.
880
881 The example from the documentation probably tells more than the
882 above sentence -- try writing:
883
884 { $code "1 { 1 2 3 } [ / ] with map" }
885
886 Let me take again { $snippet "prime?" } , but this time write it without using helper words:
887
888 { $code "
889 : prime? ( n -- ? )
890     [ sqrt 2 swap [a,b] ] [ [ swap divisor? ] curry ] bi any? not ;" }
891
892 Using { $link with }  instead of { $link curry } , this simplifies to
893
894 { $code "
895 : prime? ( n -- ? )
896     2 over sqrt [a,b] [ divisor? ] with any? not ;" }
897
898 If you are not able to visualize what is happening, you may want to consider the { $vocab-link "fry" } vocabulary. It defines { $strong "fried quotations" } ";" 
899 these are quotations that have holes in them - marked by { $snippet "_" } - that are filled with values from the stack.
900
901 The first quotation is rewritten more simply as
902
903 { $code "
904 [ '[ 2 _ sqrt [a,b] ] call ]
905 " }
906
907 Here we use a fried quotation - starting with { $link POSTPONE: '[ } - to inject the element on the top of the stack in the second 
908 position, and then use { $link call } to evaluate the resulting quotation. The second quotation can be rewritten as follows:
909
910 { $code "
911 [ '[ _ swap divisor? ] ]
912 " }
913
914 so an alternative defition of { $snippet "prime?" } is
915
916 { $code "
917 : prime? ( n -- ? )
918     [ '[ 2 _ sqrt [a,b] ] call ] [ '[ _ swap divisor? ] ] bi any? not ;
919 " }
920
921 Depending on your taste, you may find this version more readable. In this case, the added clarity is probably lost due 
922 to the fact that the fried quotations are themselves inside quotations, but occasionally their use can do a lot to 
923 simplify the flow.
924
925 Finally, there are times where one just wants to give names to variables that are available inside some scope, and use 
926 them where necessary. These variables can hold values that are global, or at least not local to a single word. A 
927 typical example could be the input and output streams, or database connections.
928
929 For this purpose, Factor allows you to create { $strong "dynamic variables" }  and bind them in scopes. The first thing is to create a { $strong "symbol" }  
930 for a variable, say
931
932 { $code "SYMBOL: favorite-language" }
933 Then one can use the word { $link set }  to bind the variable and { $link get }  to retrieve its values, like
934
935 { $code "\"Factor\" favorite-language set
936 favorite-language get" }
937
938 Scopes are nested, and new scopes can be created with the word { $link with-scope } . Try for instance
939
940 { $code "
941 : on-the-jvm ( -- )
942     [
943         \"Scala\" favorite-language set
944         favorite-language get .
945     ] with-scope ;" }
946
947 If you run { $snippet "on-the-jvm" } , { $snippet "\"Scala\"" } will be printed, but after execution, { $snippet "favorite-language get" } will hold { $snippet "\"Factor\"" } as its value.
948
949 All the tools that we have seen in this section should only be used when absolutely necessary, as they break concatenativity and make 
950 words less easy to factor. However, they can greatly increase clarity when needed. Factor has a very practical approach and 
951 does not shy from offering features that are less pure but nevertheless often useful.
952 ;
953
954 ARTICLE: "tour-io" "Input/Output"
955
956 We will now leave the tour of the language, and start investigating how to tour the outside world with Factor. This section will begin with basic input and output, and move on to asynchronous, parallel
957 and distributed I/O.
958
959 Factor implements efficient asynchronous input/output facilities, similar to NIO on the JVM or the Node.js I/O system. 
960 This means that input and output operations are performed in the background, leaving the foreground task free to 
961 perform work while the disk is spinning or the network is buffering packets. Factor is currently single threaded, but 
962 asynchrony allows it to be rather performant for applications that are I/O-bound.
963
964 All of Factor input/output words are centered on { $strong "streams" } . Streams are lazy sequences which can be read from or written 
965 to, typical examples being files, network ports or the standard input and output. Factor holds a couple of dynamic 
966 variables called { $link input-stream } and { $link output-stream } , which are used by most I/O words. These variables can be rebound locally 
967 using { $link with-input-stream } , { $link with-output-stream } and { $link with-streams } . When you are in the listener, the default streams 
968 write and read in the listener, but once you deploy your application as an executable, they are usually bound to the 
969 standard input and output of your console.
970
971 The words { $link <file-reader> } and { $link <file-writer> } (or { $link <file-appender> } ) can be used to create a read or write stream to a 
972 file, given its path and encoding. Putting everything together, we make a simple example of a word that reads each line 
973 of a file encoded in UTF8, and writes the first letter of the line to the listener.
974
975 First, we want a { $snippet "safe-head" } word, that works like { $link head } , but returns its input if the sequence is too short. To do so
976 , we will use the word { $link recover } , which allows us to declare a try-catch block. It requires two quotations: the first 
977 one is executed, and on failure, the second one is executed with the error as input. Hence we can define
978
979 { $code "
980 : safe-head ( seq n -- seq' ) [ head ] [ 2drop ] recover ;" }
981
982 This is an impractical example of exceptions, as Factor defines the { $link short } word, which takes a 
983 sequence and a number, and returns the minimum between the length of the sequence and the number. This allows us to write simply
984
985 { $code "
986 : safe-head ( seq n -- seq' ) index-or-length head ;" }
987
988 With this definition, we can make a word to read the first character of the first line:
989
990 { $code "
991 : read-first-letters ( path -- )
992     utf8 <file-reader> [
993         readln 1 safe-head write nl
994     ] with-input-stream ;" }
995
996 Using the helper word { $link with-file-reader } , we can also shorten this to
997
998 { $code "
999 : read-first-letters ( path -- )
1000     utf8 [
1001         readln 1 safe-head write nl
1002     ] with-file-reader ;" }
1003
1004 Unfortunately, we are limited to one line. To read more lines, we should chain calls to { $link readln } until one returns { $link f } .
1005 Factor helps us with { $link file-lines } , which lazily iterates "over" lines. Our "final" definition becomes
1006
1007 { $code "
1008 : read-first-letters ( path -- )
1009     utf8 file-lines [ 1 safe-head write nl ] each ;" }
1010
1011 When the file is small, one can also use { $link file-contents } to read the whole contents of a file in a single string. 
1012 Factor defines many more words for input/output, which cover many more cases, such as binary files or sockets.
1013
1014 We will end this section investigating some words to walk the filesystem. Our aim is a very minimal implementation of the { $snippet "ls" } command.
1015
1016 The word { $link directory-entries } lists the contents of a directory, giving a list of tuple elements, each one having the 
1017 slots { $snippet "name" } and { $snippet "type" } . You can see this by trying { $snippet "\"/home\" directory-entries [ name>> ] map" } . If you inspect the 
1018 directory entries, you will see that the type is either { $link +directory+ } or { $link +regular-file+ } (well, there are symlinks as well, 
1019 but we will ignore them for simplicity). Hence we can define a word that lists files and directories with
1020
1021 { $code "
1022 : list-files-and-dirs ( path -- files dirs )
1023     directory-entries [ type>> +regular-file+ = ] partition ;" }
1024
1025 With this, we can define a word { $snippet "ls" } that will print directory contents as follows:
1026
1027 { $code "
1028 : ls ( path -- )
1029     list-files-and-dirs
1030     \"DIRECTORIES:\" write nl
1031     \"------------\" write nl
1032     [ name>> write nl ] each
1033     \"FILES:\" write nl
1034     \"------\" write nl
1035     [ name>> write nl ] each ;" }
1036
1037 Try the word on your home directory to see the effects. In the next section, we shall look at how to create an 
1038 executable for our simple program.
1039 ;
1040
1041 ARTICLE: "tour-deploy" "Deploying programs"
1042
1043
1044 There are two ways to run Factor programs outside the listener: as scripts, which are interpreted by Factor, or as 
1045 standalone executable compiled for your platform. Both require you to define a vocabulary with an entry point (altough 
1046 there is an even simpler way for scripts), so let's do that first.
1047
1048 Start by creating our { $snippet "ls" } vocabulary with { $snippet "\"ls\" scaffold-work" } and make it look like this:
1049
1050
1051 { $code "\
1052 ! Copyright (C) 2014 Andrea Ferretti.
1053 ! See https://factorcode.org/license.txt for BSD license.
1054 USING: accessors command-line io io.directories io.files.types
1055   kernel namespaces sequences ;
1056 IN: ls
1057
1058 <PRIVATE
1059
1060 : list-files-and-dirs ( path -- files dirs )
1061     directory-entries [ type>> +regular-file+ = ] partition ;
1062
1063 PRIVATE>
1064
1065 : ls ( path -- )
1066     list-files-and-dirs
1067     \"DIRECTORIES:\" write nl
1068     \"------------\" write nl
1069     [ name>> write nl ] each
1070     \"FILES:\" write nl
1071     \"------\" write nl
1072     [ name>> write nl ] each ;" }
1073
1074 When we run our vocabulary, we will need to read arguments from the command line. Command-line arguments are stored 
1075 under the { $link command-line } dynamic variable, which holds an array of strings. Hence - forgetting any error checking - we can 
1076 define a word which runs { $snippet "ls" } on the first command-line argument with
1077
1078 { $code ": ls-run ( -- ) command-line get first ls ;" }
1079
1080 Finally, we use the word { $link POSTPONE: MAIN: } to declare the main word of our vocabulary:
1081
1082 { $code "MAIN: ls-run" }
1083
1084 Having added those two lines to your vocabulary, you are now ready to run it. The simplest way is to run the 
1085 vocabulary as a script with the { $snippet "-run" } flag passed to Factor. For instance to list the contents of my home I can do
1086
1087 { $code "$ ./factor -run=ls /home/andrea" }
1088
1089 In order to produce an executable, we must set some options and call the { $snippet "deploy" } word. The simplest way to do this 
1090 graphically is to invoke the { $link deploy-tool } word. If you write { $snippet "\"ls\" deploy-tool" } , you will be presented with a window to 
1091 choose deployment options. For our simple case, we will leave the default options and choose Deploy.
1092
1093 After a little while, you should be presented with an executable that you can run like
1094
1095 { $code "$ cd ls
1096
1097 $ ./ls /home/andrea" }
1098
1099 Try making the { $snippet "ls" } program more robust by handling missing command-line arguments and non-existent or non-directory 
1100 arguments.
1101 ;
1102
1103 ARTICLE: "tour-multithreading" "Multithreading"
1104
1105 As we have said, the Factor runtime is single-threaded, like Node. Still, one can emulate concurrency in a single-threaded
1106 setting by making use of { $strong "coroutines" } . These are essentially cooperative threads, which periodically release 
1107 control with the { $link yield } word, so that the scheduler can decide which coroutine to run next.
1108
1109 Although cooperative threads do not allow to make use of multiple cores, they still have some benefits:
1110 { $list 
1111   "input/output operations can avoid blocking the entire runtime, so that one can implement quite performant applications if I/O is the bottleneck;"
1112   "user interfaces are naturally a multithreaded construct, and they can be implemented in this model, as the listener itself shows;"
1113   "finally, some problems may just naturally be easier to write making use of the multithreaded constructs."
1114 }
1115
1116 For the cases where one wants to make use of multiple cores, Factor offers the possibility of spawning other processes 
1117 and communicating between them with the use of { $strong "channels" } , as we will see in a later section.
1118
1119 Threads in Factor are created using a quotation and a name, with the { $link spawn } word. Let us use this to print the 
1120 first few lines of Star Wars, one per second, each line being printed inside its own thread. First, we will assign them to a 
1121 dynamic variable:
1122
1123 { $code "\
1124 SYMBOL: star-wars
1125
1126 \"A long time ago, in a galaxy far, far away....
1127
1128 It is a period of civil war. Rebel
1129 spaceships, striking from a hidden
1130 base, have won their first victory
1131 against the evil Galactic Empire.
1132
1133 During the battle, rebel spies managed
1134 to steal secret plans to the Empire's
1135 ultimate weapon, the DEATH STAR, an
1136 armored space station with enough
1137 power to destroy an entire planet.
1138
1139 Pursued by the Empire's sinister agents,
1140 Princess Leia races home aboard her
1141 starship, custodian of the stolen plans
1142 that can save her people and restore
1143 freedom to the galaxy....\"
1144 \"\n\" split star-wars set
1145 " }
1146
1147 We will spawn 18 threads, each one printing a line. The operation that a thread must run amounts to
1148
1149 { $code "star-wars get ?nth print" }
1150
1151 Note that dynamic variables are shared between threads, so each one has access to star-wars. This is fine, since it is 
1152 read-only, but the usual caveats about shared memory in a multithreaded settings apply.
1153
1154 Let us define a word for the thread workload
1155
1156 { $code "
1157 : print-a-line ( i -- )
1158     star-wars get ?nth print ;" }
1159
1160 If we give the i-th thread the name "\"i\"" , our example amounts to
1161
1162 { $code "
1163 18 [0..b) [
1164     [ [ print-a-line ] curry ]
1165     [ number>string ]
1166     bi spawn
1167 ] each" }
1168
1169 Note the use of { $link curry } to send i to the quotation that prints the i-th line. This is almost what we want, but it runs 
1170 too fast. We need to put the thread to sleep for a while. So we { $link clear } the stack that now contains a lot of thread 
1171 objects and look for the { $link sleep } word in the help.
1172
1173 It turns out that { $link sleep } does exactly what we need, but it takes a { $strong "duration" }  object as input. We can create a 
1174 duration of i seconds with... well { $snippet "i seconds" } . So we define
1175
1176 { $code "
1177 : wait-and-print ( i -- )
1178     dup seconds sleep print-a-line ;" }
1179
1180 Let us try
1181
1182 { $code "
1183 18 [0..b) [
1184     [ [ wait-and-print ] curry ]
1185     [ number>string ]
1186     bi spawn
1187 ] each" }
1188
1189 Instead of { $link spawn } , we can also use { $link in-thread } which uses a dummy thread name and discards the returned thread, 
1190 simplifying the above to
1191
1192 { $code "
1193 18 [0..b) [
1194     [ wait-and-print ] curry in-thread
1195 ] each" }
1196
1197 In serious applications threads will be long-running. In order to make them 
1198 cooperate, one can use the { $link yield } word to signal that the thread has done a unit of work, and other threads can gain 
1199 control. You also may want to have a look at other words to { $link stop } , { $link suspend } or { $link resume } threads.
1200 ;
1201
1202 ARTICLE: "tour-servers" "Servers and Furnace"
1203
1204 Server applications often use more than one thread. When writing network 
1205 applications, it is common to start a thread for each incoming connection (remember that these are green threads, so they are much 
1206 more lightweight than OS threads).
1207
1208 To simplify this, Factor has the word { $link spawn-server } , which works like { $link spawn } , but in addition repeatedly spawns the 
1209 quotation until it returns { $link f } . This is still a very low-level word: in reality one has to do much more: listen for TCP 
1210 connections on a given port, handle connection limits and so on.
1211
1212 The vocabulary { $vocab-link "io.servers" } allows to write and configure TCP servers. A server is created with the word { $link <threaded-server> } , which requires an encoding as a parameter. Its slots can then be set to configure logging, connection limits, 
1213 ports and so on. The most important slot to fill is { $snippet "handler" } , which contains a quotation that is executed for each 
1214 incoming connection. You can see a simple example of a server with
1215 { $code "
1216 \"resource:extra/time-server/time-server.factor\" edit-file
1217 " }
1218
1219 We will raise the level of abstraction even more and show how to run a simple HTTP server. First, { $snippet "USE: http.server" } .
1220
1221 An HTTP application is built out of a { $strong "responder" } . A responder is essentially a function from a path and an HTTP 
1222 request to an HTTP response, but more concretely it is anything that implements the method { $snippet "call-responder*" } . Responses are 
1223 instances of the tuple { $link response } , so are usually generated calling { $link <response> } and customizing a few slots. Let us 
1224 write a simple echo responder:
1225
1226 { $code "TUPLE: echo-responder ;
1227
1228 : <echo-responder> ( -- responder ) echo-responder new ;
1229
1230 M: echo-responder call-responder*
1231     drop
1232     <response>
1233         200 >>code
1234         \"Document follows\" >>message
1235         \"text/plain\" >>content-type
1236         swap concat >>body ;" }
1237
1238 Responders are usually combined to form more complex responders in order to implement routing and other features. In 
1239 our simplistic example, we will use just this one responder, and set it globally with
1240
1241 { $code "<echo-responder> main-responder set-global" }
1242
1243 Once you have done this, you can start the server with { $snippet "8080 httpd" } . You can then visit { $url "https://localhost:8080/hello/%20/from/%20/factor" }
1244  in your browser to see your first responder in action. You can then stop the server with { $link stop-server } .
1245
1246 Now, if this was all that Factor offers to write web applications, it would still be rather low level. In reality, web 
1247 applications are usually written using a web framework called { $strong "Furnace" } .
1248
1249 Furnace allows us - among other things - to write more complex actions using a template language. Actually, there are 
1250 two template languages shipped by default, and we will use { $strong "Chloe" } . Furnace allows us to create { $strong "page actions" }  
1251 from Chloe templates, and in order to create a responder we will need to add routing.
1252
1253 Let use first investigate a simple example of routing. To do this, we create a special type of responder called a { $strong "dispatcher" } , that dispatches requests based on path parameters. Let us create a simple dispatcher that will choose 
1254 between our echo responder and a default responder used to serve static files.
1255
1256 { $code "
1257 dispatcher new-dispatcher
1258     <echo-responder> \"echo\" add-responder
1259     \"/home/andrea\" <static> \"home\" add-responder
1260     main-responder set-global" }
1261
1262 Of course, substitute the path { $snippet "/home/andrea" } with any folder you like. If you start again the server with { $snippet "8080 httpd" }
1263 , you should be able to see both our simple echo responder (under { $snippet "/echo" } ) and the contents of your files (under { $snippet "/home" } ).
1264  Notice that directory listing is disabled by default, you can only access the content of files.
1265
1266 Now that you know how to do routing, we can write page actions in Chloe. Things are starting to become complicated, so 
1267 we scaffold a vocabulary with { $snippet "\"hello-furnace\" scaffold-work" } . Make it look like this:
1268
1269 { $code "\
1270 ! Copyright (C) 2014 Andrea Ferretti.
1271 ! See https://factorcode.org/license.txt for BSD license.
1272 USING: accessors furnace.actions http http.server
1273   http.server.dispatchers http.server.static kernel sequences ;
1274 IN: hello-furnace
1275
1276
1277 TUPLE: echo-responder ;
1278
1279 : <echo-responder> ( -- responder ) echo-responder new ;
1280
1281 M: echo-responder call-responder*
1282     drop
1283     <response>
1284         200 >>code
1285         \"Document follows\" >>message
1286         \"text/plain\" >>content-type
1287         swap concat >>body ;
1288
1289 TUPLE: hello-dispatcher < dispatcher ;
1290
1291 : <example-responder> ( -- responder )
1292     hello-dispatcher new-dispatcher
1293         <echo-responder> \"echo\" add-responder
1294         \"/home/andrea\" <static> \"home\" add-responder
1295         <page-action>
1296             { hello-dispatcher \"greetings\" } >>template
1297         \"chloe\" add-responder ;" }
1298
1299 Most things are the same as we have done in the listener. The only difference is that we have added a third responder 
1300 in our dispatcher, under { $snippet "chloe" } . This responder is created with a page action. The page action has many slots - say, to 
1301 declare the behaviour of receiving the result of a form - but we only set its template. This is the pair with the 
1302 dispatcher class and the relative path of the template file.
1303
1304 In order for all this to work, create a file { $snippet "work/hello-furnace/greetings.xml" } with a content like
1305
1306 { $code "<?xml version='1.0' ?>
1307
1308 <t:chloe xmlns:t=\"https://factorcode.org/chloe/1.0\">
1309     <p>Hello from Chloe</p>
1310 </t:chloe>" }
1311
1312 Reload the { $snippet "hello-furnace" } vocabulary and { $snippet "<example-responder> main-responder set-global" } . You should be able to see 
1313 the results of your efforts under { $url "https://localhost:8080/chloe" } . Notice that there was no need to restart the server, we 
1314 can change the main responder dynamically.
1315
1316 This ends our very brief tour of Furnace. Furnace is much more expansive than the examples shown here,  as it allows for many general web
1317 tasks. You can learn more about it in the { $vocab-link "furnace" } documentation.
1318 ;
1319
1320 ARTICLE: "tour-processes" "Processes and Channels"
1321
1322
1323 As discussed earlier, Factor is single-threaded from the point of view of the OS. If we want to make use of multiple cores, we 
1324 need a way to spawn Factor processes and communicate between them. Factor implements two different models of message-passing concurrency: the actor model, which is based on the idea of sending messages asynchronously between threads, and the 
1325 CSP model, based on the use of { $strong "channels" } .
1326
1327 As a warm-up, we will make a simple example of communication between threads in the same process.
1328
1329 { $code "FROM: concurrency.messaging => send receive ;" }
1330
1331 We can start a thread that will receive a message and print it repeatedly:
1332
1333 { $code ": print-repeatedly ( -- ) receive . print-repeatedly ;
1334
1335 [ print-repeatedly ] \"printer\" spawn" }
1336
1337 A thread whose quotation starts with { $link receive } and calls itself recursively behaves like an actor in Erlang or Akka. 
1338 We can then use { $link send } to send messages to it. Try { $snippet "\"hello\" over send" } and then { $snippet "\"threading\" over send" } .
1339
1340 Channels are slightly different abstractions, used for instance in Go and in Clojure core.async. They decouple the 
1341 sender and the receiver, and are usually used synchronously. For instance, one side can receive from a channel before some 
1342 other party sends something to it. This just means that the receiving end yields control to the scheduler, which waits 
1343 for a message to be sent before giving control to the receiver again. This feature sometimes makes it easier to 
1344 synchronize multithreaded applications.
1345
1346 Again, we first use a channel to communicate between threads in the same process. As expected, { $snippet "USE: channels" } . You 
1347 can create a channel with { $link <channel> } , write to it with { $link to } and read from it with { $link from } . Note that both operations are 
1348 blocking: { $link to } will block until the value is read in a different thread, and { $link from } will block until a value is available.
1349
1350 We create a channel and give it a name with
1351
1352 { $code "SYMBOL: ch
1353
1354 <channel> ch set" }
1355
1356 Then we write to it in a separate thread, in order not to block the UI
1357
1358 { $code "[ \"hello\" ch get to ] in-thread" }
1359
1360 We can then read the value in the UI with
1361
1362 { $code "ch get from" }
1363
1364 We can also invert the order:
1365
1366 { $code "[ ch get from . ] in-thread
1367
1368 \"hello\" ch get to" }
1369
1370 This works fine, since we had set the reader first.
1371
1372 Now, for the interesting part: we will start a second Factor instance and communicate via message sending. Factor 
1373 transparently supports sending messages over the network, serializing values with the { $vocab-link "serialize" } vocabulary.
1374
1375 Start another instance of Factor, and run a node server on it. We will use the word { $link <inet4> } , that creates an IPv4 
1376 address from a host and a port, and the { $link <node-server> } constructor
1377
1378 { $code "USE: concurrency.distributed
1379
1380 f 9000 <inet4> <node-server> start-server" }
1381
1382 Here we have used { $link f } as host, which just stands for localhost. We will also start a thread that keeps a running count 
1383 of the numbers it has received.
1384
1385 { $code "FROM: concurrency.messaging => send receive ;
1386
1387 : add ( x -- y ) receive + dup . add ;
1388
1389 [ 0 add ] \"adder\" spawn" }
1390
1391 Once we have started the server, we can make a thread available with { $link register-remote-thread } ":"
1392
1393 { $code "dup name>> register-remote-thread" }
1394
1395 Now we switch to the other instance of Factor. Here we will receive a reference to the remote thread and start sending 
1396 numbers to it. The address of a thread is just the address of its server and the name we have registered the thread with
1397 , so we obtain a reference to our adder thread with
1398
1399 { $code "f 9000 <inet4> \"adder\" <remote-thread>" }
1400
1401 Now, we reimport { $link send } just to be sure (there is an overlap with a word having the same name in { $vocab-link "io.sockets" } , that we 
1402 have imported)
1403
1404 { $code "FROM: concurrency.messaging => send receive ;" }
1405
1406 and we can start sending numbers to it. Try { $snippet "3 over send" } , and then { $snippet "8 over send" } - you should see the running total 
1407 printed in the other Factor instance.
1408
1409 What about channels? We go back to our server, and start a channel there, just as above. This time, though, we { $link publish } it to make it available remotely:
1410
1411 { $code "USING: channels channels.remote ;
1412
1413 <channel> dup publish" }
1414
1415 What you get in return is an id you can use remotely to communicate. For instance, I just got 
1416 { $snippet "326546621698456955263335657082068225943" } (yes, they really want to be sure it is unique!).
1417
1418 We will wait on this channel, thereby blocking the UI:
1419
1420 { $code "swap from ." }
1421
1422 In the other Factor instance we use the id to get a reference to the remote channel and write to it
1423
1424 { $code "\
1425 f 9000 <inet4> 326546621698456955263335657082068225943 <remote-channel>
1426 \"Hello, channels\" over to" }
1427
1428 In the server instance, the message should be printed.
1429
1430 Remote channels and threads are both useful to implement distributed applications and make good use of multicore 
1431 servers. Of course, it remains the question how to start worker nodes in the first place. Here we have done it manually - if 
1432 the set of nodes is fixed, this is actually an option.
1433
1434 Otherwise, one could use the { $vocab-link "io.launcher" } vocabulary to start other Factor instances programmatically.
1435 ;
1436
1437 ARTICLE: "tour-where" "Where to go from here?"
1438
1439 We have covered a lot of ground here, and we hope that this has given you a taste of the great things
1440 you can do with Factor. You can now 
1441 work your way through the documentation, and hopefully contribute to Factor yourself.
1442
1443 Let me end with a few tips:
1444
1445 { $list
1446 { "when starting to write Factor, it is " { $emphasis "very" } " easy to deal a lot with stack shuffling. Learn the " 
1447 { $vocab-link "combinators" } " well, and do not fear to throw away your first examples." }
1448 "no definition is too short: aim for one line."
1449 "the help system and the inspector are your best friends."
1450 }
1451 To be fair, we have to mention some drawbacks of Factor:
1452
1453 { $list
1454 "The community is small. It is difficult to find information about Factor on the internet.
1455 However, you can help with this by posting questions on Stack Overflow under the [factor] tag."
1456 "The concatenative model is very powerful, but also hard to get good at."
1457 "Factor lacks native threads: although the distributed processes make up for it, they incur some cost in serialization."
1458 "Factor does not currently have a package manager. Most prominent packages are part of the main Factor distribution."
1459 }
1460
1461 The Factor source tree is massive, so here's a few vocabularies to get you started off:
1462
1463 { $list 
1464   { "We have not talked a lot about errors and exceptions. Learn more in the " { $vocab-link "debugger" } " vocabulary." } 
1465   { "The " { $vocab-link "macros" } " vocabulary implements a form of compile time metaprogramming less general than parsing words." }
1466   { "The " { $vocab-link "models" } " vocabulary lets you implement a form of dataflow programming using objects with observable slots." }
1467   { "The " { $vocab-link "match" } " vocabulary implements ML-style pattern matching." }
1468   { "The " { $vocab-link "monads" } " vocabulary implements Haskell-style monads." }
1469 }
1470
1471 These vocabularies are a testament to the power and expressivity of Factor, and we hope that they 
1472 help you make something you like. Happy hacking!
1473
1474 { $code "\
1475 USE: images.http
1476
1477 \"https://factorcode.org/logo.png\" http-image." }
1478 ;
1479
1480 ARTICLE: "tour" "Guided tour of Factor"
1481 Factor is a mature, dynamically typed language based on the concatenative paradigm. Getting started with Factor can be daunting 
1482 since the concatenative paradigm is different from most mainstream languages.
1483 This tutorial will:
1484
1485 { $list 
1486   "Guide you through the basics of Factor so you can appreciate its simplicity and power."
1487   "Assume you are an experienced programmer familiar with a functional language"
1488   "Assume you understand concepts like folding, higher-order functions, and currying"
1489 }
1490
1491 Even though Factor is a niche language, it is mature and has a comprehensive standard library covering tasks from JSON 
1492 serialization to socket programming and HTML templating. It runs in its own optimized VM with very high performance for a dynamically 
1493 typed language. It also has a flexible object system, a Foreign Function Interface to C, and 
1494 asynchronous I/O that works a bit like Node.js, but with a much simpler model for cooperative multithreading.
1495
1496 Factor has a few significant advantages over 
1497 other languages, most arising from the fact that it has essentially no syntax:
1498
1499 { $list
1500   "Refactoring is very easy, leading to short and meaningful function definitions"
1501   "It is extremely succinct, letting the programmer concentrate on what is important instead of boilerplate"
1502   "It has powerful metaprogramming capabilities, exceeding even those of LISPs"
1503   "It is ideal for creating DSLs"
1504   "It integrates easily with powerful tools"
1505 }
1506
1507 A few file paths in the examples may need to be adjusted based on your system.
1508
1509 The first section gives some motivation for the peculiar model of computation of concatenative languages, but feel free 
1510 to skip it if you want to get your feet wet and return to it after some hands on practice with Factor.
1511
1512 { $heading "The Tour" }
1513 { $subsections
1514   "tour-concatenative"
1515   "tour-stack"
1516   "tour-first-word"
1517   "tour-parsing-words"
1518   "tour-stack-shuffling"
1519   "tour-combinators"
1520   "tour-vocabularies"
1521   "tour-tests-docs"
1522   "tour-objects"
1523   "tour-tools"
1524   "tour-metaprogramming"
1525   "tour-stack-ne"
1526   "tour-io"
1527   "tour-deploy"
1528   "tour-multithreading"
1529   "tour-servers"
1530   "tour-processes"
1531   "tour-where"
1532 }
1533 ;
1534
1535 ABOUT: "tour"