]> gitweb.factorcode.org Git - factor.git/blob - core/combinators/combinators-docs.factor
f8a23e179b0c59d50a475ebe2ab01835c4ccf793
[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 asterisk (" { $snippet "@" } ") suffixed to these words' names signifies that they are apply combinators."
62 $nl
63 "Two quotations:"
64 { $subsections bi@ 2bi@ }
65 "Three quotations:"
66 { $subsections tri@ 2tri@ }
67 "A pair of condition words built from " { $link bi@ } " to test two values:"
68 { $subsections both? either? }
69 "All of the apply combinators are equivalent to using the corresponding " { $link "spread-combinators" } " with the same quotation supplied for every value." ;
70
71 ARTICLE: "dip-keep-combinators" "Preserving combinators"
72 "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 underneath:"
73 { $subsections dip 2dip 3dip 4dip }
74 "The " { $snippet "keep" } " combinators invoke a quotation and restore some number of values to the top of the stack when it completes:"
75 { $subsections keep 2keep 3keep } ;
76
77 ARTICLE: "curried-dataflow" "Curried dataflow combinators"
78 "Curried cleave combinators:"
79 { $subsections bi-curry tri-curry }
80 "Curried spread combinators:"
81 { $subsections bi-curry* tri-curry* }
82 "Curried apply combinators:"
83 { $subsections bi-curry@ tri-curry@ }
84 { $see-also "dataflow-combinators" } ;
85
86 ARTICLE: "compositional-examples" "Examples of compositional combinator usage"
87 "Consider printing the same message ten times:"
88 { $code ": print-10 ( -- ) 10 [ \"Hello, world.\" print ] times ;" }
89 "if we wanted to abstract out the message into a parameter, we could keep it on the stack between iterations:"
90 { $code ": print-10 ( message -- ) 10 [ dup print ] times drop ;" }
91 "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:"
92 { $code ": subtract-n ( seq n -- seq' ) swap [ over - ] map nip ;" }
93 "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 } ":"
94 { $example
95   ": subtract-n ( seq n -- seq' ) [ - ] curry map ;"
96   "{ 10 20 30 } 5 subtract-n ."
97   "{ 5 15 25 }"
98 }
99 "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" } "."
100 $nl
101 "One way to write this is with a pair of " { $link swap } "s:"
102 { $code ": n-subtract ( n seq -- seq' ) swap [ swap - ] curry map ;" }
103 "Since this pattern comes up often, " { $link with } " encapsulates it:"
104 { $example
105   ": n-subtract ( n seq -- seq' ) [ - ] with map ;"
106   "30 { 10 20 30 } n-subtract ."
107   "{ 20 10 0 }"
108 }
109 { $see-also "fry.examples" } ;
110
111 ARTICLE: "compositional-combinators" "Compositional combinators"
112 "Certain combinators transform quotations to produce a new quotation."
113 { $subsections "compositional-examples" }
114 "Fundamental operations:"
115 { $subsections curry compose }
116 "Derived operations:"
117 { $subsections 2curry 3curry with prepose }
118 "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."
119 $nl
120 "Curried dataflow combinators can be used to build more complex dataflow by combining cleave, spread and apply patterns in various ways."
121 { $subsections "curried-dataflow" }
122 "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." ;
123
124 ARTICLE: "booleans" "Booleans"
125 "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."
126 { $subsections f t }
127 "A union class of the above:"
128 { $subsections boolean }
129 "There are some logical operations on booleans:"
130 { $subsections
131     >boolean
132     not
133     and
134     or
135     xor
136 }
137 "Boolean values are most frequently used for " { $link "conditionals" } "."
138 { $heading "The f object and f class" }
139 "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."
140 $nl
141 "Here is the " { $link f } " object:"
142 { $example "f ." "f" }
143 "Here is the " { $link f } " class:"
144 { $example "\\ f ." "POSTPONE: f" }
145 "They are not equal:"
146 { $example "f \\ f = ." "f" }
147 "Here is an array containing the " { $link f } " object:"
148 { $example "{ f } ." "{ f }" }
149 "Here is an array containing the " { $link f } " class:"
150 { $example "{ POSTPONE: f } ." "{ POSTPONE: f }" }
151 "The " { $link f } " object is an instance of the " { $link f } " class:"
152 { $example "USE: classes" "f class ." "POSTPONE: f" }
153 "The " { $link f } " class is an instance of " { $link word } ":"
154 { $example "USE: classes" "\\ f class ." "word" }
155 "On the other hand, " { $link t } " is just a word, and there is no class which it is a unique instance of."
156 { $example "t \\ t eq? ." "t" }
157 "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 imporant, there is usually an alternative word which can be used; for example, compare " { $link at } " with " { $link at* } "." ;
158
159 ARTICLE: "conditionals-boolean-equivalence" "Expressing conditionals with boolean logic"
160 "Certain simple conditional forms can be expressed in a simpler manner using boolean logic."
161 $nl
162 "The following two lines are equivalent:"
163 { $code "[ drop f ] unless" "swap and" }
164 "The following two lines are equivalent:"
165 { $code "[ ] [ ] ?if" "swap or" }
166 "The following two lines are equivalent, where " { $snippet "L" } " is a literal:"
167 { $code "[ L ] unless*" "L or" } ;
168
169 ARTICLE: "conditionals" "Conditional combinators"
170 "The basic conditionals:"
171 { $subsections if when unless }
172 "Forms abstracting a common stack shuffle pattern:"
173 { $subsections if* when* unless* }
174 "Another form abstracting a common stack shuffle pattern:"
175 { $subsections ?if }
176 "Sometimes instead of branching, you just need to pick one of two values:"
177 { $subsections ? }
178 "Two combinators which abstract out nested chains of " { $link if } ":"
179 { $subsections cond case }
180 { $subsections "conditionals-boolean-equivalence" }
181 { $see-also "booleans" "bitwise-arithmetic" both? either? } ;
182
183 ARTICLE: "dataflow-combinators" "Data flow combinators"
184 "Data flow 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."
185 { $subsections
186     "dip-keep-combinators"
187     "cleave-combinators"
188     "spread-combinators"
189     "apply-combinators"
190 }
191 "More intricate data flow can be constructed by composing " { $link "curried-dataflow" } "." ;
192
193 ARTICLE: "combinators-quot" "Quotation construction utilities"
194 "Some words for creating quotations which can be useful for implementing method combinations and compiler transforms:"
195 { $subsections cond>quot case>quot alist>quot } ;
196
197 ARTICLE: "call-unsafe" "Unsafe combinators"
198 "Unsafe calls declare an effect statically without any runtime checking:"
199 { $subsections call-effect-unsafe execute-effect-unsafe } ;
200
201 ARTICLE: "call" "Fundamental combinators"
202 "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."
203 $nl
204 { $heading "Compile-time checked combinators" }
205 "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" } "."
206 { $subsections call execute }
207 { $heading "Run-time checked combinators" }
208 "With these combinators, the stack effect of the expression is checked at run time."
209 { $subsections POSTPONE: call( POSTPONE: execute( }
210 "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:"
211 { $subsections call-effect execute-effect }
212 { $heading "Unchecked combinators" }
213 { $subsections "call-unsafe" }
214 { $see-also "effects" "inference" } ;
215
216 ARTICLE: "combinators" "Combinators"
217 "A central concept in Factor is that of a " { $emphasis "combinator" } ", which is a word taking code as input."
218 { $subsections
219     "call"
220     "dataflow-combinators"
221     "conditionals"
222     "looping-combinators"
223     "compositional-combinators"
224     "combinators.short-circuit"
225     "combinators.smart"
226     "combinators-quot"
227     "generalizations"
228 }
229 "More combinators are defined for working on data structures, such as " { $link "sequences-combinators" } " and " { $link "assocs-combinators" } "."
230 { $see-also "quotations" } ;
231
232 ABOUT: "combinators"
233
234 HELP: call-effect
235 { $values { "quot" quotation } { "effect" effect } }
236 { $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." }
237 { $examples
238   "The following two lines are equivalent:"
239   { $code
240     "call( a b -- c )"
241     "(( a b -- c )) call-effect"
242   }
243 } ;
244
245 HELP: execute-effect
246 { $values { "word" word } { "effect" effect } }
247 { $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." }
248 { $examples
249   "The following two lines are equivalent:"
250   { $code
251     "execute( a b -- c )"
252     "(( a b -- c )) execute-effect"
253   }
254 } ;
255
256 HELP: execute-effect-unsafe
257 { $values { "word" word } { "effect" effect } }
258 { $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." }
259 { $warning "If the word being executed has an incorrect stack effect, undefined behavior will result. User code should use " { $link POSTPONE: execute( } " instead." } ;
260     
261 { call-effect call-effect-unsafe execute-effect execute-effect-unsafe } related-words
262
263 HELP: cleave
264 { $values { "x" object } { "seq" "a sequence of quotations with stack effect " { $snippet "( x -- ... )" } } }
265 { $description "Applies each quotation to the object in turn." }
266 { $examples
267     "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:"
268     { $code
269         "! Equivalent"
270         "{ [ p ] [ q ] [ r ] [ s ] } cleave"
271         "[ p ] keep [ q ] keep [ r ] keep s"
272     }
273 } ;
274
275 HELP: 2cleave
276 { $values { "x" object } { "y" object }
277           { "seq" "a sequence of quotations with stack effect " { $snippet "( x y -- ... )" } } }
278 { $description "Applies each quotation to the two objects in turn." } ;
279
280 HELP: 3cleave
281 { $values { "x" object } { "y" object } { "z" object }
282           { "seq" "a sequence of quotations with stack effect " { $snippet "( x y z -- ... )" } } }
283 { $description "Applies each quotation to the three objects in turn." } ;
284
285 { bi tri cleave } related-words
286
287 HELP: spread
288 { $values { "objs..." "objects" } { "seq" "a sequence of quotations with stack effect " { $snippet "( x -- ... )" } } }
289 { $description "Applies each quotation to the object in turn." }
290 { $examples
291     "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:"
292     { $code
293         "! Equivalent"
294         "{ [ p ] [ q ] [ r ] [ s ] } spread"
295         "[ [ [ p ] dip q ] dip r ] dip s"
296     }
297 } ;
298
299 { bi* tri* spread } related-words
300
301 HELP: to-fixed-point
302 { $values { "object" object } { "quot" { $quotation "( object(n) -- object(n+1) )" } } { "object(n)" object } }
303 { $description "Applies the quotation repeatedly with " { $snippet "object" } " as the initial input until the output of the quotation equals the input." }
304 { $examples
305     { $example
306         "USING: combinators kernel math prettyprint sequences ;"
307         "IN: scratchpad"
308         ": flatten ( sequence -- sequence' )"
309         "    \"flatten\" over index"
310         "    [ [ 1 + swap nth ] [ nip dup 2 + ] [ drop ] 2tri replace-slice ] when* ;"
311         ""
312         "{ \"flatten\" { 1 { 2 3 } \"flatten\" { 4 5 } { 6 } } } [ flatten ] to-fixed-point ."
313         "{ 1 { 2 3 } 4 5 { 6 } }"
314     }
315 } ;
316
317 HELP: alist>quot
318 { $values { "default" "a quotation" } { "assoc" "a sequence of quotation pairs" } { "quot" "a new quotation" } }
319 { $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." }
320 { $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." } ;
321
322 HELP: cond
323 { $values { "assoc" "a sequence of quotation pairs and an optional quotation" } }
324 { $description
325     "Calls the second quotation in the first pair whose first quotation yields a true value. A single quotation will always yield a true value."
326     $nl
327     "The following two phrases are equivalent:"
328     { $code "{ { [ X ] [ Y ] } { [ Z ] [ T ] } } cond" }
329     { $code "X [ Y ] [ Z [ T ] [ no-cond ] if ] if" }
330 }
331 { $errors "Throws a " { $link no-cond } " error if none of the test quotations yield a true value." }
332 { $examples
333     { $code
334         "{"
335         "    { [ dup 0 > ] [ \"positive\" ] }"
336         "    { [ dup 0 < ] [ \"negative\" ] }"
337         "    [ \"zero\" ]"
338         "} cond"
339     }
340 } ;
341
342 HELP: no-cond
343 { $description "Throws a " { $link no-cond } " error." }
344 { $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." } ;
345
346 HELP: case
347 { $values { "obj" object } { "assoc" "a sequence of object/word,quotation pairs, with an optional quotation at the end" } }
348 { $description
349     "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."
350     $nl
351     "If there is no case matching " { $snippet "obj" } ", the default case is taken. If the last element of " { $snippet "cases" } " is a quotation, the quotation is called with " { $snippet "obj" } " on the stack. Otherwise, a " { $link no-cond } " error is rasied."
352     $nl
353     "The following two phrases are equivalent:"
354     { $code "{ { X [ Y ] } { Z [ T ] } } case" }
355     { $code "dup X = [ drop Y ] [ dup Z = [ drop T ] [ no-case ] if ] if" }
356 }
357 { $examples
358     { $code
359         "SYMBOL: yes  SYMBOL: no  SYMBOL: 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     }
367 } ;
368
369 HELP: no-case
370 { $description "Throws a " { $link no-case } " error." }
371 { $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." } ;
372
373 HELP: recursive-hashcode
374 { $values { "n" integer } { "obj" object } { "quot" { $quotation "( n obj -- code )" } } { "code" integer } }
375 { $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." } ;
376
377 HELP: cond>quot
378 { $values { "assoc" "a sequence of pairs of quotations" } { "quot" quotation } }
379 { $description  "Creates a quotation that when called, has the same effect as applying " { $link cond } " to " { $snippet "assoc" } "."
380 $nl
381 "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." }
382 { $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." } ;
383
384 HELP: case>quot
385 { $values { "default" quotation } { "assoc" "a sequence of pairs of quotations" } { "quot" quotation } }
386 { $description "Creates a quotation that when called, has the same effect as applying " { $link case } " to " { $snippet "assoc" } "."
387 $nl
388 "This word uses three strategies:"
389 { $list
390     "If the assoc only has a few keys, a linear search is generated."
391     { "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." }
392     "Otherwise, an open-coded hashtable dispatch is generated."
393 } } ;
394
395 HELP: distribute-buckets
396 { $values { "alist" "an alist" } { "initial" object } { "quot" { $quotation "( obj -- assoc )" } } { "buckets" "a new array" } }
397 { $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." }
398 { $notes "This word is used in the implemention of " { $link hash-case-quot } " and " { $link standard-combination } "." } ;
399
400 HELP: dispatch ( n array -- )
401 { $values { "n" "a fixnum" } { "array" "an array of quotations" } }
402 { $description "Calls the " { $snippet "n" } "th quotation in the array." }
403 { $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." } ;