{"article":{"slug":"factor-overview","title":"Factor Overview","subtitle":null,"summary":"John Benediktsson's code-forward tour of the Factor stack-based language for programmers new to concatenative languages, covering the stack, word definitions, quotations and combinators, sequences, tuples, generic words, vocabularies, errors and resource cleanup, macros, and common libraries such as JSON, regex, and HTTP.","content_type":"tutorial","language":"en","canonical_url":"https://re.factorcode.org/2026/10/factor-overview.html","author":{"name":"John Benediktsson","url":"https://re.factorcode.org/","person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"Re: Factor","url":"https://re.factorcode.org/","listing_slug":null,"listing":null},"topics":[{"name":"Programming","slug":"programming","url":"https://listedarticles.com/topics/programming"},{"name":"Tutorials","slug":"tutorials","url":"https://listedarticles.com/topics/tutorials"},{"name":"Open Source","slug":"open-source","url":"https://listedarticles.com/topics/open-source"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":4819,"reading_minutes":21,"published_at":"2026-10-04T00:00:00.000Z","added_at":"2026-10-05T14:28:38.344Z","updated_at":"2026-10-05T14:28:38.344Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/factor-overview","markdown_url":"https://listedarticles.com/articles/factor-overview.md","example":false,"citation":"John Benediktsson, Re: Factor. \"Factor Overview.\" 4 Oct 2026. https://re.factorcode.org/2026/10/factor-overview.html (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://re.factorcode.org/2026/10/factor-overview.html"},"body_markdown":"# Factor Overview\n\nI highly recommend reading the [guided tour of Factor](https://docs.factorcode.org/content/article-tour.html).\nIt provides a great introduction to the language and libraries of [Factor](https://factorcode.org).\nEven still, I sometimes have also wanted to have more code-forward examples of everyday syntax,\ncontrol flow, combinators, and some of the main libraries. This is that overview. It assumes you have programmed before, but have not necessarily used a\nstack-based language.\n\n### Hello, world\n\nThe simplest [Hello, world](https://en.wikipedia.org/wiki/Hello,_world) is just:\n\n```\n\"Hello, world!\" print\n```\nYou can run that from [the listener](https://docs.factorcode.org/content/article-listener.html):\n\n```\nIN: scratchpad \"Hello, world!\" print\nHello, world!\n```\nAnd you can run it from the command-line:\n\n```\n$ ./factor -e=\"\\\"Hello, world!\\\" print\"\nHello, world!\n```\nOf course, you can also make this a file named `hello.factor`, which\ndefines a `hello` vocabulary (something you learn about in the\n[your first program](https://docs.factorcode.org/content/article-first-program.html) tutorial).\n\n```\nUSING: io ;\nIN: hello\n: main ( -- )\n    \"Hello, world!\" print ;\nMAIN: main\n```\nThe [syntax](https://docs.factorcode.org/content/article-syntax.html) used above includes:\n\n- [`USING:`](https://docs.factorcode.org/content/word-USING__colon__%2Csyntax.html) imports vocabularies (named collections of words)\n- [`IN:`](https://docs.factorcode.org/content/word-IN__colon__%2Csyntax.html) selects the vocabulary for definitions, and\n- [`MAIN:`](https://docs.factorcode.org/content/word-MAIN__colon__%2Csyntax.html) sets an entry point.\n\nAnd then you can run it either as a script:\n\n```\n$ ./factor hello.factor\nHello, world!\n```\nOr, if this is available in the [vocabulary roots](https://docs.factorcode.org/content/article-vocabs.roots.html)\nsearch path, run the vocabulary’s main word:\n\n```\n$ ./factor -run=hello\nHello, world!\n```\nFor the rest of this overview, try the examples in the *listener*, Factor’s\n[interactive REPL](https://docs.factorcode.org/content/article-listener.html).\nStart the terminal listener with `./factor -run=listener`,\nor use the graphical listener in the development environment. Each example\nincludes its imports; examples that build on a definition assume you have\nentered that definition too. [`IN: scratchpad`](https://docs.factorcode.org/content/word-IN__colon__%2Csyntax.html) puts experimental definitions\nin the listener’s usual working vocabulary. Feel free to paste the code\ndirectly, to see what it does. Comments beginning with `!` are part of\nvalid Factor source.\n\nFor a quick start, work through the stack, word definitions, quotations, control flow, and sequences. The later sections introduce objects, metaprogramming, and libraries that you can return to as you need them.\n\n### Values and the stack\n\n[Literals](https://docs.factorcode.org/content/article-literals.html) push values onto the data stack. Words consume inputs from the top\nof that stack and push their outputs. Code runs from left to right:\n\n```\nUSING: math prettyprint ;\n2 3 + .                         ! 5\n10 4 - .                        ! 6\n2 3 + 4 * .                     ! 20\n```\n[`.`](https://docs.factorcode.org/content/word-.%2Cprettyprint.html) consumes and prints an object. [`print`](https://docs.factorcode.org/content/word-print%2Cio.html) consumes and prints a string.\nThe comments beside examples show the output. Because printing removes the\nvalue, these examples leave the stack empty unless stated otherwise.\nThere are no parentheses around function arguments: put the arguments on\nthe stack, then invoke the word. Below, the top of the stack is on the right:\n\n```\nCode       Stack\n2          2\n3          2 3\n+          5\n4          5 4\n*          20\n.          (empty)\n```\nSpaces matter. `2 3 +` is three tokens; `2+3` is a single token, which would\nneed to be the name of a word. Names like [`number>string`](https://docs.factorcode.org/content/word-number__gt__string%2Cmath.parser.html), [`empty?`](https://docs.factorcode.org/content/word-empty__que__%2Csequences.html), and\n[`set-at`](https://docs.factorcode.org/content/word-set-at%2Cassocs.html) are ordinary word names. A trailing `?` conventionally marks a\npredicate; `>` often appears in conversion names. Those characters are part\nof the name, not separate operators. A trailing `!` often marks a mutating\nvariant, such as [`append!`](https://docs.factorcode.org/content/word-append%21%2Csequences.html); `*` usually marks an alternative form. There are some\n[conventions](https://docs.factorcode.org/content/article-conventions.html) useful\nfor learning word and type naming.\n\n### Comments and literals\n\n```\nUSING: math multiline prettyprint ;\n! A comment runs to the end of the line.\n/* A block comment can span\n   several lines. */\n42 .                            ! Integer\n-17 .                           ! Negative integer\n0xff .                          ! 255, hexadecimal\n0b1010 .                        ! 10, binary\n3/4 .                           ! Exact rational\n1.25 .                          ! Floating point\nC{ 2 3 } .                      ! Complex number: 2 + 3i\nt .                             ! True\nf .                             ! False\n\"hello\\nworld\" .                ! String with an escape\nCHAR: A .                       ! 65, a character code point\n{ 1 2 3 } .                     ! Array\nV{ 1 2 3 } .                    ! Growable vector\nB{ 0 127 255 } .                ! Byte array\nH{ { \"name\" \"Ada\" } } .         ! Hashtable\n[ 1 + ] .                       ! Quotation: code as a value\n```\nArrays and quotations contain objects without executing them. Collection\nliterals are useful for fixed data; when mutating one inside a word, use\n[`clone`](https://docs.factorcode.org/content/word-clone%2Ckernel.html) to obtain a fresh copy rather than changing a shared literal.\nThis is a shallow copy: objects inside the collection are still shared.\n\nBlock comments come from the [`multiline`](https://docs.factorcode.org/content/vocab-multiline.html) vocabulary.\n\n[`CHAR:`](https://docs.factorcode.org/content/word-CHAR__colon__%2Csyntax.html) produces an integer code point; Factor has no separate character\ntype. `{ ... }` is an array, while `[ ... ]` is executable code held as a\nvalue called a [quotation](https://docs.factorcode.org/content/article-quotations.html).\nSpaces separate the literal openers, their contents, and the closing\ndelimiters, as in `{ 1 2 3 }` and `[ 1 + ]`.\n\n### Strings and escape characters\n\nString literals use double quotes. A backslash introduces a\n[character escape](https://docs.factorcode.org/content/article-escape.html):\n\n| Escape | Meaning | \n|---|---|\n| `\\\"` | Double quote | \n| `\\\\` | Backslash | \n| `\\a` | Bell (code point 7) | \n| `\\b` | Backspace (8) | \n| `\\e` | Escape (27) | \n| `\\f` | Form feed (12) | \n| `\\n` | Newline (10) | \n| `\\r` | Carriage return (13) | \n| `\\s` | Space (32) | \n| `\\t` | Tab (9) | \n| `\\v` | Vertical tab (11) | \n| `\\0` | Null (0) | \n| `\\ooo` | Code point given by one to three octal digits | \n| `\\xHH` | Code point given by exactly two hexadecimal digits | \n| `\\uHHHHHH` | Code point given by exactly six hexadecimal digits | \n| `\\u{H...}` | Code point given by hexadecimal digits inside braces | \n| `\\u{name}` | Named Unicode character, with Unicode support loaded | \n\nFor example:\n\n```\nUSING: io prettyprint sequences unicode ;\n\"She said \\\"hello\\\".\" print        ! She said \"hello\".\n\"C:\\\\Users\\\\Ada\" print             ! C:\\Users\\Ada\n\"\\x41\\u000042\\u{43}\" print         ! ABC\n\"\\u{greek-small-letter-pi}\" print  ! π\n\"first\\nsecond\" print              ! Prints two lines\n\"\\t\" length .                      ! 1: the escape represents one character\n\"hello\" length .                   ! 5\n\"hello\" >upper .                   ! \"HELLO\"\n\"a,b,c\" \",\" split .                ! { \"a\" \"b\" \"c\" }\n{ \"a\" \"b\" \"c\" } \", \" join .        ! \"a, b, c\"\n\"42\" string>number .               ! 42\n42 number>string .                 ! \"42\"\n\"oops\" string>number .             ! f\n```\nThe six-digit `\\u` form differs from languages that use four digits; the\nbraced form is often easier to read. Unknown escapes are errors. Strings\ncan also span source lines directly: an actual newline becomes part of the\nstring. A backslash immediately before a source newline continues the\nstring without including that newline. A backslash followed by a literal\nspace also represents a space, like `\\s`.\n\n*Note: the length of a [string](https://docs.factorcode.org/content/article-strings.html)\nis the number of code points, not the number of visible glyphs. You can learn a bit more\nby reading about Factor’s [Unicode](https://re.factorcode.org/2023/05/unicode.html) support.*\n\n### Stack shuffling\n\nTypical of [concatenative languages](https://concatenative.org/wiki/view/Concatenative%20language),\nthe stack is a data structure with it’s own access patterns that we often call\n[stack shuffling](https://docs.factorcode.org/content/article-tour-stack-shuffling.html).\n\n```\nUSING: kernel prettyprint ;\n10 dup . .                      ! Prints 10, then 10\n10 20 swap . .                  ! Prints 10, then 20\n10 20 over . . .                ! Prints 10, then 20, then 10\n10 20 nip .                     ! 20: discard the second item\n10 20 drop .                    ! 10: discard the top item\n```\nThe usual [stack shuffling words](https://docs.factorcode.org/content/article-shuffle-words.html) have these effects:\n\n```\n! dup   ( x -- x x )\n! drop  ( x -- )\n! swap  ( x y -- y x )\n! over  ( x y -- x y x )\n! nip   ( x y -- y )\n! rot   ( x y z -- y z x )\n```\nMost Factor code uses short definitions and combinators to keep explicit shuffling to a minimum.\n\nIn a stack effect, inputs and outputs run from left to right, with the\ntopmost value last. [`swap`](https://docs.factorcode.org/content/word-swap%2Ckernel.html) therefore changes a stack ending in `x y` into\none ending in `y x`; values below those inputs are untouched. Repeated\n[`.`](https://docs.factorcode.org/content/word-.%2Cprettyprint.html) calls print the topmost result first.\n\n### Defining words\n\nYou can create [words](https://docs.factorcode.org/content/article-words.html) that\ncontain code that is executed when called:\n\n```\nUSING: kernel math prettyprint ;\nIN: scratchpad\n: square ( n -- n-squared ) dup * ;\n: neighbors ( n -- below above )\n    dup 1 - swap 1 + ;\n5 square .                      ! 25\n5 neighbors . .                 ! Prints 6, then 4\nCONSTANT: answer 42\nanswer .                        ! 42\n```\n[`:`](https://docs.factorcode.org/content/article-colon-definition.html) begins a definition and [`;`](https://docs.factorcode.org/content/word-%3B%2Csyntax.html) ends it. The [stack effect](https://docs.factorcode.org/content/article-effects.html) `( inputs -- outputs )` documents how many values the word consumes and produces. Its\nnames describe the values; they do not bind variables or specify types.\nThe compiler checks stack effects, including compatible effects for branches.\nWords can return several values simply by leaving them on the stack.\nThere is no explicit `return`: execution finishes at the end of the word.\n\n[`ALIAS: new-name existing-word`](https://docs.factorcode.org/content/word-ALIAS__colon__%2Csyntax.html) defines another name for a word.\n\n### Arithmetic and comparisons\n\nLots of [arithmetic](https://docs.factorcode.org/content/article-arithmetic.html) is\navailable for computing with [numbers](https://docs.factorcode.org/content/article-numbers.html):\n\n```\nUSING: kernel math math.functions math.order prettyprint ;\n7 2 / .                         ! 3+1/2, an exact rational\n7 2 /i .                        ! 3, integer division\n7 2 mod .                       ! 1\n2 10 ^ .                        ! 1024\n9 sqrt .                        ! 3.0\n-5 abs .                        ! 5\n3 8 min .                       ! 3\n3 8 max .                       ! 8\n2 3 < .                         ! t\n2 3 >= .                        ! f\n\"hello\" \"hello\" = .             ! t, value equality\n```\n[Integers](https://docs.factorcode.org/content/article-integers.html) grow beyond machine size automatically, and division of integers\ncan produce [exact ratios](https://docs.factorcode.org/content/article-rationals.html). Use floating-point inputs when you want\nfloating-point arithmetic.\n\nBitwise operations have their own names, separate from boolean logic:\n\n```\nUSING: math prettyprint ;\n0b1100 0b1010 bitand .          ! 8\n0b1100 0b1010 bitor .           ! 14\n0b1100 0b1010 bitxor .          ! 6\n1 3 shift .                     ! 8: shift left\n8 -1 shift .                    ! 4: shift right\n```\n### Quotations\n\nSquare brackets produce a [quotation](https://docs.factorcode.org/content/article-quotations.html). [`call`](https://docs.factorcode.org/content/word-call,kernel.html) executes it:\n\n```\nUSING: kernel math prettyprint sequences ;\n5 [ 1 + ] call .                ! 6\n{ 1 2 3 } [ 2 * ] map .         ! { 2 4 6 }\n```\nQuotations can be passed to words, returned from words, and stored in\ncollections. Words that take quotations are called\n[*combinators*](https://docs.factorcode.org/content/article-combinators.html).\n\n### Booleans and conditionals\n\nIn [boolean tests](https://docs.factorcode.org/content/article-booleans.html), only [`f`](https://docs.factorcode.org/content/word-f%2Csyntax.html) is false. Zero, an empty string, and an empty array are all true.\n\n```\nUSING: kernel math prettyprint ;\nt f and .                        ! f\nt f or .                         ! t\nf not .                          ! t\n3 2 > [ \"yes\" ] [ \"no\" ] if .    ! \"yes\"\n0 [ \"truthy\" ] [ \"false\" ] if .  ! \"truthy\"\nt [ \"runs\" . ] when\nf [ \"runs too\" . ] unless\n```\n[`if`](https://docs.factorcode.org/content/word-if,kernel.html) consumes a condition and two quotations. It calls the first quotation\nfor a true condition and the second for [`f`](https://docs.factorcode.org/content/word-f%2Csyntax.html). [`when`](https://docs.factorcode.org/content/word-when%2Ckernel.html) and [`unless`](https://docs.factorcode.org/content/word-unless%2Ckernel.html) take one\nquotation. These are words that operate on code values, just like [`+`](https://docs.factorcode.org/content/word-%2B%2Cmath.html)\noperates on numbers.\n\nFor several alternatives, use [`cond` or `case`](https://docs.factorcode.org/content/article-conditionals.html):\n\n```\nUSING: combinators kernel math prettyprint ;\nIN: scratchpad\n: sign-name ( n -- string )\n    {\n        { [ dup 0 < ] [ drop \"negative\" ] }\n        { [ dup 0 = ] [ drop \"zero\" ] }\n        [ drop \"positive\" ]\n    } cond ;\n-3 sign-name .                  ! \"negative\"\n: color-name ( color -- string )\n    {\n        { \"r\" [ \"red\" ] }\n        { \"g\" [ \"green\" ] }\n        [ drop \"unknown\" ]\n    } case ;\n\"g\" color-name .                ! \"green\"\n```\n[`cond`](https://docs.factorcode.org/content/word-cond%2Ccombinators.html) tries predicate quotations in order. [`case`](https://docs.factorcode.org/content/word-case%2Ccombinators.html) compares an input with\neach key; a matching branch consumes the key automatically, while the\ndefault branch receives the unmatched input.\n\n[`and`](https://docs.factorcode.org/content/word-and%2Ckernel.html) and [`or`](https://docs.factorcode.org/content/word-or%2Ckernel.html) combine values that have already been computed. For\n[short-circuit evaluation](https://docs.factorcode.org/content/article-combinators.short-circuit.html), pass predicate quotations instead:\n\n```\nUSING: combinators.short-circuit kernel math prettyprint ;\n5 { [ 0 > ] [ 10 < ] } 1&& .    ! t: positive and less than ten\n-5 { [ 0 < ] [ 10 > ] } 1|| .   ! t: negative or greater than ten\n```\nEach predicate receives the same input. [`1&&`](https://docs.factorcode.org/content/word-1%26%26%2Ccombinators.short-circuit.html) stops at the first false\nresult; [`1||`](https://docs.factorcode.org/content/word-1__pipe____pipe__%2Ccombinators.short-circuit.html) stops at the first true result. The leading number is the\nnumber of inputs passed to each predicate.\n\n### Keeping and hiding values\n\nThe [`dip`](https://docs.factorcode.org/content/word-dip,kernel.html) word temporarily hides a value while a quotation works on the stack below\nit. [`keep`](https://docs.factorcode.org/content/word-keep,kernel.html) gives a quotation a value and also preserves that value:\n\n```\nUSING: kernel math prettyprint ;\n10 20 [ 1 + ] dip + .           ! 31: increment 10, then restore 20\n5 [ 1 + ] keep . .              ! Prints 5, then 6\n```\n```\n! dip   ( ..a x quot -- ..b x )\n! keep  ( ..a x quot -- ..b x )\n```\nThe overall shapes look alike, but `dip` hides `x` from the quotation and\n`keep` passes it in. [`2dip`](https://docs.factorcode.org/content/word-2dip%2Ckernel.html) hides two values; [`2keep`](https://docs.factorcode.org/content/word-2keep%2Ckernel.html) preserves two inputs.\n\n### Applying several quotations\n\nThe [`bi` family](https://docs.factorcode.org/content/article-cleave-combinators.html) covers several common ways to distribute inputs:\n\n```\nUSING: kernel math prettyprint ;\n! Apply two quotations to the same input.\n5 [ 1 + ] [ 2 * ] bi . .        ! Prints 10, then 6\n! Apply one quotation to each of two inputs.\n3 4 [ 2 * ] bi@ . .             ! Prints 8, then 6\n! Apply separate quotations to separate inputs.\n3 4 [ 1 + ] [ 2 * ] bi* . .     ! Prints 8, then 4\n! Apply two quotations to the same pair of inputs.\n3 4 [ + ] [ * ] 2bi . .         ! Prints 12, then 7\n```\nFor example, [`2bi`](https://docs.factorcode.org/content/word-2bi%2Ckernel.html) lets a word calculate two results from the same inputs:\n\n```\nUSING: kernel math prettyprint ;\nIN: scratchpad\n: sum-and-product ( a b -- sum product )\n    [ + ] [ * ] 2bi ;\n3 4 sum-and-product . .         ! Prints 12, then 7\n```\nThen [`tri`](https://docs.factorcode.org/content/word-tri%2Ckernel.html), [`tri@`](https://docs.factorcode.org/content/word-tri__at__%2Ckernel.html), and [`tri*`](https://docs.factorcode.org/content/word-tri__star__%2Ckernel.html) extend these patterns to three quotations or\ninputs.\n\nYou can find [`cleave`](https://docs.factorcode.org/content/word-cleave%2Ccombinators.html), [`napply`](https://docs.factorcode.org/content/word-napply%2Cgeneralizations.html) and [`spread`](https://docs.factorcode.org/content/word-spread%2Ccombinators.html) as the generalizations\nof those patterns.\n\n### Partial application and composition\n\nThe [`curry`](https://docs.factorcode.org/content/word-curry,kernel.html) word binds a value to the beginning of a quotation.\n[`compose`](https://docs.factorcode.org/content/word-compose,kernel.html) joins two\nquotations so that one runs after the other:\n\n```\nUSING: kernel math prettyprint sequences ;\n{ 1 2 3 } 10 [ + ] curry map .    ! { 11 12 13 }\n5 [ 1 + ] [ 2 * ] compose call .  ! 12\n```\n`10 [ + ] curry` behaves like `[ 10 + ]`. This is a convenient way to build\na quotation using a value computed at runtime.\n\nThe [`fry` vocabulary](https://docs.factorcode.org/content/article-fry.html) provides quotation templates. [`_`](https://docs.factorcode.org/content/word-_%2Csyntax.html) inserts a value;\n[`@`](https://docs.factorcode.org/content/word-__at__%2Csyntax.html) inserts a call to a supplied quotation:\n\n```\nUSING: fry kernel math prettyprint sequences ;\n{ 1 2 3 } 10 '[ _ + ] map .     ! { 11 12 13 }\n5 [ 1 + ] '[ @ 2 * ] call .     ! 12\n```\nThe apostrophe in `'[ ... ]` makes this a template rather than an ordinary\nquotation. Its placeholders consume their values when the template is\nconstructed, not when the resulting quotation is called.\n\n### Defining combinators\n\nA combinator can be an ordinary word with quotation inputs. Give those\ninputs their own [stack effects](https://docs.factorcode.org/content/article-inference-combinators.html) and declare the word [`inline`](https://docs.factorcode.org/content/word-inline%2Csyntax.html) so the\ncompiler can infer the effects at its call sites:\n\n```\nUSING: kernel math prettyprint ;\nIN: scratchpad\n: twice ( ... quot: ( ... -- ... ) -- ... )\n    dup [ call ] dip call ; inline\n3 [ 2 * ] twice .               ! 12\n```\nThe `...` represents values carried through the combinator. Here, the\nsupplied quotation must preserve stack height, and `twice` calls it twice.\n\n### Loops and recursion\n\n```\nUSING: kernel math prettyprint sequences ;\n3 [ \"hello\" . ] times           ! Print three times\n{ \"Ada\" \"Grace\" } [ . ] each    ! Visit each element\n5 <iota> [ . ] each             ! Print 0 through 4\n0 [ dup 3 < ] [ dup . 1 + ] while drop\n! Print 0, 1, 2; keep the counter on the stack\n```\nThe [looping combinator](https://docs.factorcode.org/content/article-looping-combinators.html) [`while`](https://docs.factorcode.org/content/word-while%2Ckernel.html) calls its predicate before each iteration. The predicate leaves\na condition; the body updates the loop’s values. [`until`](https://docs.factorcode.org/content/word-until%2Ckernel.html) reverses the\ncondition. Often [`each`](https://docs.factorcode.org/content/word-each%2Csequences.html), [`map`](https://docs.factorcode.org/content/word-map%2Csequences.html), or [`reduce`](https://docs.factorcode.org/content/word-reduce%2Csequences.html) expresses the loop directly.\n\nRecursion uses an ordinary call to the word being defined:\n\n```\nUSING: kernel math prettyprint ;\nIN: scratchpad\n: factorial ( n -- n! )\n    dup 1 <=\n    [ drop 1 ]\n    [ dup 1 - factorial * ] if ;\n5 factorial .                   ! 120\n```\nDefinitions are read in order: define helper words before words that use\nthem. [`DEFER:`](https://docs.factorcode.org/content/article-deferred.html)\ndeclares a word before its implementation, allowing mutual recursion:\n\n```\nUSING: kernel math prettyprint ;\nIN: scratchpad\nDEFER: odd-count?\n: even-count? ( n -- ? )\n    dup 0 = [ drop t ] [ 1 - odd-count? ] if ;\n: odd-count? ( n -- ? )\n    dup 0 = [ drop f ] [ 1 - even-count? ] if ;\n6 even-count? .                 ! t\n7 odd-count? .                  ! t\n```\nThese examples accept nonnegative integers. Factor guarantees\n[tail-call optimization](https://docs.factorcode.org/content/article-tail-call-opt.html),\nso a final call such as the one to `odd-count?` can continue without growing\nthe call stack.\n\n### Local variables and closures\n\nWhen names make an algorithm easier to read, import\n[`locals`](https://docs.factorcode.org/content/article-locals.html) and define\na word with [`::`](https://docs.factorcode.org/content/word-__colon____colon__%2Csyntax.html). Inputs become lexical variables:\n\n```\nUSING: kernel locals math prettyprint sequences ;\nIN: scratchpad\n:: rectangle-area ( width height -- area )\n    width height * ;\n:: add-offset ( seq offset -- newseq )\n    seq [| n | n offset + ] map ;\n3 4 rectangle-area .            ! 12\n{ 1 2 3 } 10 add-offset .       ! { 11 12 13 }\n:: hypotenuse-squared ( a b -- n )\n    a a * :> a-squared\n    b b * :> b-squared\n    a-squared b-squared + ;\n```\n[`:>`](https://docs.factorcode.org/content/word-__colon____gt__%2Csyntax.html) binds a computed value. [`\\[| n | ... \\]`](https://docs.factorcode.org/content/word-%5B__pipe__%2Csyntax.html) names quotation inputs and can\ncapture enclosing variables, as `offset` does above. Output names in [`::`](https://docs.factorcode.org/content/word-__colon____colon__%2Csyntax.html)\nstill describe stack results; there is no implicit return variable.\n\n[Mutable locals](https://docs.factorcode.org/content/article-locals-mutable.html) have an exclamation point in their declaration and an\nassociated setter:\n\n```\nUSING: kernel locals math prettyprint ;\n[let\n    0 :> total!\n    5 [ total 1 + total! ] times\n    total .                     ! 5\n]\n```\n[`\\[let ... \\]`](https://docs.factorcode.org/content/word-%5Blet%2Csyntax.html) establishes a lexical scope, including in the listener.\n\n### Sequences\n\nArrays, vectors, strings, and several other types share the sequence\n[protocol](https://docs.factorcode.org/content/article-sequence-protocol.html). Most sequence words work across these types:\n\n```\nUSING: kernel math prettyprint sequences sorting ;\n{ 10 20 30 } length .               ! 3\n{ 10 20 30 } first .                ! 10\n1 { 10 20 30 } nth .                ! 20, zero-based indexing\n{ 1 2 } { 3 4 } append .            ! { 1 2 3 4 }\n{ 1 2 3 } reverse .                 ! { 3 2 1 }\n{ 1 2 3 4 } [ dup * ] map .         ! { 1 4 9 16 }\n{ 1 2 3 4 } [ 2 mod 0 = ] filter .  ! { 2 4 }\n{ 1 2 3 4 } 0 [ + ] reduce .        ! 10\n{ 1 2 3 } [ 0 > ] all? .            ! t\n{ 1 2 3 } [ 2 = ] any? .            ! t\n{ 3 1 2 } natural-sort .            ! { 1 2 3 }\nV{ 1 2 } clone\n3 over push .                       ! V{ 1 2 3 }\n```\nThe [sequence combinator](https://docs.factorcode.org/content/article-sequences-combinators.html) [`map`](https://docs.factorcode.org/content/word-map%2Csequences.html) collects quotation results; [`each`](https://docs.factorcode.org/content/word-each%2Csequences.html) is for side effects. [`reduce`](https://docs.factorcode.org/content/word-reduce%2Csequences.html)\nthreads an accumulator through the sequence. [`push`](https://docs.factorcode.org/content/word-push%2Csequences.html) mutates a growable\nsequence and consumes both the new element and the sequence.\n\nFor incremental construction, [`make`](https://docs.factorcode.org/content/article-namespaces-make.html)\ncollects values produced inside a quotation. [`,`](https://docs.factorcode.org/content/word-__comma__%2Cmake.html) adds one element and [`%`](https://docs.factorcode.org/content/word-__percent__%2Cmake.html)\nadds the elements of a sequence:\n\n```\nUSING: make prettyprint ;\n[ 1 , { 2 3 } % 4 , ] { } make .            ! { 1 2 3 4 }\n[ \"Hello\" % CHAR: \\s , \"Ada\" % ] \"\" make .  ! \"Hello Ada\"\n```\nThe final exemplar (`{ }` or `\"\"`) chooses the result type. Prefer [`map`](https://docs.factorcode.org/content/word-map%2Csequences.html),\n[`filter`](https://docs.factorcode.org/content/word-filter%2Csequences.html), or [`append`](https://docs.factorcode.org/content/word-append%2Csequences.html) when one of those directly expresses the operation.\n\n[`Specialized arrays`](https://docs.factorcode.org/content/article-specialized-arrays.html)\nstore elements as C numeric types in contiguous memory while supporting\nthe sequence protocol:\n\n```\nUSING: alien.c-types prettyprint sequences specialized-arrays ;\nSPECIALIZED-ARRAY: double\ndouble-array{ 1.0 2.0 3.0 } length .  ! 3\n```\n### Hashtables and sets\n\nAssociative collections use the [`assocs` protocol](https://docs.factorcode.org/content/article-assocs.html):\n\n```\nUSING: assocs kernel prettyprint ;\n\"Ada\" H{ { \"Ada\" 36 } { \"Grace\" 85 } } at .  ! 36\n\"missing\" H{ { \"Ada\" 36 } } at .             ! f\n\"enabled\" H{ { \"enabled\" f } } at* . .       ! Prints t, then f\nH{ { \"Ada\" 36 } } clone\n37 \"Ada\" pick set-at\n\"Ada\" swap at .                              ! 37\n```\n[`at*`](https://docs.factorcode.org/content/word-at__star__%2Cassocs.html) returns a presence flag as well as a value, distinguishing a missing\nkey from a key whose value is [`f`](https://docs.factorcode.org/content/word-f%2Csyntax.html). [`set-at`](https://docs.factorcode.org/content/word-set-at%2Cassocs.html) takes a value, key, and assoc.\n\n[Sets](https://docs.factorcode.org/content/article-sets.html) also have a protocol, with useful operations on ordinary sequences:\n\n```\nUSING: prettyprint sets ;\n{ 1 2 2 3 } members .           ! { 1 2 3 }\n2 { 1 2 3 } in? .               ! t\n{ 1 2 } { 2 3 } union .         ! { 1 2 3 }\n{ 1 2 } { 2 3 } intersect .     ! { 2 }\n{ 1 2 } { 2 3 } diff .          ! { 1 }\n```\nFor repeated membership checks, use a hash set rather than scanning a sequence:\n\n```\nUSING: hash-sets prettyprint sets ;\n2 HS{ 1 2 3 } in? .             ! t\n```\n### Tuples and accessors\n\n[Tuples](https://docs.factorcode.org/content/article-tuples.html) define classes with named slots. [`boa`](https://docs.factorcode.org/content/word-boa%2Ckernel.html) constructs a tuple from\nslot values in declaration order:\n\n```\nUSING: accessors kernel prettyprint ;\nIN: scratchpad\nTUPLE: person name age ;\nC: <person> person\n\"Ada\" 36 <person>\ndup name>> .                    ! \"Ada\"\n37 >>age\nage>> .                         ! 37\n```\n[`C:`](https://docs.factorcode.org/content/word-C__colon__%2Csyntax.html) defines a constructor using [`boa`](https://docs.factorcode.org/content/word-boa%2Ckernel.html). [`name>>`](https://docs.factorcode.org/content/article-accessors.html) reads a slot; [`>>age`](https://docs.factorcode.org/content/article-accessors.html)\nwrites a slot and returns the tuple, allowing chained updates. You can also\nconstruct an instance with `person new` and set its slots explicitly.\nNames such as `<person>` conventionally denote constructors; the angle\nbrackets are part of the word’s name.\n\nTuple literals use [`T{ ... }`](https://docs.factorcode.org/content/word-T%7B%2Csyntax.html). Slots can also declare a class, an initial\nvalue, or the [`read-only`](https://docs.factorcode.org/content/word-read-only%2Csyntax.html) attribute:\n\n```\nUSING: accessors kernel math prettyprint ;\nIN: scratchpad\nT{ person { name \"Grace\" } { age 85 } } name>> .  ! \"Grace\"\nTUPLE: counter { value integer initial: 0 } ;\ncounter new\n[ 1 + ] change-value\nvalue>> .                                         ! 1\n```\n[`Slot declarations`](https://docs.factorcode.org/content/article-tuple-declarations.html)\nconstrain stored values. `{ name string read-only }`, for example, declares\na string slot that is initialized at construction and has no generated\nsetter. [`change-value`](https://docs.factorcode.org/content/article-accessors.html) applies a quotation to the current slot value,\nstores the result, and returns the tuple.\n\n### Structs and C layouts\n\n[`STRUCT:`](https://docs.factorcode.org/content/article-classes.struct.html)\ndefines a record backed by a C memory layout. Every field declares a C\ntype, and the usual slot accessors work on struct instances:\n\n```\nUSING: accessors alien.c-types classes.struct kernel prettyprint ;\nIN: scratchpad\nSTRUCT: c-point\n    { x double }\n    { y double } ;\n3.0 4.0 c-point boa\ndup x>> .                       ! 3.0\ny>> .                           ! 4.0\nPACKED-STRUCT: packet-header\n    { kind uint8_t }\n    { length uint32_t } ;\npacket-header heap-size .       ! 5\n```\n[`boa`](https://docs.factorcode.org/content/word-boa%2Ckernel.html) initializes fields from stack values; `c-point <struct>` creates an\ninstance with its declared initial field values. These constructors use\ngarbage-collected storage. [`STRUCT:`](https://docs.factorcode.org/content/word-STRUCT__colon__%2Cclasses.struct.html) includes alignment padding according\nto the platform’s C layout rules. [`PACKED-STRUCT:`](https://docs.factorcode.org/content/word-PACKED-STRUCT__colon__%2Cclasses.struct.html) removes padding between\nfields and at the end, for layouts that explicitly require packed storage.\nIt does not choose byte order.\n\n[`UNION-STRUCT:`](https://docs.factorcode.org/content/word-UNION-STRUCT__colon__%2Cclasses.struct.html) defines overlapping C fields that share the same storage.\nIt serves a different purpose from [`UNION:`](https://docs.factorcode.org/content/word-UNION__colon__%2Csyntax.html), which groups Factor classes.\nUse tuples for ordinary Factor records and structs when you need C-compatible\nmemory or an explicitly specified binary layout.\n\n### Generic words and classes\n\nA [generic word](https://docs.factorcode.org/content/article-generic.html) chooses a method based on the class of its topmost input.\nThis example reuses `person` and `<person>` from “Tuples and accessors”:\n\n```\nUSING: accessors kernel math math.parser prettyprint ;\nIN: scratchpad\nGENERIC: description ( obj -- string )\nM: person description name>> ;\nM: integer description number>string ;\n\"Ada\" 36 <person> description .  ! \"Ada\"\n42 description .                 ! \"42\"\n```\nA [tuple subclass](https://docs.factorcode.org/content/article-tuple-subclassing.html)\ninherits its parent’s slots and can add its own. An overriding method can\nreuse the next less-specific method with\n[`call-next-method`](https://docs.factorcode.org/content/article-call-next-method.html):\n\n```\nUSING: accessors kernel prettyprint sequences ;\nIN: scratchpad\nTUPLE: employee < person role ;\nC: <employee> employee\nM: employee description\n    [ call-next-method ] [ role>> ] bi \" - \" glue ;\n\"Ada\" 36 \"programmer\" <employee> description .\n! \"Ada - programmer\"\n```\nThe constructor takes inherited slots first (`name`, `age`), then `role`.\nHere [`call-next-method`](https://docs.factorcode.org/content/word-call-next-method%2Csyntax.html) receives the employee, calls the `person` method,\nand returns `\"Ada\"`; the override combines that with the employee’s role.\nIt must appear inside a method definition and receives its inputs from the\nstack, just like an ordinary call.\n\n[`M:`](https://docs.factorcode.org/content/word-M__colon__%2Csyntax.html) defines a method. This is how protocols such as sequences and assocs\nprovide common operations for many concrete types. Classes also have\npredicate words, and you can define narrower predicate classes or unions:\n\n```\nUSING: kernel math prettyprint strings ;\nIN: scratchpad\nPREDICATE: positive-integer < integer 0 > ;\nUNION: text-or-integer string integer ;\n3 positive-integer? .           ! t\n-3 positive-integer? .          ! f\n\"hello\" text-or-integer? .      ! t\n```\n[`Mixin classes`](https://docs.factorcode.org/content/article-mixins.html)\nare open groups of classes: [`INSTANCE:`](https://docs.factorcode.org/content/word-INSTANCE__colon__%2Csyntax.html) adds a member, including after the\nmixin was defined. They are useful for protocols spanning unrelated types:\n\n```\nUSING: prettyprint ;\nIN: scratchpad\nMIXIN: named\nINSTANCE: person named\n\"Ada\" 36 <person> named? .      ! t\n```\n[`Singleton classes`](https://docs.factorcode.org/content/article-singletons.html)\neach have one stateless instance, useful as distinct states or options.\nUnlike a plain symbol, each can have its own generic methods:\n\n```\nUSING: prettyprint ;\nIN: scratchpad\nSINGLETONS: pending running finished ;\nUNION: job-state pending running finished ;\npending job-state? .            ! t\n```\n[`UNION:`](https://docs.factorcode.org/content/word-UNION__colon__%2Csyntax.html) accepts instances of any listed class. [`INTERSECTION:`](https://docs.factorcode.org/content/word-INTERSECTION__colon__%2Csyntax.html) requires\nmembership in all listed classes. For named numeric values,\n[`ENUMERATION:`](https://docs.factorcode.org/content/article-enums.html)\nis available in [`classes.enumeration`](https://docs.factorcode.org/content/vocab-classes.enumeration.html):\n\n```\nUSING: classes.enumeration prettyprint ;\nIN: scratchpad\nENUMERATION: priority low medium high ;\npriority.low .                  ! 0\npriority.high .                 ! 2\n```\n### Symbols and dynamic variables\n\nLexical locals are scoped by source structure. [`namespaces`](https://docs.factorcode.org/content/vocab-namespaces.html) provides\n[variables scoped dynamically](https://docs.factorcode.org/content/article-namespaces.html) around a quotation:\n\n```\nUSING: namespaces prettyprint ;\nIN: scratchpad\nSYMBOL: current-user\n\"Ada\" current-user [\n    current-user get .          ! \"Ada\"\n] with-variable\n```\nCalled words inside the quotation see the binding too. [`with-variable`](https://docs.factorcode.org/content/word-with-variable%2Cnamespaces.html)\nrestores the previous binding on exit. [`set`](https://docs.factorcode.org/content/word-set%2Cnamespaces.html) changes a binding in the\ncurrent namespace; [`set-global`](https://docs.factorcode.org/content/word-set-global%2Cnamespaces.html) sets a global binding. A symbol is itself\na value, so symbols also work as distinct markers and hashtable keys.\n\n### Errors and cleanup\n\n```\nUSING: continuations kernel prettyprint ;\nIN: scratchpad\nERROR: invalid-age age ;\n[ -1 invalid-age ] [ drop \"handled\" ] recover .  ! \"handled\"\n[ \"work\" . ] [ \"cleanup\" . ] finally\n! Prints \"work\", then \"cleanup\"\n```\nThe [exception handling](https://docs.factorcode.org/content/article-errors.html) form [`ERROR:`](https://docs.factorcode.org/content/word-ERROR__colon__%2Csyntax.html) defines an error class and a word that throws an instance.\n[`recover`](https://docs.factorcode.org/content/word-recover%2Ccontinuations.html) calls a handler with the thrown object. The data stack is restored\nto its state before the protected quotation, then the error is pushed.\n[`finally`](https://docs.factorcode.org/content/word-finally%2Ccontinuations.html) runs cleanup on either normal completion or an error.\n\nFactor also exposes [continuations](https://docs.factorcode.org/content/article-continuations.html),\nwhich capture execution state and can later resume it. They underpin error\nhandling and cooperative threads; most everyday code uses those higher-level\nfacilities directly.\n\n### Resource disposal\n\nOrdinary objects are garbage collected. Resources such as open streams\nalso need [deterministic disposal](https://docs.factorcode.org/content/article-destructors.html).\n[`dispose`](https://docs.factorcode.org/content/word-dispose%2Cdestructors.html) releases a resource explicitly. [`with-disposal`](https://docs.factorcode.org/content/word-with-disposal%2Cdestructors.html) passes a resource\nto a quotation and disposes it when the quotation finishes or throws:\n\n```\nUSING: destructors io io.encodings.utf8 io.files prettyprint ;\n\"Hello!\\n\" \"disposal.txt\" utf8 set-file-contents\n\"disposal.txt\" utf8 <file-reader>\n[ stream-readln . ] with-disposal  ! \"Hello!\"\n```\nThis example creates `disposal.txt` in the current directory. The reader\nis closed after reading the line. For several resources, use\n[`with-destructors`](https://docs.factorcode.org/content/article-destructors-using.html)\nand register each one for cleanup:\n\n```\nUSING: destructors io io.encodings.utf8 io.files prettyprint ;\n[\n    \"disposal.txt\" utf8 <file-reader> &dispose\n    stream-readln .             ! \"Hello!\"\n] with-destructors\n```\nBoth registration words leave the resource on the stack so you can use it:\n\n| Word | When the resource is disposed | \n|---|---|\n| [`&dispose`](https://docs.factorcode.org/content/word-%26dispose%2Cdestructors.html) | When the enclosing [`with-destructors`](https://docs.factorcode.org/content/word-with-destructors%2Cdestructors.html) scope finishes, on success or error | \n| [`\\|dispose`](https://docs.factorcode.org/content/word-__pipe__dispose%2Cdestructors.html) | When the enclosing [`with-destructors`](https://docs.factorcode.org/content/word-with-destructors%2Cdestructors.html) scope exits with an error | \n\n[`&dispose`](https://docs.factorcode.org/content/word-%26dispose%2Cdestructors.html) is for resources used within a scope. [`|dispose`](https://docs.factorcode.org/content/word-__pipe__dispose%2Cdestructors.html) is useful when\nbuilding a result that owns resources: if construction fails, clean up;\nif it succeeds, return the resources to the caller. For example:\n\n```\nUSING: destructors io.encodings.utf8 io.files kernel ;\nIN: scratchpad\n: open-two-readers ( path1 path2 -- reader1 reader2 )\n    [ [ utf8 <file-reader> |dispose ] bi@ ] with-destructors ;\n\"disposal.txt\" \"disposal.txt\" open-two-readers\n[ dispose ] bi@                 ! Caller closes both readers\n```\nIf opening the second reader throws, the first reader is disposed. On\nsuccess, both readers remain open and the caller owns their cleanup.\nWithin each registration group, destructors run in reverse registration\norder. The [`with-file-reader`](https://docs.factorcode.org/content/word-with-file-reader%2Cio.files.html) and [`with-file-writer`](https://docs.factorcode.org/content/word-with-file-writer%2Cio.files.html) combinators shown below\nmanage stream cleanup automatically.\n\n### Vocabularies\n\nA [vocabulary](https://docs.factorcode.org/content/article-vocabularies.html) is a namespace and a unit of source organization. A vocabulary\nnamed `examples.greeting` conventionally lives in\n`examples/greeting/greeting.factor` under a vocabulary root:\n\n```\nUSING: io ;\nIN: examples.greeting\n<PRIVATE\n: greeting ( -- string ) \"Hello, world!\" ;\nPRIVATE>\n: greet ( -- ) greeting print ;\nMAIN: greet\n```\n[`<PRIVATE ... PRIVATE>`](https://docs.factorcode.org/content/word-__lt__PRIVATE%2Csyntax.html) places helper definitions in the vocabulary’s\nprivate namespace. Import public definitions with `USE: examples.greeting`\nor include it in a [`USING:`](https://docs.factorcode.org/content/word-USING__colon__%2Csyntax.html) list. Run the entry point with\n`./factor -run=examples.greeting` once its directory is in a vocabulary\n[root](https://docs.factorcode.org/content/article-vocabs.roots.html), such as your installation’s `work` directory. Dots organize vocabulary\nnames; importing a parent does not automatically import its children.\n\nSource files need explicit imports. If a word is missing, its documentation\nshows which vocabulary provides it. The listener may offer to import a word\nautomatically; include that vocabulary in [`USING:`](https://docs.factorcode.org/content/word-USING__colon__%2Csyntax.html) when saving the code.\nFor [ambiguous names](https://docs.factorcode.org/content/article-word-search.html),\nuse a vocabulary prefix or select a word with [`FROM:`](https://docs.factorcode.org/content/word-FROM__colon__%2Csyntax.html):\n\n```\nUSING: math prettyprint ;\n2 3 math:+ .                    ! 5\nFROM: math => + ;\n2 3 + .                         ! 5\n```\n### Editing and reloading\n\nFactor’s listener runs in a live image containing loaded definitions and\nobjects. You can redefine a word and try it again in the same session.\nFor code saved in a vocabulary, load it once with [`USE:`](https://docs.factorcode.org/content/word-USE__colon__%2Csyntax.html), then\n[reload changes](https://docs.factorcode.org/content/article-vocabs.refresh.html)\nafter editing its source:\n\n```\nUSING: vocabs.loader vocabs.refresh ;\nUSE: examples.greeting\n\"examples.greeting\" reload      ! Reload this vocabulary\nrefresh-all                     ! Reload changed files in loaded vocabularies\n```\nThis assumes you saved `examples.greeting` in a vocabulary root as above.\nThe [scaffold tool](https://docs.factorcode.org/content/article-tools.scaffold.html)\ncan create source, documentation, and test files for a new vocabulary.\n\n### Code as data, macros, and parsing words\n\nWords are objects too. A backslash obtains a word without executing it:\n\n```\nUSING: accessors math prettyprint words ;\n\\ + name>> .                    ! \"+\"\n```\nQuotations are built out of objects and words.\n[Macros](https://docs.factorcode.org/content/article-macros.html) compute quotations\nthat the compiler expands at call sites:\n\n```\nUSING: kernel macros math prettyprint ;\nIN: scratchpad\nMACRO: add-constant ( n -- quot ) [ + ] curry ;\n5 10 add-constant .             ! 15\n```\nHere `10` is the macro input, and the expansion adds it to the runtime\nvalue `5`. Macro inputs must be known at compile time.\n\nSyntax is extensible through [*parsing words*](https://docs.factorcode.org/content/article-parsing-words.html), which execute while source\nis being read. `:`, [`TUPLE:`](https://docs.factorcode.org/content/word-TUPLE__colon__%2Csyntax.html), and literal openers are examples. Libraries\ncan add their own syntax, such as `R/ ... /` for regular expressions.\n\n### Memoization\n\n[`MEMO:`](https://docs.factorcode.org/content/article-memoize.html) defines a word whose results are cached by its inputs:\n\n```\nUSING: kernel math memoize prettyprint ;\nIN: scratchpad\nMEMO: fibonacci ( n -- m )\n    dup 1 <= [ ] [\n        [ 1 - fibonacci ] [ 2 - fibonacci ] bi +\n    ] if ;\n10 fibonacci .                  ! 55\n```\nThis is useful for pure computations. Cached mutable results are shared objects, so memoization needs care when callers mutate those results.\n\n### Files and formatted output\n\n```\nUSING: formatting io io.encodings.utf8 io.files prettyprint ;\n\"Ada\" 36 \"%s is %d years old.\\n\" printf\n\"Hello, world!\\n\" \"hello.txt\" utf8 set-file-contents\n\"hello.txt\" utf8 file-contents print\n\"hello.txt\" utf8 [\n    readln .\n] with-file-reader\n```\nThe [file examples](https://docs.factorcode.org/content/article-io.files.html) create `hello.txt` in the current directory.\n[`formatting`](https://docs.factorcode.org/content/article-formatting.html) provides [`printf`](https://docs.factorcode.org/content/word-printf%2Cformatting.html) for formatted output.\n[`with-file-reader`](https://docs.factorcode.org/content/word-with-file-reader%2Cio.files.html) binds the current input stream and closes it after the\nquotation finishes. [`with-file-writer`](https://docs.factorcode.org/content/word-with-file-writer%2Cio.files.html) does the same for output.\n\n### JSON, regular expressions, and HTTP\n\nThe [`json` vocabulary](https://docs.factorcode.org/content/article-json.html) converts between JSON text and Factor objects:\n\n```\nUSING: assocs json kernel prettyprint ;\n\"{\\\"name\\\":\\\"Ada\\\",\\\"age\\\":36}\" json>\n\"name\" swap at .                ! \"Ada\"\nH{ { \"name\" \"Ada\" } } >json .   ! \"{\\\"name\\\":\\\"Ada\\\"}\"\n```\n[Regular expressions](https://docs.factorcode.org/content/article-regexp.html) use their own literal syntax:\n\n```\nUSING: prettyprint regexp ;\n\"12345\" R/ [0-9]+/ matches? .   ! t\n\"hello\" R/ [0-9]+/ matches? .   ! f\n```\nThe [HTTP client](https://docs.factorcode.org/content/article-http.client.html) returns both a response object and the downloaded content:\n\n```\nUSING: http.client kernel ;\n\"https://factorcode.org\" http-get\nnip                             ! Leave only the content\n```\n### Dates and calendars\n\n[`calendar`](https://docs.factorcode.org/content/article-calendar.html) provides timestamps and durations and computations on them.\n\n```\nUSING: calendar prettyprint ;\nnow .                              ! Current local timestamp\n10 months duration>minutes         ! Lots of minutes\ntoday next-monday                  ! The next monday after today\n```\n### Random\n\n[`random`](https://docs.factorcode.org/content/article-random.html) selects random numbers or collection elements:\n\n```\nUSING: prettyprint random ;\n10 random .                        ! Random integer from 0 through 9\n{ \"red\" \"green\" \"blue\" } random .  ! Random element\n```\nWe also have various [random distributions](../../2024/07/random-distributions.html) available.\n\n### Threads\n\nFactor [threads](https://docs.factorcode.org/content/article-threads.html) are cooperatively scheduled. [`yield`](https://docs.factorcode.org/content/word-yield%2Cthreads.html) lets another runnable\nthread execute, and blocking I/O integrates with the scheduler:\n\n```\nUSING: kernel math prettyprint threads ;\n42 [ 1 + . ] curry \"worker\" spawn drop\nyield                           ! Worker prints 43\n```\nThe worker starts with an empty data stack; `curry` explicitly carries the\ninput into its quotation. The `concurrency` vocabularies provide additional\ntools such as mailboxes and promises.\n\n### Calling C\n\nThe [foreign function interface](https://docs.factorcode.org/content/article-alien-invoke.html) declares C functions as Factor words.\nFor example, this binds `strlen` from the C library:\n\n```\nUSING: alien.c-types alien.syntax prettyprint ;\nIN: scratchpad\nLIBRARY: libc\nFUNCTION: size_t strlen ( c-string str )\n\"hello\" strlen .                ! 5\n```\nThe [`c-string`](https://docs.factorcode.org/content/word-c-string%2Calien.c-types.html) argument converts a Factor string for the C call. The FFI\nalso supports structures, pointers, callbacks, and arrays. Unlike the\nmanaged objects used above, foreign allocations can require explicit\nlifetime management.\n\n### Testing and exploring\n\n[`tools.test`](https://docs.factorcode.org/content/article-tools.test.html) expresses expected stack results as an array:\n\n```\nUSING: kernel math tools.test ;\n{ 5 } [ 2 3 + ] unit-test\n{ 25 } [ 5 dup * ] unit-test\n[ 1 0 / ] must-fail\n```\nTests for a vocabulary conventionally live alongside its source in a\n`*-tests.factor` file. After saving tests for `examples.greeting`, run them\nwith `\"examples.greeting\" test` in the listener. This also runs tests in\nits child vocabularies.\n\nThe development environment also lets you inspect definitions, look up documentation, and time quotations:\n\n```\nUSING: help kernel math see sequences tools.time ;\n\\ map help                      ! Open documentation for map\n\\ + describe                    ! Describe the object ``+``\n\\ square see                    ! Show the earlier definition\n[ 1000000 [ ] times ] time      ! Time a quotation\n```\nThe [Factor handbook](https://docs.factorcode.org/content/article-handbook.html)\nis the next stop for more detail. For a project walkthrough, the\n[first-program tutorial](https://docs.factorcode.org/content/article-first-program.html)\ncovers creating a vocabulary, editing and reloading it, and extending it\nwith tests. The\n[vocabulary index](https://docs.factorcode.org/content/article-vocab-index.html) covers\nthe libraries, and the source distribution includes documentation and tests\nnext to the code. Start with small words, follow their stack effects, and\nuse combinators to make the flow of values clear.\n","body_html":"<h1 id=\"factor-overview\">Factor Overview</h1>\n<p>I highly recommend reading the <a href=\"https://docs.factorcode.org/content/article-tour.html\" rel=\"nofollow ugc noopener\">guided tour of Factor</a>.\nIt provides a great introduction to the language and libraries of <a href=\"https://factorcode.org\" rel=\"nofollow ugc noopener\">Factor</a>.\nEven still, I sometimes have also wanted to have more code-forward examples of everyday syntax,\ncontrol flow, combinators, and some of the main libraries. This is that overview. It assumes you have programmed before, but have not necessarily used a\nstack-based language.</p>\n<h3 id=\"hello-world\">Hello, world</h3>\n<p>The simplest <a href=\"https://en.wikipedia.org/wiki/Hello,_world\" rel=\"nofollow ugc noopener\">Hello, world</a> is just:</p>\n<pre><code>&quot;Hello, world!&quot; print</code></pre>\n<p>You can run that from <a href=\"https://docs.factorcode.org/content/article-listener.html\" rel=\"nofollow ugc noopener\">the listener</a>:</p>\n<pre><code>IN: scratchpad &quot;Hello, world!&quot; print\nHello, world!</code></pre>\n<p>And you can run it from the command-line:</p>\n<pre><code>$ ./factor -e=&quot;\\&quot;Hello, world!\\&quot; print&quot;\nHello, world!</code></pre>\n<p>Of course, you can also make this a file named <code>hello.factor</code>, which\ndefines a <code>hello</code> vocabulary (something you learn about in the\n<a href=\"https://docs.factorcode.org/content/article-first-program.html\" rel=\"nofollow ugc noopener\">your first program</a> tutorial).</p>\n<pre><code>USING: io ;\nIN: hello\n: main ( -- )\n    &quot;Hello, world!&quot; print ;\nMAIN: main</code></pre>\n<p>The <a href=\"https://docs.factorcode.org/content/article-syntax.html\" rel=\"nofollow ugc noopener\">syntax</a> used above includes:</p>\n<ul><li><a href=\"https://docs.factorcode.org/content/word-USING__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>USING:</code></a> imports vocabularies (named collections of words)</li><li><a href=\"https://docs.factorcode.org/content/word-IN__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>IN:</code></a> selects the vocabulary for definitions, and</li><li><a href=\"https://docs.factorcode.org/content/word-MAIN__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>MAIN:</code></a> sets an entry point.</li></ul>\n<p>And then you can run it either as a script:</p>\n<pre><code>$ ./factor hello.factor\nHello, world!</code></pre>\n<p>Or, if this is available in the <a href=\"https://docs.factorcode.org/content/article-vocabs.roots.html\" rel=\"nofollow ugc noopener\">vocabulary roots</a>\nsearch path, run the vocabulary’s main word:</p>\n<pre><code>$ ./factor -run=hello\nHello, world!</code></pre>\n<p>For the rest of this overview, try the examples in the <em>listener</em>, Factor’s\n<a href=\"https://docs.factorcode.org/content/article-listener.html\" rel=\"nofollow ugc noopener\">interactive REPL</a>.\nStart the terminal listener with <code>./factor -run=listener</code>,\nor use the graphical listener in the development environment. Each example\nincludes its imports; examples that build on a definition assume you have\nentered that definition too. <a href=\"https://docs.factorcode.org/content/word-IN__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>IN: scratchpad</code></a> puts experimental definitions\nin the listener’s usual working vocabulary. Feel free to paste the code\ndirectly, to see what it does. Comments beginning with <code>!</code> are part of\nvalid Factor source.</p>\n<p>For a quick start, work through the stack, word definitions, quotations, control flow, and sequences. The later sections introduce objects, metaprogramming, and libraries that you can return to as you need them.</p>\n<h3 id=\"values-and-the-stack\">Values and the stack</h3>\n<p><a href=\"https://docs.factorcode.org/content/article-literals.html\" rel=\"nofollow ugc noopener\">Literals</a> push values onto the data stack. Words consume inputs from the top\nof that stack and push their outputs. Code runs from left to right:</p>\n<pre><code>USING: math prettyprint ;\n2 3 + .                         ! 5\n10 4 - .                        ! 6\n2 3 + 4 * .                     ! 20</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/word-.%2Cprettyprint.html\" rel=\"nofollow ugc noopener\"><code>.</code></a> consumes and prints an object. <a href=\"https://docs.factorcode.org/content/word-print%2Cio.html\" rel=\"nofollow ugc noopener\"><code>print</code></a> consumes and prints a string.\nThe comments beside examples show the output. Because printing removes the\nvalue, these examples leave the stack empty unless stated otherwise.\nThere are no parentheses around function arguments: put the arguments on\nthe stack, then invoke the word. Below, the top of the stack is on the right:</p>\n<pre><code>Code       Stack\n2          2\n3          2 3\n+          5\n4          5 4\n*          20\n.          (empty)</code></pre>\n<p>Spaces matter. <code>2 3 +</code> is three tokens; <code>2+3</code> is a single token, which would\nneed to be the name of a word. Names like <a href=\"https://docs.factorcode.org/content/word-number__gt__string%2Cmath.parser.html\" rel=\"nofollow ugc noopener\"><code>number&gt;string</code></a>, <a href=\"https://docs.factorcode.org/content/word-empty__que__%2Csequences.html\" rel=\"nofollow ugc noopener\"><code>empty?</code></a>, and\n<a href=\"https://docs.factorcode.org/content/word-set-at%2Cassocs.html\" rel=\"nofollow ugc noopener\"><code>set-at</code></a> are ordinary word names. A trailing <code>?</code> conventionally marks a\npredicate; <code>&gt;</code> often appears in conversion names. Those characters are part\nof the name, not separate operators. A trailing <code>!</code> often marks a mutating\nvariant, such as <a href=\"https://docs.factorcode.org/content/word-append%21%2Csequences.html\" rel=\"nofollow ugc noopener\"><code>append!</code></a>; <code>*</code> usually marks an alternative form. There are some\n<a href=\"https://docs.factorcode.org/content/article-conventions.html\" rel=\"nofollow ugc noopener\">conventions</a> useful\nfor learning word and type naming.</p>\n<h3 id=\"comments-and-literals\">Comments and literals</h3>\n<pre><code>USING: math multiline prettyprint ;\n! A comment runs to the end of the line.\n/* A block comment can span\n   several lines. */\n42 .                            ! Integer\n-17 .                           ! Negative integer\n0xff .                          ! 255, hexadecimal\n0b1010 .                        ! 10, binary\n3/4 .                           ! Exact rational\n1.25 .                          ! Floating point\nC{ 2 3 } .                      ! Complex number: 2 + 3i\nt .                             ! True\nf .                             ! False\n&quot;hello\\nworld&quot; .                ! String with an escape\nCHAR: A .                       ! 65, a character code point\n{ 1 2 3 } .                     ! Array\nV{ 1 2 3 } .                    ! Growable vector\nB{ 0 127 255 } .                ! Byte array\nH{ { &quot;name&quot; &quot;Ada&quot; } } .         ! Hashtable\n[ 1 + ] .                       ! Quotation: code as a value</code></pre>\n<p>Arrays and quotations contain objects without executing them. Collection\nliterals are useful for fixed data; when mutating one inside a word, use\n<a href=\"https://docs.factorcode.org/content/word-clone%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>clone</code></a> to obtain a fresh copy rather than changing a shared literal.\nThis is a shallow copy: objects inside the collection are still shared.</p>\n<p>Block comments come from the <a href=\"https://docs.factorcode.org/content/vocab-multiline.html\" rel=\"nofollow ugc noopener\"><code>multiline</code></a> vocabulary.</p>\n<p><a href=\"https://docs.factorcode.org/content/word-CHAR__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>CHAR:</code></a> produces an integer code point; Factor has no separate character\ntype. <code>{ ... }</code> is an array, while <code>[ ... ]</code> is executable code held as a\nvalue called a <a href=\"https://docs.factorcode.org/content/article-quotations.html\" rel=\"nofollow ugc noopener\">quotation</a>.\nSpaces separate the literal openers, their contents, and the closing\ndelimiters, as in <code>{ 1 2 3 }</code> and <code>[ 1 + ]</code>.</p>\n<h3 id=\"strings-and-escape-characters\">Strings and escape characters</h3>\n<p>String literals use double quotes. A backslash introduces a\n<a href=\"https://docs.factorcode.org/content/article-escape.html\" rel=\"nofollow ugc noopener\">character escape</a>:</p>\n<div class=\"table-wrap\"><table><thead><tr><th>Escape</th><th>Meaning</th></tr></thead><tbody><tr><td><code>\\&quot;</code></td><td>Double quote</td></tr><tr><td><code>\\\\</code></td><td>Backslash</td></tr><tr><td><code>\\a</code></td><td>Bell (code point 7)</td></tr><tr><td><code>\\b</code></td><td>Backspace (8)</td></tr><tr><td><code>\\e</code></td><td>Escape (27)</td></tr><tr><td><code>\\f</code></td><td>Form feed (12)</td></tr><tr><td><code>\\n</code></td><td>Newline (10)</td></tr><tr><td><code>\\r</code></td><td>Carriage return (13)</td></tr><tr><td><code>\\s</code></td><td>Space (32)</td></tr><tr><td><code>\\t</code></td><td>Tab (9)</td></tr><tr><td><code>\\v</code></td><td>Vertical tab (11)</td></tr><tr><td><code>\\0</code></td><td>Null (0)</td></tr><tr><td><code>\\ooo</code></td><td>Code point given by one to three octal digits</td></tr><tr><td><code>\\xHH</code></td><td>Code point given by exactly two hexadecimal digits</td></tr><tr><td><code>\\uHHHHHH</code></td><td>Code point given by exactly six hexadecimal digits</td></tr><tr><td><code>\\u{H...}</code></td><td>Code point given by hexadecimal digits inside braces</td></tr><tr><td><code>\\u{name}</code></td><td>Named Unicode character, with Unicode support loaded</td></tr></tbody></table></div>\n<p>For example:</p>\n<pre><code>USING: io prettyprint sequences unicode ;\n&quot;She said \\&quot;hello\\&quot;.&quot; print        ! She said &quot;hello&quot;.\n&quot;C:\\\\Users\\\\Ada&quot; print             ! C:\\Users\\Ada\n&quot;\\x41\\u000042\\u{43}&quot; print         ! ABC\n&quot;\\u{greek-small-letter-pi}&quot; print  ! π\n&quot;first\\nsecond&quot; print              ! Prints two lines\n&quot;\\t&quot; length .                      ! 1: the escape represents one character\n&quot;hello&quot; length .                   ! 5\n&quot;hello&quot; &gt;upper .                   ! &quot;HELLO&quot;\n&quot;a,b,c&quot; &quot;,&quot; split .                ! { &quot;a&quot; &quot;b&quot; &quot;c&quot; }\n{ &quot;a&quot; &quot;b&quot; &quot;c&quot; } &quot;, &quot; join .        ! &quot;a, b, c&quot;\n&quot;42&quot; string&gt;number .               ! 42\n42 number&gt;string .                 ! &quot;42&quot;\n&quot;oops&quot; string&gt;number .             ! f</code></pre>\n<p>The six-digit <code>\\u</code> form differs from languages that use four digits; the\nbraced form is often easier to read. Unknown escapes are errors. Strings\ncan also span source lines directly: an actual newline becomes part of the\nstring. A backslash immediately before a source newline continues the\nstring without including that newline. A backslash followed by a literal\nspace also represents a space, like <code>\\s</code>.</p>\n<p>*Note: the length of a <a href=\"https://docs.factorcode.org/content/article-strings.html\" rel=\"nofollow ugc noopener\">string</a>\nis the number of code points, not the number of visible glyphs. You can learn a bit more\nby reading about Factor’s <a href=\"https://re.factorcode.org/2023/05/unicode.html\" rel=\"nofollow ugc noopener\">Unicode</a> support.*</p>\n<h3 id=\"stack-shuffling\">Stack shuffling</h3>\n<p>Typical of <a href=\"https://concatenative.org/wiki/view/Concatenative%20language\" rel=\"nofollow ugc noopener\">concatenative languages</a>,\nthe stack is a data structure with it’s own access patterns that we often call\n<a href=\"https://docs.factorcode.org/content/article-tour-stack-shuffling.html\" rel=\"nofollow ugc noopener\">stack shuffling</a>.</p>\n<pre><code>USING: kernel prettyprint ;\n10 dup . .                      ! Prints 10, then 10\n10 20 swap . .                  ! Prints 10, then 20\n10 20 over . . .                ! Prints 10, then 20, then 10\n10 20 nip .                     ! 20: discard the second item\n10 20 drop .                    ! 10: discard the top item</code></pre>\n<p>The usual <a href=\"https://docs.factorcode.org/content/article-shuffle-words.html\" rel=\"nofollow ugc noopener\">stack shuffling words</a> have these effects:</p>\n<pre><code>! dup   ( x -- x x )\n! drop  ( x -- )\n! swap  ( x y -- y x )\n! over  ( x y -- x y x )\n! nip   ( x y -- y )\n! rot   ( x y z -- y z x )</code></pre>\n<p>Most Factor code uses short definitions and combinators to keep explicit shuffling to a minimum.</p>\n<p>In a stack effect, inputs and outputs run from left to right, with the\ntopmost value last. <a href=\"https://docs.factorcode.org/content/word-swap%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>swap</code></a> therefore changes a stack ending in <code>x y</code> into\none ending in <code>y x</code>; values below those inputs are untouched. Repeated\n<a href=\"https://docs.factorcode.org/content/word-.%2Cprettyprint.html\" rel=\"nofollow ugc noopener\"><code>.</code></a> calls print the topmost result first.</p>\n<h3 id=\"defining-words\">Defining words</h3>\n<p>You can create <a href=\"https://docs.factorcode.org/content/article-words.html\" rel=\"nofollow ugc noopener\">words</a> that\ncontain code that is executed when called:</p>\n<pre><code>USING: kernel math prettyprint ;\nIN: scratchpad\n: square ( n -- n-squared ) dup * ;\n: neighbors ( n -- below above )\n    dup 1 - swap 1 + ;\n5 square .                      ! 25\n5 neighbors . .                 ! Prints 6, then 4\nCONSTANT: answer 42\nanswer .                        ! 42</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/article-colon-definition.html\" rel=\"nofollow ugc noopener\"><code>:</code></a> begins a definition and <a href=\"https://docs.factorcode.org/content/word-%3B%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>;</code></a> ends it. The <a href=\"https://docs.factorcode.org/content/article-effects.html\" rel=\"nofollow ugc noopener\">stack effect</a> <code>( inputs -- outputs )</code> documents how many values the word consumes and produces. Its\nnames describe the values; they do not bind variables or specify types.\nThe compiler checks stack effects, including compatible effects for branches.\nWords can return several values simply by leaving them on the stack.\nThere is no explicit <code>return</code>: execution finishes at the end of the word.</p>\n<p><a href=\"https://docs.factorcode.org/content/word-ALIAS__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>ALIAS: new-name existing-word</code></a> defines another name for a word.</p>\n<h3 id=\"arithmetic-and-comparisons\">Arithmetic and comparisons</h3>\n<p>Lots of <a href=\"https://docs.factorcode.org/content/article-arithmetic.html\" rel=\"nofollow ugc noopener\">arithmetic</a> is\navailable for computing with <a href=\"https://docs.factorcode.org/content/article-numbers.html\" rel=\"nofollow ugc noopener\">numbers</a>:</p>\n<pre><code>USING: kernel math math.functions math.order prettyprint ;\n7 2 / .                         ! 3+1/2, an exact rational\n7 2 /i .                        ! 3, integer division\n7 2 mod .                       ! 1\n2 10 ^ .                        ! 1024\n9 sqrt .                        ! 3.0\n-5 abs .                        ! 5\n3 8 min .                       ! 3\n3 8 max .                       ! 8\n2 3 &lt; .                         ! t\n2 3 &gt;= .                        ! f\n&quot;hello&quot; &quot;hello&quot; = .             ! t, value equality</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/article-integers.html\" rel=\"nofollow ugc noopener\">Integers</a> grow beyond machine size automatically, and division of integers\ncan produce <a href=\"https://docs.factorcode.org/content/article-rationals.html\" rel=\"nofollow ugc noopener\">exact ratios</a>. Use floating-point inputs when you want\nfloating-point arithmetic.</p>\n<p>Bitwise operations have their own names, separate from boolean logic:</p>\n<pre><code>USING: math prettyprint ;\n0b1100 0b1010 bitand .          ! 8\n0b1100 0b1010 bitor .           ! 14\n0b1100 0b1010 bitxor .          ! 6\n1 3 shift .                     ! 8: shift left\n8 -1 shift .                    ! 4: shift right</code></pre>\n<h3 id=\"quotations\">Quotations</h3>\n<p>Square brackets produce a <a href=\"https://docs.factorcode.org/content/article-quotations.html\" rel=\"nofollow ugc noopener\">quotation</a>. <a href=\"https://docs.factorcode.org/content/word-call,kernel.html\" rel=\"nofollow ugc noopener\"><code>call</code></a> executes it:</p>\n<pre><code>USING: kernel math prettyprint sequences ;\n5 [ 1 + ] call .                ! 6\n{ 1 2 3 } [ 2 * ] map .         ! { 2 4 6 }</code></pre>\n<p>Quotations can be passed to words, returned from words, and stored in\ncollections. Words that take quotations are called\n<a href=\"https://docs.factorcode.org/content/article-combinators.html\" rel=\"nofollow ugc noopener\"><em>combinators</em></a>.</p>\n<h3 id=\"booleans-and-conditionals\">Booleans and conditionals</h3>\n<p>In <a href=\"https://docs.factorcode.org/content/article-booleans.html\" rel=\"nofollow ugc noopener\">boolean tests</a>, only <a href=\"https://docs.factorcode.org/content/word-f%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>f</code></a> is false. Zero, an empty string, and an empty array are all true.</p>\n<pre><code>USING: kernel math prettyprint ;\nt f and .                        ! f\nt f or .                         ! t\nf not .                          ! t\n3 2 &gt; [ &quot;yes&quot; ] [ &quot;no&quot; ] if .    ! &quot;yes&quot;\n0 [ &quot;truthy&quot; ] [ &quot;false&quot; ] if .  ! &quot;truthy&quot;\nt [ &quot;runs&quot; . ] when\nf [ &quot;runs too&quot; . ] unless</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/word-if,kernel.html\" rel=\"nofollow ugc noopener\"><code>if</code></a> consumes a condition and two quotations. It calls the first quotation\nfor a true condition and the second for <a href=\"https://docs.factorcode.org/content/word-f%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>f</code></a>. <a href=\"https://docs.factorcode.org/content/word-when%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>when</code></a> and <a href=\"https://docs.factorcode.org/content/word-unless%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>unless</code></a> take one\nquotation. These are words that operate on code values, just like <a href=\"https://docs.factorcode.org/content/word-%2B%2Cmath.html\" rel=\"nofollow ugc noopener\"><code>+</code></a>\noperates on numbers.</p>\n<p>For several alternatives, use <a href=\"https://docs.factorcode.org/content/article-conditionals.html\" rel=\"nofollow ugc noopener\"><code>cond</code> or <code>case</code></a>:</p>\n<pre><code>USING: combinators kernel math prettyprint ;\nIN: scratchpad\n: sign-name ( n -- string )\n    {\n        { [ dup 0 &lt; ] [ drop &quot;negative&quot; ] }\n        { [ dup 0 = ] [ drop &quot;zero&quot; ] }\n        [ drop &quot;positive&quot; ]\n    } cond ;\n-3 sign-name .                  ! &quot;negative&quot;\n: color-name ( color -- string )\n    {\n        { &quot;r&quot; [ &quot;red&quot; ] }\n        { &quot;g&quot; [ &quot;green&quot; ] }\n        [ drop &quot;unknown&quot; ]\n    } case ;\n&quot;g&quot; color-name .                ! &quot;green&quot;</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/word-cond%2Ccombinators.html\" rel=\"nofollow ugc noopener\"><code>cond</code></a> tries predicate quotations in order. <a href=\"https://docs.factorcode.org/content/word-case%2Ccombinators.html\" rel=\"nofollow ugc noopener\"><code>case</code></a> compares an input with\neach key; a matching branch consumes the key automatically, while the\ndefault branch receives the unmatched input.</p>\n<p><a href=\"https://docs.factorcode.org/content/word-and%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>and</code></a> and <a href=\"https://docs.factorcode.org/content/word-or%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>or</code></a> combine values that have already been computed. For\n<a href=\"https://docs.factorcode.org/content/article-combinators.short-circuit.html\" rel=\"nofollow ugc noopener\">short-circuit evaluation</a>, pass predicate quotations instead:</p>\n<pre><code>USING: combinators.short-circuit kernel math prettyprint ;\n5 { [ 0 &gt; ] [ 10 &lt; ] } 1&amp;&amp; .    ! t: positive and less than ten\n-5 { [ 0 &lt; ] [ 10 &gt; ] } 1|| .   ! t: negative or greater than ten</code></pre>\n<p>Each predicate receives the same input. <a href=\"https://docs.factorcode.org/content/word-1%26%26%2Ccombinators.short-circuit.html\" rel=\"nofollow ugc noopener\"><code>1&amp;&amp;</code></a> stops at the first false\nresult; <a href=\"https://docs.factorcode.org/content/word-1__pipe____pipe__%2Ccombinators.short-circuit.html\" rel=\"nofollow ugc noopener\"><code>1||</code></a> stops at the first true result. The leading number is the\nnumber of inputs passed to each predicate.</p>\n<h3 id=\"keeping-and-hiding-values\">Keeping and hiding values</h3>\n<p>The <a href=\"https://docs.factorcode.org/content/word-dip,kernel.html\" rel=\"nofollow ugc noopener\"><code>dip</code></a> word temporarily hides a value while a quotation works on the stack below\nit. <a href=\"https://docs.factorcode.org/content/word-keep,kernel.html\" rel=\"nofollow ugc noopener\"><code>keep</code></a> gives a quotation a value and also preserves that value:</p>\n<pre><code>USING: kernel math prettyprint ;\n10 20 [ 1 + ] dip + .           ! 31: increment 10, then restore 20\n5 [ 1 + ] keep . .              ! Prints 5, then 6</code></pre>\n<pre><code>! dip   ( ..a x quot -- ..b x )\n! keep  ( ..a x quot -- ..b x )</code></pre>\n<p>The overall shapes look alike, but <code>dip</code> hides <code>x</code> from the quotation and\n<code>keep</code> passes it in. <a href=\"https://docs.factorcode.org/content/word-2dip%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>2dip</code></a> hides two values; <a href=\"https://docs.factorcode.org/content/word-2keep%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>2keep</code></a> preserves two inputs.</p>\n<h3 id=\"applying-several-quotations\">Applying several quotations</h3>\n<p>The <a href=\"https://docs.factorcode.org/content/article-cleave-combinators.html\" rel=\"nofollow ugc noopener\"><code>bi</code> family</a> covers several common ways to distribute inputs:</p>\n<pre><code>USING: kernel math prettyprint ;\n! Apply two quotations to the same input.\n5 [ 1 + ] [ 2 * ] bi . .        ! Prints 10, then 6\n! Apply one quotation to each of two inputs.\n3 4 [ 2 * ] bi@ . .             ! Prints 8, then 6\n! Apply separate quotations to separate inputs.\n3 4 [ 1 + ] [ 2 * ] bi* . .     ! Prints 8, then 4\n! Apply two quotations to the same pair of inputs.\n3 4 [ + ] [ * ] 2bi . .         ! Prints 12, then 7</code></pre>\n<p>For example, <a href=\"https://docs.factorcode.org/content/word-2bi%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>2bi</code></a> lets a word calculate two results from the same inputs:</p>\n<pre><code>USING: kernel math prettyprint ;\nIN: scratchpad\n: sum-and-product ( a b -- sum product )\n    [ + ] [ * ] 2bi ;\n3 4 sum-and-product . .         ! Prints 12, then 7</code></pre>\n<p>Then <a href=\"https://docs.factorcode.org/content/word-tri%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>tri</code></a>, <a href=\"https://docs.factorcode.org/content/word-tri__at__%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>tri@</code></a>, and <a href=\"https://docs.factorcode.org/content/word-tri__star__%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>tri*</code></a> extend these patterns to three quotations or\ninputs.</p>\n<p>You can find <a href=\"https://docs.factorcode.org/content/word-cleave%2Ccombinators.html\" rel=\"nofollow ugc noopener\"><code>cleave</code></a>, <a href=\"https://docs.factorcode.org/content/word-napply%2Cgeneralizations.html\" rel=\"nofollow ugc noopener\"><code>napply</code></a> and <a href=\"https://docs.factorcode.org/content/word-spread%2Ccombinators.html\" rel=\"nofollow ugc noopener\"><code>spread</code></a> as the generalizations\nof those patterns.</p>\n<h3 id=\"partial-application-and-composition\">Partial application and composition</h3>\n<p>The <a href=\"https://docs.factorcode.org/content/word-curry,kernel.html\" rel=\"nofollow ugc noopener\"><code>curry</code></a> word binds a value to the beginning of a quotation.\n<a href=\"https://docs.factorcode.org/content/word-compose,kernel.html\" rel=\"nofollow ugc noopener\"><code>compose</code></a> joins two\nquotations so that one runs after the other:</p>\n<pre><code>USING: kernel math prettyprint sequences ;\n{ 1 2 3 } 10 [ + ] curry map .    ! { 11 12 13 }\n5 [ 1 + ] [ 2 * ] compose call .  ! 12</code></pre>\n<p><code>10 [ + ] curry</code> behaves like <code>[ 10 + ]</code>. This is a convenient way to build\na quotation using a value computed at runtime.</p>\n<p>The <a href=\"https://docs.factorcode.org/content/article-fry.html\" rel=\"nofollow ugc noopener\"><code>fry</code> vocabulary</a> provides quotation templates. <a href=\"https://docs.factorcode.org/content/word-_%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>_</code></a> inserts a value;\n<a href=\"https://docs.factorcode.org/content/word-__at__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>@</code></a> inserts a call to a supplied quotation:</p>\n<pre><code>USING: fry kernel math prettyprint sequences ;\n{ 1 2 3 } 10 &#39;[ _ + ] map .     ! { 11 12 13 }\n5 [ 1 + ] &#39;[ @ 2 * ] call .     ! 12</code></pre>\n<p>The apostrophe in <code>&#39;[ ... ]</code> makes this a template rather than an ordinary\nquotation. Its placeholders consume their values when the template is\nconstructed, not when the resulting quotation is called.</p>\n<h3 id=\"defining-combinators\">Defining combinators</h3>\n<p>A combinator can be an ordinary word with quotation inputs. Give those\ninputs their own <a href=\"https://docs.factorcode.org/content/article-inference-combinators.html\" rel=\"nofollow ugc noopener\">stack effects</a> and declare the word <a href=\"https://docs.factorcode.org/content/word-inline%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>inline</code></a> so the\ncompiler can infer the effects at its call sites:</p>\n<pre><code>USING: kernel math prettyprint ;\nIN: scratchpad\n: twice ( ... quot: ( ... -- ... ) -- ... )\n    dup [ call ] dip call ; inline\n3 [ 2 * ] twice .               ! 12</code></pre>\n<p>The <code>...</code> represents values carried through the combinator. Here, the\nsupplied quotation must preserve stack height, and <code>twice</code> calls it twice.</p>\n<h3 id=\"loops-and-recursion\">Loops and recursion</h3>\n<pre><code>USING: kernel math prettyprint sequences ;\n3 [ &quot;hello&quot; . ] times           ! Print three times\n{ &quot;Ada&quot; &quot;Grace&quot; } [ . ] each    ! Visit each element\n5 &lt;iota&gt; [ . ] each             ! Print 0 through 4\n0 [ dup 3 &lt; ] [ dup . 1 + ] while drop\n! Print 0, 1, 2; keep the counter on the stack</code></pre>\n<p>The <a href=\"https://docs.factorcode.org/content/article-looping-combinators.html\" rel=\"nofollow ugc noopener\">looping combinator</a> <a href=\"https://docs.factorcode.org/content/word-while%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>while</code></a> calls its predicate before each iteration. The predicate leaves\na condition; the body updates the loop’s values. <a href=\"https://docs.factorcode.org/content/word-until%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>until</code></a> reverses the\ncondition. Often <a href=\"https://docs.factorcode.org/content/word-each%2Csequences.html\" rel=\"nofollow ugc noopener\"><code>each</code></a>, <a href=\"https://docs.factorcode.org/content/word-map%2Csequences.html\" rel=\"nofollow ugc noopener\"><code>map</code></a>, or <a href=\"https://docs.factorcode.org/content/word-reduce%2Csequences.html\" rel=\"nofollow ugc noopener\"><code>reduce</code></a> expresses the loop directly.</p>\n<p>Recursion uses an ordinary call to the word being defined:</p>\n<pre><code>USING: kernel math prettyprint ;\nIN: scratchpad\n: factorial ( n -- n! )\n    dup 1 &lt;=\n    [ drop 1 ]\n    [ dup 1 - factorial * ] if ;\n5 factorial .                   ! 120</code></pre>\n<p>Definitions are read in order: define helper words before words that use\nthem. <a href=\"https://docs.factorcode.org/content/article-deferred.html\" rel=\"nofollow ugc noopener\"><code>DEFER:</code></a>\ndeclares a word before its implementation, allowing mutual recursion:</p>\n<pre><code>USING: kernel math prettyprint ;\nIN: scratchpad\nDEFER: odd-count?\n: even-count? ( n -- ? )\n    dup 0 = [ drop t ] [ 1 - odd-count? ] if ;\n: odd-count? ( n -- ? )\n    dup 0 = [ drop f ] [ 1 - even-count? ] if ;\n6 even-count? .                 ! t\n7 odd-count? .                  ! t</code></pre>\n<p>These examples accept nonnegative integers. Factor guarantees\n<a href=\"https://docs.factorcode.org/content/article-tail-call-opt.html\" rel=\"nofollow ugc noopener\">tail-call optimization</a>,\nso a final call such as the one to <code>odd-count?</code> can continue without growing\nthe call stack.</p>\n<h3 id=\"local-variables-and-closures\">Local variables and closures</h3>\n<p>When names make an algorithm easier to read, import\n<a href=\"https://docs.factorcode.org/content/article-locals.html\" rel=\"nofollow ugc noopener\"><code>locals</code></a> and define\na word with <a href=\"https://docs.factorcode.org/content/word-__colon____colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>::</code></a>. Inputs become lexical variables:</p>\n<pre><code>USING: kernel locals math prettyprint sequences ;\nIN: scratchpad\n:: rectangle-area ( width height -- area )\n    width height * ;\n:: add-offset ( seq offset -- newseq )\n    seq [| n | n offset + ] map ;\n3 4 rectangle-area .            ! 12\n{ 1 2 3 } 10 add-offset .       ! { 11 12 13 }\n:: hypotenuse-squared ( a b -- n )\n    a a * :&gt; a-squared\n    b b * :&gt; b-squared\n    a-squared b-squared + ;</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/word-__colon____gt__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>:&gt;</code></a> binds a computed value. <a href=\"https://docs.factorcode.org/content/word-%5B__pipe__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>\\[| n | ... \\]</code></a> names quotation inputs and can\ncapture enclosing variables, as <code>offset</code> does above. Output names in <a href=\"https://docs.factorcode.org/content/word-__colon____colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>::</code></a>\nstill describe stack results; there is no implicit return variable.</p>\n<p><a href=\"https://docs.factorcode.org/content/article-locals-mutable.html\" rel=\"nofollow ugc noopener\">Mutable locals</a> have an exclamation point in their declaration and an\nassociated setter:</p>\n<pre><code>USING: kernel locals math prettyprint ;\n[let\n    0 :&gt; total!\n    5 [ total 1 + total! ] times\n    total .                     ! 5\n]</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/word-%5Blet%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>\\[let ... \\]</code></a> establishes a lexical scope, including in the listener.</p>\n<h3 id=\"sequences\">Sequences</h3>\n<p>Arrays, vectors, strings, and several other types share the sequence\n<a href=\"https://docs.factorcode.org/content/article-sequence-protocol.html\" rel=\"nofollow ugc noopener\">protocol</a>. Most sequence words work across these types:</p>\n<pre><code>USING: kernel math prettyprint sequences sorting ;\n{ 10 20 30 } length .               ! 3\n{ 10 20 30 } first .                ! 10\n1 { 10 20 30 } nth .                ! 20, zero-based indexing\n{ 1 2 } { 3 4 } append .            ! { 1 2 3 4 }\n{ 1 2 3 } reverse .                 ! { 3 2 1 }\n{ 1 2 3 4 } [ dup * ] map .         ! { 1 4 9 16 }\n{ 1 2 3 4 } [ 2 mod 0 = ] filter .  ! { 2 4 }\n{ 1 2 3 4 } 0 [ + ] reduce .        ! 10\n{ 1 2 3 } [ 0 &gt; ] all? .            ! t\n{ 1 2 3 } [ 2 = ] any? .            ! t\n{ 3 1 2 } natural-sort .            ! { 1 2 3 }\nV{ 1 2 } clone\n3 over push .                       ! V{ 1 2 3 }</code></pre>\n<p>The <a href=\"https://docs.factorcode.org/content/article-sequences-combinators.html\" rel=\"nofollow ugc noopener\">sequence combinator</a> <a href=\"https://docs.factorcode.org/content/word-map%2Csequences.html\" rel=\"nofollow ugc noopener\"><code>map</code></a> collects quotation results; <a href=\"https://docs.factorcode.org/content/word-each%2Csequences.html\" rel=\"nofollow ugc noopener\"><code>each</code></a> is for side effects. <a href=\"https://docs.factorcode.org/content/word-reduce%2Csequences.html\" rel=\"nofollow ugc noopener\"><code>reduce</code></a>\nthreads an accumulator through the sequence. <a href=\"https://docs.factorcode.org/content/word-push%2Csequences.html\" rel=\"nofollow ugc noopener\"><code>push</code></a> mutates a growable\nsequence and consumes both the new element and the sequence.</p>\n<p>For incremental construction, <a href=\"https://docs.factorcode.org/content/article-namespaces-make.html\" rel=\"nofollow ugc noopener\"><code>make</code></a>\ncollects values produced inside a quotation. <a href=\"https://docs.factorcode.org/content/word-__comma__%2Cmake.html\" rel=\"nofollow ugc noopener\"><code>,</code></a> adds one element and <a href=\"https://docs.factorcode.org/content/word-__percent__%2Cmake.html\" rel=\"nofollow ugc noopener\"><code>%</code></a>\nadds the elements of a sequence:</p>\n<pre><code>USING: make prettyprint ;\n[ 1 , { 2 3 } % 4 , ] { } make .            ! { 1 2 3 4 }\n[ &quot;Hello&quot; % CHAR: \\s , &quot;Ada&quot; % ] &quot;&quot; make .  ! &quot;Hello Ada&quot;</code></pre>\n<p>The final exemplar (<code>{ }</code> or <code>&quot;&quot;</code>) chooses the result type. Prefer <a href=\"https://docs.factorcode.org/content/word-map%2Csequences.html\" rel=\"nofollow ugc noopener\"><code>map</code></a>,\n<a href=\"https://docs.factorcode.org/content/word-filter%2Csequences.html\" rel=\"nofollow ugc noopener\"><code>filter</code></a>, or <a href=\"https://docs.factorcode.org/content/word-append%2Csequences.html\" rel=\"nofollow ugc noopener\"><code>append</code></a> when one of those directly expresses the operation.</p>\n<p><a href=\"https://docs.factorcode.org/content/article-specialized-arrays.html\" rel=\"nofollow ugc noopener\"><code>Specialized arrays</code></a>\nstore elements as C numeric types in contiguous memory while supporting\nthe sequence protocol:</p>\n<pre><code>USING: alien.c-types prettyprint sequences specialized-arrays ;\nSPECIALIZED-ARRAY: double\ndouble-array{ 1.0 2.0 3.0 } length .  ! 3</code></pre>\n<h3 id=\"hashtables-and-sets\">Hashtables and sets</h3>\n<p>Associative collections use the <a href=\"https://docs.factorcode.org/content/article-assocs.html\" rel=\"nofollow ugc noopener\"><code>assocs</code> protocol</a>:</p>\n<pre><code>USING: assocs kernel prettyprint ;\n&quot;Ada&quot; H{ { &quot;Ada&quot; 36 } { &quot;Grace&quot; 85 } } at .  ! 36\n&quot;missing&quot; H{ { &quot;Ada&quot; 36 } } at .             ! f\n&quot;enabled&quot; H{ { &quot;enabled&quot; f } } at* . .       ! Prints t, then f\nH{ { &quot;Ada&quot; 36 } } clone\n37 &quot;Ada&quot; pick set-at\n&quot;Ada&quot; swap at .                              ! 37</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/word-at__star__%2Cassocs.html\" rel=\"nofollow ugc noopener\"><code>at*</code></a> returns a presence flag as well as a value, distinguishing a missing\nkey from a key whose value is <a href=\"https://docs.factorcode.org/content/word-f%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>f</code></a>. <a href=\"https://docs.factorcode.org/content/word-set-at%2Cassocs.html\" rel=\"nofollow ugc noopener\"><code>set-at</code></a> takes a value, key, and assoc.</p>\n<p><a href=\"https://docs.factorcode.org/content/article-sets.html\" rel=\"nofollow ugc noopener\">Sets</a> also have a protocol, with useful operations on ordinary sequences:</p>\n<pre><code>USING: prettyprint sets ;\n{ 1 2 2 3 } members .           ! { 1 2 3 }\n2 { 1 2 3 } in? .               ! t\n{ 1 2 } { 2 3 } union .         ! { 1 2 3 }\n{ 1 2 } { 2 3 } intersect .     ! { 2 }\n{ 1 2 } { 2 3 } diff .          ! { 1 }</code></pre>\n<p>For repeated membership checks, use a hash set rather than scanning a sequence:</p>\n<pre><code>USING: hash-sets prettyprint sets ;\n2 HS{ 1 2 3 } in? .             ! t</code></pre>\n<h3 id=\"tuples-and-accessors\">Tuples and accessors</h3>\n<p><a href=\"https://docs.factorcode.org/content/article-tuples.html\" rel=\"nofollow ugc noopener\">Tuples</a> define classes with named slots. <a href=\"https://docs.factorcode.org/content/word-boa%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>boa</code></a> constructs a tuple from\nslot values in declaration order:</p>\n<pre><code>USING: accessors kernel prettyprint ;\nIN: scratchpad\nTUPLE: person name age ;\nC: &lt;person&gt; person\n&quot;Ada&quot; 36 &lt;person&gt;\ndup name&gt;&gt; .                    ! &quot;Ada&quot;\n37 &gt;&gt;age\nage&gt;&gt; .                         ! 37</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/word-C__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>C:</code></a> defines a constructor using <a href=\"https://docs.factorcode.org/content/word-boa%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>boa</code></a>. <a href=\"https://docs.factorcode.org/content/article-accessors.html\" rel=\"nofollow ugc noopener\"><code>name&gt;&gt;</code></a> reads a slot; <a href=\"https://docs.factorcode.org/content/article-accessors.html\" rel=\"nofollow ugc noopener\"><code>&gt;&gt;age</code></a>\nwrites a slot and returns the tuple, allowing chained updates. You can also\nconstruct an instance with <code>person new</code> and set its slots explicitly.\nNames such as <code>&lt;person&gt;</code> conventionally denote constructors; the angle\nbrackets are part of the word’s name.</p>\n<p>Tuple literals use <a href=\"https://docs.factorcode.org/content/word-T%7B%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>T{ ... }</code></a>. Slots can also declare a class, an initial\nvalue, or the <a href=\"https://docs.factorcode.org/content/word-read-only%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>read-only</code></a> attribute:</p>\n<pre><code>USING: accessors kernel math prettyprint ;\nIN: scratchpad\nT{ person { name &quot;Grace&quot; } { age 85 } } name&gt;&gt; .  ! &quot;Grace&quot;\nTUPLE: counter { value integer initial: 0 } ;\ncounter new\n[ 1 + ] change-value\nvalue&gt;&gt; .                                         ! 1</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/article-tuple-declarations.html\" rel=\"nofollow ugc noopener\"><code>Slot declarations</code></a>\nconstrain stored values. <code>{ name string read-only }</code>, for example, declares\na string slot that is initialized at construction and has no generated\nsetter. <a href=\"https://docs.factorcode.org/content/article-accessors.html\" rel=\"nofollow ugc noopener\"><code>change-value</code></a> applies a quotation to the current slot value,\nstores the result, and returns the tuple.</p>\n<h3 id=\"structs-and-c-layouts\">Structs and C layouts</h3>\n<p><a href=\"https://docs.factorcode.org/content/article-classes.struct.html\" rel=\"nofollow ugc noopener\"><code>STRUCT:</code></a>\ndefines a record backed by a C memory layout. Every field declares a C\ntype, and the usual slot accessors work on struct instances:</p>\n<pre><code>USING: accessors alien.c-types classes.struct kernel prettyprint ;\nIN: scratchpad\nSTRUCT: c-point\n    { x double }\n    { y double } ;\n3.0 4.0 c-point boa\ndup x&gt;&gt; .                       ! 3.0\ny&gt;&gt; .                           ! 4.0\nPACKED-STRUCT: packet-header\n    { kind uint8_t }\n    { length uint32_t } ;\npacket-header heap-size .       ! 5</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/word-boa%2Ckernel.html\" rel=\"nofollow ugc noopener\"><code>boa</code></a> initializes fields from stack values; <code>c-point &lt;struct&gt;</code> creates an\ninstance with its declared initial field values. These constructors use\ngarbage-collected storage. <a href=\"https://docs.factorcode.org/content/word-STRUCT__colon__%2Cclasses.struct.html\" rel=\"nofollow ugc noopener\"><code>STRUCT:</code></a> includes alignment padding according\nto the platform’s C layout rules. <a href=\"https://docs.factorcode.org/content/word-PACKED-STRUCT__colon__%2Cclasses.struct.html\" rel=\"nofollow ugc noopener\"><code>PACKED-STRUCT:</code></a> removes padding between\nfields and at the end, for layouts that explicitly require packed storage.\nIt does not choose byte order.</p>\n<p><a href=\"https://docs.factorcode.org/content/word-UNION-STRUCT__colon__%2Cclasses.struct.html\" rel=\"nofollow ugc noopener\"><code>UNION-STRUCT:</code></a> defines overlapping C fields that share the same storage.\nIt serves a different purpose from <a href=\"https://docs.factorcode.org/content/word-UNION__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>UNION:</code></a>, which groups Factor classes.\nUse tuples for ordinary Factor records and structs when you need C-compatible\nmemory or an explicitly specified binary layout.</p>\n<h3 id=\"generic-words-and-classes\">Generic words and classes</h3>\n<p>A <a href=\"https://docs.factorcode.org/content/article-generic.html\" rel=\"nofollow ugc noopener\">generic word</a> chooses a method based on the class of its topmost input.\nThis example reuses <code>person</code> and <code>&lt;person&gt;</code> from “Tuples and accessors”:</p>\n<pre><code>USING: accessors kernel math math.parser prettyprint ;\nIN: scratchpad\nGENERIC: description ( obj -- string )\nM: person description name&gt;&gt; ;\nM: integer description number&gt;string ;\n&quot;Ada&quot; 36 &lt;person&gt; description .  ! &quot;Ada&quot;\n42 description .                 ! &quot;42&quot;</code></pre>\n<p>A <a href=\"https://docs.factorcode.org/content/article-tuple-subclassing.html\" rel=\"nofollow ugc noopener\">tuple subclass</a>\ninherits its parent’s slots and can add its own. An overriding method can\nreuse the next less-specific method with\n<a href=\"https://docs.factorcode.org/content/article-call-next-method.html\" rel=\"nofollow ugc noopener\"><code>call-next-method</code></a>:</p>\n<pre><code>USING: accessors kernel prettyprint sequences ;\nIN: scratchpad\nTUPLE: employee &lt; person role ;\nC: &lt;employee&gt; employee\nM: employee description\n    [ call-next-method ] [ role&gt;&gt; ] bi &quot; - &quot; glue ;\n&quot;Ada&quot; 36 &quot;programmer&quot; &lt;employee&gt; description .\n! &quot;Ada - programmer&quot;</code></pre>\n<p>The constructor takes inherited slots first (<code>name</code>, <code>age</code>), then <code>role</code>.\nHere <a href=\"https://docs.factorcode.org/content/word-call-next-method%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>call-next-method</code></a> receives the employee, calls the <code>person</code> method,\nand returns <code>&quot;Ada&quot;</code>; the override combines that with the employee’s role.\nIt must appear inside a method definition and receives its inputs from the\nstack, just like an ordinary call.</p>\n<p><a href=\"https://docs.factorcode.org/content/word-M__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>M:</code></a> defines a method. This is how protocols such as sequences and assocs\nprovide common operations for many concrete types. Classes also have\npredicate words, and you can define narrower predicate classes or unions:</p>\n<pre><code>USING: kernel math prettyprint strings ;\nIN: scratchpad\nPREDICATE: positive-integer &lt; integer 0 &gt; ;\nUNION: text-or-integer string integer ;\n3 positive-integer? .           ! t\n-3 positive-integer? .          ! f\n&quot;hello&quot; text-or-integer? .      ! t</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/article-mixins.html\" rel=\"nofollow ugc noopener\"><code>Mixin classes</code></a>\nare open groups of classes: <a href=\"https://docs.factorcode.org/content/word-INSTANCE__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>INSTANCE:</code></a> adds a member, including after the\nmixin was defined. They are useful for protocols spanning unrelated types:</p>\n<pre><code>USING: prettyprint ;\nIN: scratchpad\nMIXIN: named\nINSTANCE: person named\n&quot;Ada&quot; 36 &lt;person&gt; named? .      ! t</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/article-singletons.html\" rel=\"nofollow ugc noopener\"><code>Singleton classes</code></a>\neach have one stateless instance, useful as distinct states or options.\nUnlike a plain symbol, each can have its own generic methods:</p>\n<pre><code>USING: prettyprint ;\nIN: scratchpad\nSINGLETONS: pending running finished ;\nUNION: job-state pending running finished ;\npending job-state? .            ! t</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/word-UNION__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>UNION:</code></a> accepts instances of any listed class. <a href=\"https://docs.factorcode.org/content/word-INTERSECTION__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>INTERSECTION:</code></a> requires\nmembership in all listed classes. For named numeric values,\n<a href=\"https://docs.factorcode.org/content/article-enums.html\" rel=\"nofollow ugc noopener\"><code>ENUMERATION:</code></a>\nis available in <a href=\"https://docs.factorcode.org/content/vocab-classes.enumeration.html\" rel=\"nofollow ugc noopener\"><code>classes.enumeration</code></a>:</p>\n<pre><code>USING: classes.enumeration prettyprint ;\nIN: scratchpad\nENUMERATION: priority low medium high ;\npriority.low .                  ! 0\npriority.high .                 ! 2</code></pre>\n<h3 id=\"symbols-and-dynamic-variables\">Symbols and dynamic variables</h3>\n<p>Lexical locals are scoped by source structure. <a href=\"https://docs.factorcode.org/content/vocab-namespaces.html\" rel=\"nofollow ugc noopener\"><code>namespaces</code></a> provides\n<a href=\"https://docs.factorcode.org/content/article-namespaces.html\" rel=\"nofollow ugc noopener\">variables scoped dynamically</a> around a quotation:</p>\n<pre><code>USING: namespaces prettyprint ;\nIN: scratchpad\nSYMBOL: current-user\n&quot;Ada&quot; current-user [\n    current-user get .          ! &quot;Ada&quot;\n] with-variable</code></pre>\n<p>Called words inside the quotation see the binding too. <a href=\"https://docs.factorcode.org/content/word-with-variable%2Cnamespaces.html\" rel=\"nofollow ugc noopener\"><code>with-variable</code></a>\nrestores the previous binding on exit. <a href=\"https://docs.factorcode.org/content/word-set%2Cnamespaces.html\" rel=\"nofollow ugc noopener\"><code>set</code></a> changes a binding in the\ncurrent namespace; <a href=\"https://docs.factorcode.org/content/word-set-global%2Cnamespaces.html\" rel=\"nofollow ugc noopener\"><code>set-global</code></a> sets a global binding. A symbol is itself\na value, so symbols also work as distinct markers and hashtable keys.</p>\n<h3 id=\"errors-and-cleanup\">Errors and cleanup</h3>\n<pre><code>USING: continuations kernel prettyprint ;\nIN: scratchpad\nERROR: invalid-age age ;\n[ -1 invalid-age ] [ drop &quot;handled&quot; ] recover .  ! &quot;handled&quot;\n[ &quot;work&quot; . ] [ &quot;cleanup&quot; . ] finally\n! Prints &quot;work&quot;, then &quot;cleanup&quot;</code></pre>\n<p>The <a href=\"https://docs.factorcode.org/content/article-errors.html\" rel=\"nofollow ugc noopener\">exception handling</a> form <a href=\"https://docs.factorcode.org/content/word-ERROR__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>ERROR:</code></a> defines an error class and a word that throws an instance.\n<a href=\"https://docs.factorcode.org/content/word-recover%2Ccontinuations.html\" rel=\"nofollow ugc noopener\"><code>recover</code></a> calls a handler with the thrown object. The data stack is restored\nto its state before the protected quotation, then the error is pushed.\n<a href=\"https://docs.factorcode.org/content/word-finally%2Ccontinuations.html\" rel=\"nofollow ugc noopener\"><code>finally</code></a> runs cleanup on either normal completion or an error.</p>\n<p>Factor also exposes <a href=\"https://docs.factorcode.org/content/article-continuations.html\" rel=\"nofollow ugc noopener\">continuations</a>,\nwhich capture execution state and can later resume it. They underpin error\nhandling and cooperative threads; most everyday code uses those higher-level\nfacilities directly.</p>\n<h3 id=\"resource-disposal\">Resource disposal</h3>\n<p>Ordinary objects are garbage collected. Resources such as open streams\nalso need <a href=\"https://docs.factorcode.org/content/article-destructors.html\" rel=\"nofollow ugc noopener\">deterministic disposal</a>.\n<a href=\"https://docs.factorcode.org/content/word-dispose%2Cdestructors.html\" rel=\"nofollow ugc noopener\"><code>dispose</code></a> releases a resource explicitly. <a href=\"https://docs.factorcode.org/content/word-with-disposal%2Cdestructors.html\" rel=\"nofollow ugc noopener\"><code>with-disposal</code></a> passes a resource\nto a quotation and disposes it when the quotation finishes or throws:</p>\n<pre><code>USING: destructors io io.encodings.utf8 io.files prettyprint ;\n&quot;Hello!\\n&quot; &quot;disposal.txt&quot; utf8 set-file-contents\n&quot;disposal.txt&quot; utf8 &lt;file-reader&gt;\n[ stream-readln . ] with-disposal  ! &quot;Hello!&quot;</code></pre>\n<p>This example creates <code>disposal.txt</code> in the current directory. The reader\nis closed after reading the line. For several resources, use\n<a href=\"https://docs.factorcode.org/content/article-destructors-using.html\" rel=\"nofollow ugc noopener\"><code>with-destructors</code></a>\nand register each one for cleanup:</p>\n<pre><code>USING: destructors io io.encodings.utf8 io.files prettyprint ;\n[\n    &quot;disposal.txt&quot; utf8 &lt;file-reader&gt; &amp;dispose\n    stream-readln .             ! &quot;Hello!&quot;\n] with-destructors</code></pre>\n<p>Both registration words leave the resource on the stack so you can use it:</p>\n<div class=\"table-wrap\"><table><thead><tr><th>Word</th><th>When the resource is disposed</th></tr></thead><tbody><tr><td><a href=\"https://docs.factorcode.org/content/word-%26dispose%2Cdestructors.html\" rel=\"nofollow ugc noopener\"><code>&amp;dispose</code></a></td><td>When the enclosing <a href=\"https://docs.factorcode.org/content/word-with-destructors%2Cdestructors.html\" rel=\"nofollow ugc noopener\"><code>with-destructors</code></a> scope finishes, on success or error</td></tr><tr><td><a href=\"https://docs.factorcode.org/content/word-__pipe__dispose%2Cdestructors.html\" rel=\"nofollow ugc noopener\"><code>|dispose</code></a></td><td>When the enclosing <a href=\"https://docs.factorcode.org/content/word-with-destructors%2Cdestructors.html\" rel=\"nofollow ugc noopener\"><code>with-destructors</code></a> scope exits with an error</td></tr></tbody></table></div>\n<p><a href=\"https://docs.factorcode.org/content/word-%26dispose%2Cdestructors.html\" rel=\"nofollow ugc noopener\"><code>&amp;dispose</code></a> is for resources used within a scope. <a href=\"https://docs.factorcode.org/content/word-__pipe__dispose%2Cdestructors.html\" rel=\"nofollow ugc noopener\"><code>|dispose</code></a> is useful when\nbuilding a result that owns resources: if construction fails, clean up;\nif it succeeds, return the resources to the caller. For example:</p>\n<pre><code>USING: destructors io.encodings.utf8 io.files kernel ;\nIN: scratchpad\n: open-two-readers ( path1 path2 -- reader1 reader2 )\n    [ [ utf8 &lt;file-reader&gt; |dispose ] bi@ ] with-destructors ;\n&quot;disposal.txt&quot; &quot;disposal.txt&quot; open-two-readers\n[ dispose ] bi@                 ! Caller closes both readers</code></pre>\n<p>If opening the second reader throws, the first reader is disposed. On\nsuccess, both readers remain open and the caller owns their cleanup.\nWithin each registration group, destructors run in reverse registration\norder. The <a href=\"https://docs.factorcode.org/content/word-with-file-reader%2Cio.files.html\" rel=\"nofollow ugc noopener\"><code>with-file-reader</code></a> and <a href=\"https://docs.factorcode.org/content/word-with-file-writer%2Cio.files.html\" rel=\"nofollow ugc noopener\"><code>with-file-writer</code></a> combinators shown below\nmanage stream cleanup automatically.</p>\n<h3 id=\"vocabularies\">Vocabularies</h3>\n<p>A <a href=\"https://docs.factorcode.org/content/article-vocabularies.html\" rel=\"nofollow ugc noopener\">vocabulary</a> is a namespace and a unit of source organization. A vocabulary\nnamed <code>examples.greeting</code> conventionally lives in\n<code>examples/greeting/greeting.factor</code> under a vocabulary root:</p>\n<pre><code>USING: io ;\nIN: examples.greeting\n&lt;PRIVATE\n: greeting ( -- string ) &quot;Hello, world!&quot; ;\nPRIVATE&gt;\n: greet ( -- ) greeting print ;\nMAIN: greet</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/word-__lt__PRIVATE%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>&lt;PRIVATE ... PRIVATE&gt;</code></a> places helper definitions in the vocabulary’s\nprivate namespace. Import public definitions with <code>USE: examples.greeting</code>\nor include it in a <a href=\"https://docs.factorcode.org/content/word-USING__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>USING:</code></a> list. Run the entry point with\n<code>./factor -run=examples.greeting</code> once its directory is in a vocabulary\n<a href=\"https://docs.factorcode.org/content/article-vocabs.roots.html\" rel=\"nofollow ugc noopener\">root</a>, such as your installation’s <code>work</code> directory. Dots organize vocabulary\nnames; importing a parent does not automatically import its children.</p>\n<p>Source files need explicit imports. If a word is missing, its documentation\nshows which vocabulary provides it. The listener may offer to import a word\nautomatically; include that vocabulary in <a href=\"https://docs.factorcode.org/content/word-USING__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>USING:</code></a> when saving the code.\nFor <a href=\"https://docs.factorcode.org/content/article-word-search.html\" rel=\"nofollow ugc noopener\">ambiguous names</a>,\nuse a vocabulary prefix or select a word with <a href=\"https://docs.factorcode.org/content/word-FROM__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>FROM:</code></a>:</p>\n<pre><code>USING: math prettyprint ;\n2 3 math:+ .                    ! 5\nFROM: math =&gt; + ;\n2 3 + .                         ! 5</code></pre>\n<h3 id=\"editing-and-reloading\">Editing and reloading</h3>\n<p>Factor’s listener runs in a live image containing loaded definitions and\nobjects. You can redefine a word and try it again in the same session.\nFor code saved in a vocabulary, load it once with <a href=\"https://docs.factorcode.org/content/word-USE__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>USE:</code></a>, then\n<a href=\"https://docs.factorcode.org/content/article-vocabs.refresh.html\" rel=\"nofollow ugc noopener\">reload changes</a>\nafter editing its source:</p>\n<pre><code>USING: vocabs.loader vocabs.refresh ;\nUSE: examples.greeting\n&quot;examples.greeting&quot; reload      ! Reload this vocabulary\nrefresh-all                     ! Reload changed files in loaded vocabularies</code></pre>\n<p>This assumes you saved <code>examples.greeting</code> in a vocabulary root as above.\nThe <a href=\"https://docs.factorcode.org/content/article-tools.scaffold.html\" rel=\"nofollow ugc noopener\">scaffold tool</a>\ncan create source, documentation, and test files for a new vocabulary.</p>\n<h3 id=\"code-as-data-macros-and-parsing-words\">Code as data, macros, and parsing words</h3>\n<p>Words are objects too. A backslash obtains a word without executing it:</p>\n<pre><code>USING: accessors math prettyprint words ;\n\\ + name&gt;&gt; .                    ! &quot;+&quot;</code></pre>\n<p>Quotations are built out of objects and words.\n<a href=\"https://docs.factorcode.org/content/article-macros.html\" rel=\"nofollow ugc noopener\">Macros</a> compute quotations\nthat the compiler expands at call sites:</p>\n<pre><code>USING: kernel macros math prettyprint ;\nIN: scratchpad\nMACRO: add-constant ( n -- quot ) [ + ] curry ;\n5 10 add-constant .             ! 15</code></pre>\n<p>Here <code>10</code> is the macro input, and the expansion adds it to the runtime\nvalue <code>5</code>. Macro inputs must be known at compile time.</p>\n<p>Syntax is extensible through <a href=\"https://docs.factorcode.org/content/article-parsing-words.html\" rel=\"nofollow ugc noopener\"><em>parsing words</em></a>, which execute while source\nis being read. <code>:</code>, <a href=\"https://docs.factorcode.org/content/word-TUPLE__colon__%2Csyntax.html\" rel=\"nofollow ugc noopener\"><code>TUPLE:</code></a>, and literal openers are examples. Libraries\ncan add their own syntax, such as <code>R/ ... /</code> for regular expressions.</p>\n<h3 id=\"memoization\">Memoization</h3>\n<p><a href=\"https://docs.factorcode.org/content/article-memoize.html\" rel=\"nofollow ugc noopener\"><code>MEMO:</code></a> defines a word whose results are cached by its inputs:</p>\n<pre><code>USING: kernel math memoize prettyprint ;\nIN: scratchpad\nMEMO: fibonacci ( n -- m )\n    dup 1 &lt;= [ ] [\n        [ 1 - fibonacci ] [ 2 - fibonacci ] bi +\n    ] if ;\n10 fibonacci .                  ! 55</code></pre>\n<p>This is useful for pure computations. Cached mutable results are shared objects, so memoization needs care when callers mutate those results.</p>\n<h3 id=\"files-and-formatted-output\">Files and formatted output</h3>\n<pre><code>USING: formatting io io.encodings.utf8 io.files prettyprint ;\n&quot;Ada&quot; 36 &quot;%s is %d years old.\\n&quot; printf\n&quot;Hello, world!\\n&quot; &quot;hello.txt&quot; utf8 set-file-contents\n&quot;hello.txt&quot; utf8 file-contents print\n&quot;hello.txt&quot; utf8 [\n    readln .\n] with-file-reader</code></pre>\n<p>The <a href=\"https://docs.factorcode.org/content/article-io.files.html\" rel=\"nofollow ugc noopener\">file examples</a> create <code>hello.txt</code> in the current directory.\n<a href=\"https://docs.factorcode.org/content/article-formatting.html\" rel=\"nofollow ugc noopener\"><code>formatting</code></a> provides <a href=\"https://docs.factorcode.org/content/word-printf%2Cformatting.html\" rel=\"nofollow ugc noopener\"><code>printf</code></a> for formatted output.\n<a href=\"https://docs.factorcode.org/content/word-with-file-reader%2Cio.files.html\" rel=\"nofollow ugc noopener\"><code>with-file-reader</code></a> binds the current input stream and closes it after the\nquotation finishes. <a href=\"https://docs.factorcode.org/content/word-with-file-writer%2Cio.files.html\" rel=\"nofollow ugc noopener\"><code>with-file-writer</code></a> does the same for output.</p>\n<h3 id=\"json-regular-expressions-and-http\">JSON, regular expressions, and HTTP</h3>\n<p>The <a href=\"https://docs.factorcode.org/content/article-json.html\" rel=\"nofollow ugc noopener\"><code>json</code> vocabulary</a> converts between JSON text and Factor objects:</p>\n<pre><code>USING: assocs json kernel prettyprint ;\n&quot;{\\&quot;name\\&quot;:\\&quot;Ada\\&quot;,\\&quot;age\\&quot;:36}&quot; json&gt;\n&quot;name&quot; swap at .                ! &quot;Ada&quot;\nH{ { &quot;name&quot; &quot;Ada&quot; } } &gt;json .   ! &quot;{\\&quot;name\\&quot;:\\&quot;Ada\\&quot;}&quot;</code></pre>\n<p><a href=\"https://docs.factorcode.org/content/article-regexp.html\" rel=\"nofollow ugc noopener\">Regular expressions</a> use their own literal syntax:</p>\n<pre><code>USING: prettyprint regexp ;\n&quot;12345&quot; R/ [0-9]+/ matches? .   ! t\n&quot;hello&quot; R/ [0-9]+/ matches? .   ! f</code></pre>\n<p>The <a href=\"https://docs.factorcode.org/content/article-http.client.html\" rel=\"nofollow ugc noopener\">HTTP client</a> returns both a response object and the downloaded content:</p>\n<pre><code>USING: http.client kernel ;\n&quot;https://factorcode.org&quot; http-get\nnip                             ! Leave only the content</code></pre>\n<h3 id=\"dates-and-calendars\">Dates and calendars</h3>\n<p><a href=\"https://docs.factorcode.org/content/article-calendar.html\" rel=\"nofollow ugc noopener\"><code>calendar</code></a> provides timestamps and durations and computations on them.</p>\n<pre><code>USING: calendar prettyprint ;\nnow .                              ! Current local timestamp\n10 months duration&gt;minutes         ! Lots of minutes\ntoday next-monday                  ! The next monday after today</code></pre>\n<h3 id=\"random\">Random</h3>\n<p><a href=\"https://docs.factorcode.org/content/article-random.html\" rel=\"nofollow ugc noopener\"><code>random</code></a> selects random numbers or collection elements:</p>\n<pre><code>USING: prettyprint random ;\n10 random .                        ! Random integer from 0 through 9\n{ &quot;red&quot; &quot;green&quot; &quot;blue&quot; } random .  ! Random element</code></pre>\n<p>We also have various random distributions available.</p>\n<h3 id=\"threads\">Threads</h3>\n<p>Factor <a href=\"https://docs.factorcode.org/content/article-threads.html\" rel=\"nofollow ugc noopener\">threads</a> are cooperatively scheduled. <a href=\"https://docs.factorcode.org/content/word-yield%2Cthreads.html\" rel=\"nofollow ugc noopener\"><code>yield</code></a> lets another runnable\nthread execute, and blocking I/O integrates with the scheduler:</p>\n<pre><code>USING: kernel math prettyprint threads ;\n42 [ 1 + . ] curry &quot;worker&quot; spawn drop\nyield                           ! Worker prints 43</code></pre>\n<p>The worker starts with an empty data stack; <code>curry</code> explicitly carries the\ninput into its quotation. The <code>concurrency</code> vocabularies provide additional\ntools such as mailboxes and promises.</p>\n<h3 id=\"calling-c\">Calling C</h3>\n<p>The <a href=\"https://docs.factorcode.org/content/article-alien-invoke.html\" rel=\"nofollow ugc noopener\">foreign function interface</a> declares C functions as Factor words.\nFor example, this binds <code>strlen</code> from the C library:</p>\n<pre><code>USING: alien.c-types alien.syntax prettyprint ;\nIN: scratchpad\nLIBRARY: libc\nFUNCTION: size_t strlen ( c-string str )\n&quot;hello&quot; strlen .                ! 5</code></pre>\n<p>The <a href=\"https://docs.factorcode.org/content/word-c-string%2Calien.c-types.html\" rel=\"nofollow ugc noopener\"><code>c-string</code></a> argument converts a Factor string for the C call. The FFI\nalso supports structures, pointers, callbacks, and arrays. Unlike the\nmanaged objects used above, foreign allocations can require explicit\nlifetime management.</p>\n<h3 id=\"testing-and-exploring\">Testing and exploring</h3>\n<p><a href=\"https://docs.factorcode.org/content/article-tools.test.html\" rel=\"nofollow ugc noopener\"><code>tools.test</code></a> expresses expected stack results as an array:</p>\n<pre><code>USING: kernel math tools.test ;\n{ 5 } [ 2 3 + ] unit-test\n{ 25 } [ 5 dup * ] unit-test\n[ 1 0 / ] must-fail</code></pre>\n<p>Tests for a vocabulary conventionally live alongside its source in a\n<code>*-tests.factor</code> file. After saving tests for <code>examples.greeting</code>, run them\nwith <code>&quot;examples.greeting&quot; test</code> in the listener. This also runs tests in\nits child vocabularies.</p>\n<p>The development environment also lets you inspect definitions, look up documentation, and time quotations:</p>\n<pre><code>USING: help kernel math see sequences tools.time ;\n\\ map help                      ! Open documentation for map\n\\ + describe                    ! Describe the object ``+``\n\\ square see                    ! Show the earlier definition\n[ 1000000 [ ] times ] time      ! Time a quotation</code></pre>\n<p>The <a href=\"https://docs.factorcode.org/content/article-handbook.html\" rel=\"nofollow ugc noopener\">Factor handbook</a>\nis the next stop for more detail. For a project walkthrough, the\n<a href=\"https://docs.factorcode.org/content/article-first-program.html\" rel=\"nofollow ugc noopener\">first-program tutorial</a>\ncovers creating a vocabulary, editing and reloading it, and extending it\nwith tests. The\n<a href=\"https://docs.factorcode.org/content/article-vocab-index.html\" rel=\"nofollow ugc noopener\">vocabulary index</a> covers\nthe libraries, and the source distribution includes documentation and tests\nnext to the code. Start with small words, follow their stack effects, and\nuse combinators to make the flow of values clear.</p>","headings":[{"level":1,"text":"Factor Overview","id":"factor-overview"},{"level":3,"text":"Hello, world","id":"hello-world"},{"level":3,"text":"Values and the stack","id":"values-and-the-stack"},{"level":3,"text":"Comments and literals","id":"comments-and-literals"},{"level":3,"text":"Strings and escape characters","id":"strings-and-escape-characters"},{"level":3,"text":"Stack shuffling","id":"stack-shuffling"},{"level":3,"text":"Defining words","id":"defining-words"},{"level":3,"text":"Arithmetic and comparisons","id":"arithmetic-and-comparisons"},{"level":3,"text":"Quotations","id":"quotations"},{"level":3,"text":"Booleans and conditionals","id":"booleans-and-conditionals"},{"level":3,"text":"Keeping and hiding values","id":"keeping-and-hiding-values"},{"level":3,"text":"Applying several quotations","id":"applying-several-quotations"},{"level":3,"text":"Partial application and composition","id":"partial-application-and-composition"},{"level":3,"text":"Defining combinators","id":"defining-combinators"},{"level":3,"text":"Loops and recursion","id":"loops-and-recursion"},{"level":3,"text":"Local variables and closures","id":"local-variables-and-closures"},{"level":3,"text":"Sequences","id":"sequences"},{"level":3,"text":"Hashtables and sets","id":"hashtables-and-sets"},{"level":3,"text":"Tuples and accessors","id":"tuples-and-accessors"},{"level":3,"text":"Structs and C layouts","id":"structs-and-c-layouts"},{"level":3,"text":"Generic words and classes","id":"generic-words-and-classes"},{"level":3,"text":"Symbols and dynamic variables","id":"symbols-and-dynamic-variables"},{"level":3,"text":"Errors and cleanup","id":"errors-and-cleanup"},{"level":3,"text":"Resource disposal","id":"resource-disposal"},{"level":3,"text":"Vocabularies","id":"vocabularies"},{"level":3,"text":"Editing and reloading","id":"editing-and-reloading"},{"level":3,"text":"Code as data, macros, and parsing words","id":"code-as-data-macros-and-parsing-words"},{"level":3,"text":"Memoization","id":"memoization"},{"level":3,"text":"Files and formatted output","id":"files-and-formatted-output"},{"level":3,"text":"JSON, regular expressions, and HTTP","id":"json-regular-expressions-and-http"},{"level":3,"text":"Dates and calendars","id":"dates-and-calendars"},{"level":3,"text":"Random","id":"random"},{"level":3,"text":"Threads","id":"threads"},{"level":3,"text":"Calling C","id":"calling-c"},{"level":3,"text":"Testing and exploring","id":"testing-and-exploring"}]}}