]> gitweb.factorcode.org Git - factor.git/blob - core/combinators/combinators-docs.factor
Update Windows for word renames, fix lint errors
[factor.git] / core / combinators / combinators-docs.factor
1 USING: arrays help.markup help.syntax strings sbufs vectors
2 kernel quotations generic generic.standard classes
3 math assocs sequences sequences.private combinators.private
4 effects words ;
5 IN: combinators
6
7 ARTICLE: "cleave-combinators" "Cleave combinators"
8 "The cleave combinators apply multiple quotations to a single value or set of values."
9 $nl
10 "Two quotations:"
11 { $subsections
12     bi
13     2bi
14     3bi
15 }
16 "Three quotations:"
17 { $subsections
18     tri
19     2tri
20     3tri
21 }
22 "An array of quotations:"
23 { $subsections
24     cleave
25     2cleave
26     3cleave
27 }
28 "Cleave combinators provide a more readable alternative to repeated applications of the " { $link keep } " combinators. The following example using " { $link keep } ":"
29 { $code
30     "[ 1 + ] keep"
31     "[ 1 - ] keep"
32     "2 *"
33 }
34 "can be more clearly written using " { $link tri } ":"
35 { $code
36     "[ 1 + ]"
37     "[ 1 - ]"
38     "[ 2 * ] tri"
39 } ;
40
41 ARTICLE: "spread-combinators" "Spread combinators"
42 "The spread combinators apply multiple quotations to multiple values. The asterisk (" { $snippet "*" } ") suffixed to these words' names signifies that they are spread combinators."
43 $nl
44 "Two quotations:"
45 { $subsections bi* 2bi* }
46 "Three quotations:"
47 { $subsections tri* 2tri* }
48 "An array of quotations:"
49 { $subsections spread }
50 "Spread combinators provide a more readable alternative to repeated applications of the " { $link dip } " combinators. The following example using " { $link dip } ":"
51 { $code
52     "[ [ 1 + ] dip 1 - ] dip 2 *"
53 }
54 "can be more clearly written using " { $link tri* } ":"
55 { $code
56     "[ 1 + ] [ 1 - ] [ 2 * ] tri*"
57 }
58 "A generalization of the above combinators to any number of quotations can be found in " { $link "combinators" } "." ;
59
60 ARTICLE: "apply-combinators" "Apply combinators"
61 "The apply combinators apply a single quotation to multiple values. The at sign (" { $snippet "@" } ") suffixed to these words' names signifies that they are apply combinators."
62 { $subsections bi@ 2bi@ tri@ 2tri@ }
63 "A pair of condition words built from " { $link bi@ } " to test two values:"
64 { $subsections both? either? }
65 "All of the apply combinators are equivalent to using the corresponding " { $link "spread-combinators" } " with the same quotation supplied for every value." ;
66
67 ARTICLE: "dip-keep-combinators" "Preserving combinators"
68 "Sometimes it is necessary to temporarily hide values on the datastack. The " { $snippet "dip" } " combinators invoke the quotation at the top of the stack, hiding some number of values:"
69 { $subsections dip 2dip 3dip 4dip }
70 "The " { $snippet "keep" } " combinators invoke a quotation and restore some number of values to the top of the stack:"
71 { $subsections keep 2keep 3keep } ;
72
73 ARTICLE: "curried-dataflow" "Curried dataflow combinators"
74 "Curried cleave combinators:"
75 { $subsections bi-curry tri-curry }
76 "Curried spread combinators:"
77 { $subsections bi-curry* tri-curry* }
78 "Curried apply combinators:"
79 { $subsections bi-curry@ tri-curry@ }
80 { $see-also "dataflow-combinators" } ;
81
82 ARTICLE: "compositional-examples" "Examples of compositional combinator usage"
83 "Consider printing the same message ten times:"
84 { $code ": print-10 ( -- ) 10 [ \"Hello, world.\" print ] times ;" }
85 "if we wanted to abstract out the message into a parameter, we could keep it on the stack between iterations:"
86 { $code ": print-10 ( message -- ) 10 [ dup print ] times drop ;" }
87 "However, keeping loop-invariant values on the stack doesn't always work out nicely. For example, a word to subtract a value from each element of a sequence:"
88 { $code ": subtract-n ( seq n -- seq' ) swap [ over - ] map nip ;" }
89 "Three shuffle words are required to pass the value around. Instead, the loop-invariant value can be partially applied to a quotation using " { $link curry } ", yielding a new quotation that is passed to " { $link map } ":"
90 { $example
91   ": subtract-n ( seq n -- seq' ) [ - ] curry map ;"
92   "{ 10 20 30 } 5 subtract-n ."
93   "{ 5 15 25 }"
94 }
95 "Now consider the word that is dual to the one above; instead of subtracting " { $snippet "n" } " from each stack element, it subtracts each element from " { $snippet "n" } "."
96 $nl
97 "One way to write this is with a pair of " { $link swap } "s:"
98 { $code ": n-subtract ( n seq -- seq' ) swap [ swap - ] curry map ;" }
99 "Since this pattern comes up often, " { $link with } " encapsulates it:"
100 { $example
101   ": n-subtract ( n seq -- seq' ) [ - ] with map ;"
102   "30 { 10 20 30 } n-subtract ."
103   "{ 20 10 0 }"
104 }
105 { $see-also "fry.examples" } ;
106
107 ARTICLE: "compositional-combinators" "Compositional combinators"
108 "Certain combinators transform quotations to produce a new quotation."
109 { $subsections "compositional-examples" }
110 "Fundamental operations:"
111 { $subsections curry compose }
112 "Derived operations:"
113 { $subsections 2curry 3curry with prepose }
114 "These operations run in constant time, and in many cases are optimized out altogether by the " { $link "compiler" } ". " { $link "fry" } " are an abstraction built on top of these operations, and code that uses this abstraction is often clearer than direct calls to the below words."
115 $nl
116 "Curried dataflow combinators can be used to build more complex dataflow by combining cleave, spread and apply patterns in various ways."
117 { $subsections "curried-dataflow" }
118 "Quotations also implement the sequence protocol, and can be manipulated with sequence words; see " { $link "quotations" } ". However, such runtime quotation manipulation will not be optimized by the optimizing compiler." ;
119
120 ARTICLE: "booleans" "Booleans"
121 "In Factor, any object that is not " { $link f } " has a true value, and " { $link f } " has a false value. The " { $link t } " object is the canonical true value."
122 { $subsections f t }
123 "A union class of the above:"
124 { $subsections boolean }
125 "There are some logical operations on booleans:"
126 { $subsections
127     >boolean
128     not
129     and
130     or
131     xor
132 }
133 "Boolean values are most frequently used for " { $link "conditionals" } "."
134 { $heading "The f object and f class" }
135 "The " { $link f } " object is the unique instance of the " { $link f } " class; the two are distinct objects. The latter is also a parsing word which adds the " { $link f } " object to the parse tree at parse time. To refer to the class itself you must use " { $link POSTPONE: POSTPONE: } " or " { $link POSTPONE: \ } " to prevent the parsing word from executing."
136 $nl
137 "Here is the " { $link f } " object:"
138 { $example "f ." "f" }
139 "Here is the " { $link f } " class:"
140 { $example "\\ f ." "POSTPONE: f" }
141 "They are not equal:"
142 { $example "f \\ f = ." "f" }
143 "Here is an array containing the " { $link f } " object:"
144 { $example "{ f } ." "{ f }" }
145 "Here is an array containing the " { $link f } " class:"
146 { $example "{ POSTPONE: f } ." "{ POSTPONE: f }" }
147 "The " { $link f } " object is an instance of the " { $link f } " class:"
148 { $example "USE: classes" "f class-of ." "POSTPONE: f" }
149 "The " { $link f } " class is an instance of " { $link word } ":"
150 { $example "USE: classes" "\\ f class-of ." "word" }
151 "On the other hand, " { $link t } " is just a word, and there is no class which it is a unique instance of."
152 { $example "t \\ t eq? ." "t" }
153 "Many words which search collections confuse the case of no element being present with an element being found equal to " { $link f } ". If this distinction is important, there is usually an alternative word which can be used; for example, compare " { $link at } " with " { $link at* } "." ;
154
155 ARTICLE: "conditionals-boolean-equivalence" "Expressing conditionals with boolean logic"
156 "Certain simple conditional forms can be expressed in a simpler manner using boolean logic."
157 $nl
158 "The following two lines are equivalent:"
159 { $code "[ drop f ] unless" "swap and" }
160 "The following two lines are equivalent:"
161 { $code "[ ] [ ] ?if" "swap or" }
162 "The following two lines are equivalent, where " { $snippet "L" } " is a literal:"
163 { $code "[ L ] unless*" "L or" } ;
164
165 ARTICLE: "conditionals" "Conditional combinators"
166 "The basic conditionals:"
167 { $subsections if when unless }
168 "Forms abstracting a common stack shuffle pattern:"
169 { $subsections if* when* unless* }
170 "Another form abstracting a common stack shuffle pattern:"
171 { $subsections ?if }
172 "Sometimes instead of branching, you just need to pick one of two values:"
173 { $subsections ? }
174 "Two combinators which abstract out nested chains of " { $link if } ":"
175 { $subsections cond case }
176 { $subsections "conditionals-boolean-equivalence" }
177 { $see-also "booleans" "bitwise-arithmetic" both? either? } ;
178
179 ARTICLE: "dataflow-combinators" "Dataflow combinators"
180 "Dataflow combinators express common dataflow patterns such as performing a operation while preserving its inputs, applying multiple operations to a single value, applying a set of operations to a set of values, or applying a single operation to multiple values."
181 { $subsections
182     "dip-keep-combinators"
183     "cleave-combinators"
184     "spread-combinators"
185     "apply-combinators"
186 }
187 "More intricate dataflow can be constructed by composing " { $link "curried-dataflow" } "." ;
188
189 ARTICLE: "combinators-quot" "Quotation construction utilities"
190 "Some words for creating quotations which can be useful for implementing method combinations and compiler transforms:"
191 { $subsections cond>quot case>quot alist>quot } ;
192
193 ARTICLE: "call-unsafe" "Unsafe combinators"
194 "Unsafe calls declare an effect statically without any runtime checking:"
195 { $subsections call-effect-unsafe execute-effect-unsafe } ;
196
197 ARTICLE: "call" "Fundamental combinators"
198 "The most basic combinators are those that take either a quotation or word, and invoke it immediately. There are two sets of these fundamental combinators. They differ in whether the compiler is expected to determine the stack effect of the expression at compile time or the stack effect is declared and verified at run time."
199 $nl
200 { $heading "Compile-time checked combinators" }
201 "With these combinators, the compiler attempts to determine the stack effect of the expression at compile time, rejecting the program if the effect cannot be determined. See " { $link "inference-combinators" } "."
202 { $subsections call execute }
203 { $heading "Run-time checked combinators" }
204 "With these combinators, the stack effect of the expression is checked at run time."
205 { $subsections POSTPONE: call( POSTPONE: execute( }
206 "Note that the opening parenthesis is actually part of the word name for " { $snippet "call(" } " and " { $snippet "execute(" } "; they are parsing words, and they read a stack effect until the corresponding closing parenthesis. The underlying words are a bit more verbose, but they can be given non-constant stack effects:"
207 { $subsections call-effect execute-effect }
208 { $heading "Unchecked combinators" }
209 { $subsections "call-unsafe" }
210 { $see-also "effects" "inference" } ;
211
212 ARTICLE: "combinators" "Combinators"
213 "A central concept in Factor is that of a " { $emphasis "combinator" } ", which is a word taking code as input."
214 { $subsections
215     "call"
216     "dataflow-combinators"
217     "conditionals"
218     "looping-combinators"
219     "compositional-combinators"
220     "combinators.short-circuit"
221     "combinators.smart"
222     "combinators-quot"
223     "generalizations"
224 }
225 "More combinators are defined for working on data structures, such as " { $link "sequences-combinators" } " and " { $link "assocs-combinators" } "."
226 { $see-also "quotations" } ;
227
228 ABOUT: "combinators"
229
230 HELP: call-effect
231 { $values { "quot" quotation } { "effect" effect } }
232 { $description "Given a quotation and a stack effect, calls the quotation, asserting at runtime that it has the given stack effect. This is a macro which expands given a literal effect parameter, and an arbitrary quotation which is not required at compile time." }
233 { $examples
234   "The following two lines are equivalent:"
235   { $code
236     "call( a b -- c )"
237     "( a b -- c ) call-effect"
238   }
239 } ;
240
241 HELP: execute-effect
242 { $values { "word" word } { "effect" effect } }
243 { $description "Given a word and a stack effect, executes the word, asserting at runtime that it has the given stack effect. This is a macro which expands given a literal effect parameter, and an arbitrary word which is not required at compile time." }
244 { $examples
245   "The following two lines are equivalent:"
246   { $code
247     "execute( a b -- c )"
248     "( a b -- c ) execute-effect"
249   }
250 } ;
251
252 HELP: execute-effect-unsafe
253 { $values { "word" word } { "effect" effect } }
254 { $description "Given a word and a stack effect, executes the word, blindly declaring at runtime that it has the given stack effect. This is a macro which expands given a literal effect parameter, and an arbitrary word which is not required at compile time." }
255 { $warning "If the word being executed has an incorrect stack effect, undefined behavior will result. User code should use " { $link POSTPONE: execute( } " instead." } ;
256
257 { call-effect call-effect-unsafe execute-effect execute-effect-unsafe } related-words
258
259 HELP: cleave
260 { $values { "x" object } { "seq" "a sequence of quotations with stack effect " { $snippet "( x -- ... )" } } }
261 { $description "Applies each quotation to the object in turn." }
262 { $examples
263     "The " { $link bi } " combinator takes one value and two quotations; the " { $link tri } " combinator takes one value and three quotations. The " { $link cleave } " combinator takes one value and any number of quotations, and is essentially equivalent to a chain of " { $link keep } " forms:"
264     { $code
265         "! Equivalent"
266         "{ [ p ] [ q ] [ r ] [ s ] } cleave"
267         "[ p ] keep [ q ] keep [ r ] keep s"
268     }
269 } ;
270
271 HELP: 2cleave
272 { $values { "x" object } { "y" object }
273           { "seq" "a sequence of quotations with stack effect " { $snippet "( x y -- ... )" } } }
274 { $description "Applies each quotation to the two objects in turn." } ;
275
276 HELP: 3cleave
277 { $values { "x" object } { "y" object } { "z" object }
278           { "seq" "a sequence of quotations with stack effect " { $snippet "( x y z -- ... )" } } }
279 { $description "Applies each quotation to the three objects in turn." } ;
280
281 { bi tri cleave } related-words
282
283 HELP: spread
284 { $values { "objs..." "objects" } { "seq" "a sequence of quotations with stack effect " { $snippet "( x -- ... )" } } }
285 { $description "Applies each quotation to the object in turn." }
286 { $examples
287     "The " { $link bi* } " combinator takes two values and two quotations; the " { $link tri* } " combinator takes three values and three quotations. The " { $link spread } " combinator takes " { $snippet "n" } " values and " { $snippet "n" } " quotations, where " { $snippet "n" } " is the length of the input sequence, and is essentially equivalent to a nested series of " { $link dip } "s:"
288     { $code
289         "! Equivalent"
290         "{ [ p ] [ q ] [ r ] [ s ] } spread"
291         "[ [ [ p ] dip q ] dip r ] dip s"
292     }
293 } ;
294
295 { bi* tri* spread } related-words
296
297 HELP: to-fixed-point
298 { $values { "object" object } { "quot" { $quotation "( ... object(n) -- ... object(n+1) )" } } { "object(n)" object } }
299 { $description "Applies the quotation repeatedly with " { $snippet "object" } " as the initial input until the output of the quotation equals the input." }
300 { $examples
301     { $example
302         "USING: combinators kernel math prettyprint sequences ;"
303         "IN: scratchpad"
304         ": flatten ( sequence -- sequence' )"
305         "    \"flatten\" over index"
306         "    [ [ 1 + swap nth ] [ nip dup 2 + ] [ drop ] 2tri replace-slice ] when* ;"
307         ""
308         "{ \"flatten\" { 1 { 2 3 } \"flatten\" { 4 5 } { 6 } } } [ flatten ] to-fixed-point ."
309         "{ 1 { 2 3 } 4 5 { 6 } }"
310     }
311 } ;
312
313 HELP: alist>quot
314 { $values { "default" "a quotation" } { "assoc" "a sequence of quotation pairs" } { "quot" "a new quotation" } }
315 { $description "Constructs a quotation which calls the first quotation in each pair of " { $snippet "assoc" } " until one of them outputs a true value, and then calls the second quotation in the corresponding pair. Quotations are called in reverse order, and if no quotation outputs a true value then " { $snippet "default" } " is called." }
316 { $notes "This word is used to implement compile-time behavior for " { $link cond } ", and it is also used by the generic word system. Note that unlike " { $link cond } ", the constructed quotation performs the tests starting from the end and not the beginning." } ;
317
318 HELP: cond
319 { $values { "assoc" "a sequence of quotation pairs and an optional quotation" } }
320 { $description
321     "Calls the second quotation in the first pair whose first quotation yields a true value. A single quotation will always yield a true value."
322     $nl
323     "The following two phrases are equivalent:"
324     { $code "{ { [ X ] [ Y ] } { [ Z ] [ T ] } } cond" }
325     { $code "X [ Y ] [ Z [ T ] [ no-cond ] if ] if" }
326 }
327 { $errors "Throws a " { $link no-cond } " error if none of the test quotations yield a true value." }
328 { $examples
329     { $example
330         "USING: combinators io kernel math ;"
331         "0 {"
332         "    { [ dup 0 > ] [ drop \"positive\" ] }"
333         "    { [ dup 0 < ] [ drop \"negative\" ] }"
334         "    [ drop \"zero\" ]"
335         "} cond print"
336         "zero"
337     }
338 } ;
339
340 HELP: no-cond
341 { $description "Throws a " { $link no-cond } " error." }
342 { $error-description "Thrown by " { $link cond } " if none of the test quotations yield a true value. Some uses of " { $link cond } " include a default case where the test quotation is " { $snippet "[ t ]" } "; such a " { $link cond } " form will never throw this error." } ;
343
344 HELP: case
345 { $values { "obj" object } { "assoc" "a sequence of object/word, quotation pairs, with an optional quotation at the end" } }
346 { $description
347     "Compares " { $snippet "obj" } " against the first element of every pair, first evaluating the first element if it is a word. If some pair matches, removes " { $snippet "obj" } " from the stack and calls the second element of that pair, which must be a quotation."
348     $nl
349     "If there is no case matching " { $snippet "obj" } ", the default case is taken. If the last element of " { $snippet "assoc" } " is a quotation, the quotation is called with " { $snippet "obj" } " on the stack. Otherwise, a " { $link no-cond } " error is raised."
350     $nl
351     "The following two phrases are equivalent:"
352     { $code "{ { X [ Y ] } { Z [ T ] } } case" }
353     { $code "dup X = [ drop Y ] [ dup Z = [ drop T ] [ no-case ] if ] if" }
354 }
355 { $examples
356     { $example
357         "USING: combinators io kernel ;"
358         "IN: scratchpad"
359         "SYMBOLS: yes no maybe ;"
360         "maybe {"
361         "    { yes [ ] } ! Do nothing"
362         "    { no [ \"No way!\" throw ] }"
363         "    { maybe [ \"Make up your mind!\" print ] }"
364         "    [ \"Invalid input; try again.\" print ]"
365         "} case"
366         "Make up your mind!"
367     }
368 } ;
369
370 HELP: no-case
371 { $description "Throws a " { $link no-case } " error." }
372 { $error-description "Thrown by " { $link case } " if the object at the top of the stack does not match any case, and no default case is given." } ;
373
374 HELP: recursive-hashcode
375 { $values { "n" integer } { "obj" object } { "quot" { $quotation "( n obj -- code )" } } { "code" integer } }
376 { $description "A combinator used to implement methods for the " { $link hashcode* } " generic word. If " { $snippet "n" } " is less than or equal to zero, outputs 0, otherwise calls the quotation." } ;
377
378 HELP: cond>quot
379 { $values { "assoc" "a sequence of pairs of quotations" } { "quot" quotation } }
380 { $description "Creates a quotation that when called, has the same effect as applying " { $link cond } " to " { $snippet "assoc" } "."
381 $nl
382 "The generated quotation is more efficient than the naive implementation of " { $link cond } ", though, since it expands into a series of conditionals, and no iteration through " { $snippet "assoc" } " has to be performed." }
383 { $notes "This word is used behind the scenes to compile " { $link cond } " forms efficiently; it can also be called directly, which is useful for meta-programming." } ;
384
385 HELP: case>quot
386 { $values { "default" quotation } { "assoc" "a sequence of pairs of quotations" } { "quot" quotation } }
387 { $description "Creates a quotation that when called, has the same effect as applying " { $link case } " to " { $snippet "assoc" } "."
388 $nl
389 "This word uses three strategies:"
390 { $list
391     "If the assoc only has a few keys, a linear search is generated."
392     { "If the assoc has a large number of keys which form a contiguous range of integers, a direct dispatch is generated using the " { $link dispatch } " word together with a bounds check." }
393     "Otherwise, an open-coded hashtable dispatch is generated."
394 } } ;
395
396 HELP: distribute-buckets
397 { $values { "alist" "an alist" } { "initial" object } { "quot" { $quotation "( obj -- assoc )" } } { "buckets" "a new array" } }
398 { $description "Sorts the entries of " { $snippet "assoc" } " into buckets, using the quotation to yield a set of keys for each entry. The hashcode of each key is computed, and the entry is placed in all corresponding buckets. Each bucket is initially cloned from " { $snippet "initial" } "; this should either be an empty vector or a one-element vector containing a pair." }
399 { $notes "This word is used in the implementation of " { $link hash-case-quot } " and " { $link standard-combination } "." } ;
400
401 HELP: dispatch
402 { $values { "n" "a fixnum" } { "array" "an array of quotations" } }
403 { $description "Calls the " { $snippet "n" } "th quotation in the array." }
404 { $warning "This word is in the " { $vocab-link "kernel.private" } " vocabulary because it is an implementation detail used by the generic word system to accelerate method dispatch. It does not perform type or bounds checks, and user code should not need to call it directly." } ;