{"text": "# The Racket Guide\n8.18.0.13"} {"text": "# The Racket Guide\nThis guide is intended for programmers who are new to Racket or new to some part of Racket. It assumes programming experience, so if you are new to programming, consider instead reading [How to Design Programs](https://htdp.org). If you want an especially quick introduction to Racket, start with [Quick: An Introduction to Racket with Pictures](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?tag=%28part._%28.%27%28lib._scribblings%2Fquick%2Fquick..scrbl%29.%27._.%27top.%27%29%29&version=8.18.0.13).\n[Chapter 2](to-scheme.html) provides a brief introduction to Racket. From [Chapter 3](datatypes.html) on, this guide dives into details—covering much of the Racket toolbox, but leaving precise details to [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) and other reference manuals.\n> > > The source of this manual is available on [GitHub](https://github.com/racket/racket/tree/master/pkgs/racket-doc/scribblings/guide)."} {"text": "# The Racket Guide\n| |\n|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n|     [1 Welcome to Racket](intro.html) |\n|       [1.1 Interacting with Racket](intro.html#%28part._.Interacting_with_.Racket%29) |\n|       [1.2 Definitions and Interactions](intro.html#%28part._.Definitions_and_.Interactions%29) |\n|       [1.3 Creating Executables](intro.html#%28part._.Creating_.Executables%29) |\n|       [1.4 A Note to Readers with Lisp/Scheme Experience](intro.html#%28part._use-module%29) |\n| |\n|     [2 Racket Essentials](to-scheme.html) |\n|       [2.1 Simple Values](Simple_Values.html) |\n|       [2.2 Simple Definitions and Expressions](syntax-overview.html) |\n|         [2.2.1 Definitions](syntax-overview.html#%28part._.Definitions%29) |\n|         [2.2.2 An Aside on Indenting Code](syntax-overview.html#%28part._indentation%29) |\n|         [2.2.3 Identifiers](syntax-overview.html#%28part._.Identifiers%29) |\n|         [2.2.4 Function Calls (Procedure Applications)](syntax-overview.html#%28part._.Function_.Calls__.Procedure_.Applications_%29) |\n|         [2.2.5 Conditionals with if, and, or, and cond](syntax-overview.html#%28part._.Conditionals_with_if__and__or__and_cond%29) |\n|         [2.2.6 Function Calls, Again](syntax-overview.html#%28part._.Function_.Calls__.Again%29) |\n|         [2.2.7 Anonymous Functions with lambda](syntax-overview.html#%28part._.Anonymous_.Functions_with_lambda%29) |\n|         [2.2.8 Local Binding with define, let, and let*](syntax-overview.html#%28part._local-binding-intro%29) |\n|       [2.3 Lists, Iteration, and Recursion](Lists__Iteration__and_Recursion.html) |\n|         [2.3.1 Predefined List Loops](Lists__Iteration__and_Recursion.html#%28part._.Predefined_.List_.Loops%29) |\n|         [2.3.2 List Iteration from Scratch](Lists__Iteration__and_Recursion.html#%28part._.List_.Iteration_from_.Scratch%29) |\n|         [2.3.3 Tail Recursion](Lists__Iteration__and_Recursion.html#%28part._tail-recursion%29) |\n|         [2.3.4 Recursion versus Iteration](Lists__Iteration__and_Recursion.html#%28part._.Recursion_versus_.Iteration%29) |\n|       [2.4 Pairs, Lists, and Racket Syntax](Pairs__Lists__and_Racket_Syntax.html) |\n|         [2.4.1 Quoting Pairs and Symbols with quote](Pairs__Lists__and_Racket_Syntax.html#%28part._quoting-lists%29) |\n|         [2.4.2 Abbreviating quote with '](Pairs__Lists__and_Racket_Syntax.html#%28part._.Abbreviating_quote_with__%29) |\n|         [2.4.3 Lists and Racket Syntax](Pairs__Lists__and_Racket_Syntax.html#%28part._lists-and-syntax%29) |\n| |\n|     [3 Built-In Datatypes](datatypes.html) |\n|       [3.1 Booleans](booleans.html) |\n|       [3.2 Numbers](numbers.html) |\n|       [3.3 Characters](characters.html) |\n|       [3.4 Strings (Unicode)](strings.html) |\n|       [3.5 Bytes and Byte Strings](bytestrings.html) |\n|       [3.6 Symbols](symbols.html) |\n|       [3.7 Keywords](keywords.html) |\n|       [3.8 Pairs and Lists](pairs.html) |\n|       [3.9 Vectors](vectors.html) |\n|       [3.10 Hash Tables](hash-tables.html) |\n|       [3.11 Boxes](boxes.html) |\n|       [3.12 Void and Undefined](void_undefined.html) |\n| |\n|     [4 Expressions and Definitions](scheme-forms.html) |\n|       [4.1 Notation](syntax-notation.html) |\n|       [4.2 Identifiers and Binding](binding.html) |\n|       [4.3 Function Calls (Procedure Applications)](application.html) |\n|         [4.3.1 Evaluation Order and Arity](application.html#%28part._.Evaluation_.Order_and_.Arity%29) |\n|         [4.3.2 Keyword Arguments](application.html#%28part._keyword-args%29) |\n|         [4.3.3 The apply Function](application.html#%28part._apply%29) |\n|       [4.4 Functions (Procedures): lambda](lambda.html) |\n|         [4.4.1 Declaring a Rest Argument](lambda.html#%28part._rest-args%29) |\n|         [4.4.2 Declaring Optional Arguments](lambda.html#%28part._.Declaring_.Optional_.Arguments%29) |\n|         [4.4.3 Declaring Keyword Arguments](lambda.html#%28part._lambda-keywords%29) |\n|         [4.4.4 Arity-Sensitive Functions: case-lambda](lambda.html#%28part._case-lambda%29) |\n|       [4.5 Definitions: define](define.html) |\n|         [4.5.1 Function Shorthand](define.html#%28part._.Function_.Shorthand%29) |\n|         [4.5.2 Curried Function Shorthand](define.html#%28part._.Curried_.Function_.Shorthand%29) |\n|         [4.5.3 Multiple Values and define-values](define.html#%28part._multiple-values%29) |\n|         [4.5.4 Internal Definitions](define.html#%28part._intdefs%29) |\n|       [4.6 Local Binding](let.html) |\n|         [4.6.1 Parallel Binding: let](let.html#%28part._.Parallel_.Binding__let%29) |\n|         [4.6.2 Sequential Binding: let*](let.html#%28part._.Sequential_.Binding__let_%29) |\n|         [4.6.3 Recursive Binding: letrec](let.html#%28part._.Recursive_.Binding__letrec%29) |\n|         [4.6.4 Named let](let.html#%28part._.Named_let%29) |\n|         [4.6.5 Multiple Values: let-values, let*-values, letrec-values](let.html#%28part._.Multiple_.Values__let-values__let_-values__letrec-values%29) |\n|       [4.7 Conditionals](conditionals.html) |\n|         [4.7.1 Simple Branching: if](conditionals.html#%28part._.Simple_.Branching__if%29) |\n|         [4.7.2 Combining Tests: and and or](conditionals.html#%28part._and%2Bor%29) |\n|         [4.7.3 Chaining Tests: cond](conditionals.html#%28part._cond%29) |\n|       [4.8 Sequencing](begin.html) |\n|         [4.8.1 Effects Before: begin](begin.html#%28part._.Effects_.Before__begin%29) |\n|         [4.8.2 Effects After: begin0](begin.html#%28part._.Effects_.After__begin0%29) |\n|         [4.8.3 Effects If...: when and unless](begin.html#%28part._when%2Bunless%29) |\n|       [4.9 Assignment: set!](set_.html) |\n|         [4.9.1 Guidelines for Using Assignment](set_.html#%28part._using-set%21%29) |\n|         [4.9.2 Multiple Values: set!-values](set_.html#%28part._.Multiple_.Values__set_-values%29) |\n|       [4.10 Quoting: quote and ’](quote.html) |\n|       [4.11 Quasiquoting: quasiquote and ‘](qq.html) |\n|       [4.12 Simple Dispatch: case](case.html) |\n|       [4.13 Dynamic Binding: parameterize](parameterize.html) |\n| |\n|     [5 Programmer-Defined Datatypes](define-struct.html) |\n|       [5.1 Simple Structure Types: struct](define-struct.html#%28part._.Simple_.Structure_.Types__struct%29) |\n|       [5.2 Copying and Update](define-struct.html#%28part._struct-copy%29) |\n|       [5.3 Structure Subtypes](define-struct.html#%28part._struct-subtypes%29) |\n|       [5.4 Opaque versus Transparent Structure Types](define-struct.html#%28part._trans-struct%29) |\n|       [5.5 Structure Comparisons](define-struct.html#%28part._struct-equal%29) |\n|       [5.6 Structure Type Generativity](define-struct.html#%28part._.Structure_.Type_.Generativity%29) |\n|       [5.7 Prefab Structure Types](define-struct.html#%28part._prefab-struct%29) |\n|       [5.8 More Structure Type Options](define-struct.html#%28part._struct-options%29) |\n| |\n|     [6 Modules](modules.html) |\n|       [6.1 Module Basics](module-basics.html) |\n|         [6.1.1 Organizing Modules](module-basics.html#%28part._module-org%29) |\n|         [6.1.2 Library Collections](module-basics.html#%28part._.Library_.Collections%29) |\n|         [6.1.3 Packages and Collections](module-basics.html#%28part._packages-and-collections%29) |\n|         [6.1.4 Adding Collections](module-basics.html#%28part._link-collection%29) |\n|         [6.1.5 Module References Within a Collection](module-basics.html#%28part._intracollection%29) |\n|       [6.2 Module Syntax](Module_Syntax.html) |\n|         [6.2.1 The module Form](Module_Syntax.html#%28part._module-syntax%29) |\n|         [6.2.2 The #lang Shorthand](Module_Syntax.html#%28part._hash-lang%29) |\n|         [6.2.3 Submodules](Module_Syntax.html#%28part._submodules%29) |\n|         [6.2.4 Main and Test Submodules](Module_Syntax.html#%28part._main-and-test%29) |\n|       [6.3 Module Paths](module-paths.html) |\n|       [6.4 Imports: require](module-require.html) |\n|       [6.5 Exports: provide](module-provide.html) |\n|       [6.6 Assignment and Redefinition](module-set.html) |\n|       [6.7 Modules and Macros](module-macro.html) |\n|       [6.8 Protected Exports](protect-out.html) |\n| |\n|     [7 Contracts](contracts.html) |\n|       [7.1 Contracts and Boundaries](contract-boundaries.html) |\n|         [7.1.1 Contract Violations](contract-boundaries.html#%28part._contracts-amount0%29) |\n|         [7.1.2 Experimenting with Contracts and Modules](contract-boundaries.html#%28part._.Experimenting_with_.Contracts_and_.Modules%29) |\n|         [7.1.3 Experimenting with Nested Contract Boundaries](contract-boundaries.html#%28part._contracts-intro-nested%29) |\n|       [7.2 Simple Contracts on Functions](contract-func.html) |\n|         [7.2.1 Styles of ->](contract-func.html#%28part._.Styles_of_-_%29) |\n|         [7.2.2 Using define/contract and ->](contract-func.html#%28part._simple-nested%29) |\n|         [7.2.3 any and any/c](contract-func.html#%28part._any_and_any_c%29) |\n|         [7.2.4 Rolling Your Own Contracts](contract-func.html#%28part._contracts-own%29) |\n|         [7.2.5 Contracts on Higher-order Functions](contract-func.html#%28part._.Contracts_on_.Higher-order_.Functions%29) |\n|         [7.2.6 Contract Messages with “???”](contract-func.html#%28part._contracts-flat-named-contracts%29) |\n|         [7.2.7 Dissecting a contract error message](contract-func.html#%28part._contracts-dissecting-contract-errors%29) |\n|       [7.3 Contracts on Functions in General](contracts-general-functions.html) |\n|         [7.3.1 Optional Arguments](contracts-general-functions.html#%28part._contracts-optional%29) |\n|         [7.3.2 Rest Arguments](contracts-general-functions.html#%28part._contracts-rest-args%29) |\n|         [7.3.3 Keyword Arguments](contracts-general-functions.html#%28part._contracts-keywords%29) |\n|         [7.3.4 Optional Keyword Arguments](contracts-general-functions.html#%28part._contracts-optional-keywords%29) |\n|         [7.3.5 Contracts for case-lambda](contracts-general-functions.html#%28part._contracts-case-lambda%29) |\n|         [7.3.6 Argument and Result Dependencies](contracts-general-functions.html#%28part._contracts-arrow-d%29) |\n|         [7.3.7 Checking State Changes](contracts-general-functions.html#%28part._contracts-arrow-d-eval-order%29) |\n|         [7.3.8 Multiple Result Values](contracts-general-functions.html#%28part._contracts-multiple%29) |\n|         [7.3.9 Fixed but Statically Unknown Arities](contracts-general-functions.html#%28part._contracts-no-domain%29) |\n|       [7.4 Contracts: A Thorough Example](contracts-first.html) |\n|       [7.5 Contracts on Structures](contracts-struct.html) |\n|         [7.5.1 Guarantees for a Specific Value](contracts-struct.html#%28part._contracts-single-struct%29) |\n|         [7.5.2 Guarantees for All Values](contracts-struct.html#%28part._contracts-define-struct%29) |\n|         [7.5.3 Checking Properties of Data Structures](contracts-struct.html#%28part._contracts-lazy-contracts%29) |\n|       [7.6 Abstract Contracts using #:exists and #:∃](contracts-exists.html) |\n|       [7.7 Additional Examples](contracts-examples.html) |\n|         [7.7.1 A Customer-Manager Component](contracts-examples.html#%28part._.A_.Customer-.Manager_.Component%29) |\n|         [7.7.2 A Parameteric (Simple) Stack](contracts-examples.html#%28part._.A_.Parameteric__.Simple__.Stack%29) |\n|         [7.7.3 A Dictionary](contracts-examples.html#%28part._.A_.Dictionary%29) |\n|         [7.7.4 A Queue](contracts-examples.html#%28part._.A_.Queue%29) |\n|       [7.8 Building New Contracts](Building_New_Contracts.html) |\n|         [7.8.1 Contract Struct Properties](Building_New_Contracts.html#%28part._.Contract_.Struct_.Properties%29) |\n|         [7.8.2 With all the Bells and Whistles](Building_New_Contracts.html#%28part._.With_all_the_.Bells_and_.Whistles%29) |\n|       [7.9 Gotchas](contracts-gotchas.html) |\n|         [7.9.1 Contracts and eq?](contracts-gotchas.html#%28part._.Contracts_and_eq_%29) |\n|         [7.9.2 Contract boundaries and define/contract](contracts-gotchas.html#%28part._contracts-gotcha-nested%29) |\n|         [7.9.3 Exists Contracts and Predicates](contracts-gotchas.html#%28part._contracts-exists-gotcha%29) |\n|         [7.9.4 Defining Recursive Contracts](contracts-gotchas.html#%28part._.Defining_.Recursive_.Contracts%29) |\n|         [7.9.5 Mixing set! and contract-out](contracts-gotchas.html#%28part._.Mixing_set__and_contract-out%29) |\n| |\n|     [8 Input and Output](i_o.html) |\n|       [8.1 Varieties of Ports](ports.html) |\n|       [8.2 Default Ports](default-ports.html) |\n|       [8.3 Reading and Writing Racket Data](read-write.html) |\n|       [8.4 Datatypes and Serialization](serialization.html) |\n|       [8.5 Bytes, Characters, and Encodings](encodings.html) |\n|       [8.6 I/O Patterns](io-patterns.html) |\n| |\n|     [9 Regular Expressions](regexp.html) |\n|       [9.1 Writing Regexp Patterns](regexp-intro.html) |\n|       [9.2 Matching Regexp Patterns](regexp-match.html) |\n|       [9.3 Basic Assertions](regexp-assert.html) |\n|       [9.4 Characters and Character Classes](regexp-chars.html) |\n|         [9.4.1 Some Frequently Used Character Classes](regexp-chars.html#%28part._.Some_.Frequently_.Used_.Character_.Classes%29) |\n|         [9.4.2 POSIX character classes](regexp-chars.html#%28part._.P.O.S.I.X_character_classes%29) |\n|       [9.5 Quantifiers](regexp-quant.html) |\n|       [9.6 Clusters](regexp-clusters.html) |\n|         [9.6.1 Backreferences](regexp-clusters.html#%28part._.Backreferences%29) |\n|         [9.6.2 Non-capturing Clusters](regexp-clusters.html#%28part._.Non-capturing_.Clusters%29) |\n|         [9.6.3 Cloisters](regexp-clusters.html#%28part._regexp-cloister%29) |\n|       [9.7 Alternation](regexp-alternation.html) |\n|       [9.8 Backtracking](Backtracking.html) |\n|       [9.9 Looking Ahead and Behind](Looking_Ahead_and_Behind.html) |\n|         [9.9.1 Lookahead](Looking_Ahead_and_Behind.html#%28part._.Lookahead%29) |\n|         [9.9.2 Lookbehind](Looking_Ahead_and_Behind.html#%28part._.Lookbehind%29) |\n|       [9.10 An Extended Example](An_Extended_Example.html) |\n| |\n|     [10 Exceptions and Control](control.html) |\n|       [10.1 Exceptions](exns.html) |\n|       [10.2 Prompts and Aborts](prompt.html) |\n|       [10.3 Continuations](conts.html) |\n| |\n|     [11 Iterations and Comprehensions](for.html) |\n|       [11.1 Sequence Constructors](for.html#%28part._sequences%29) |\n|       [11.2 for and for*](for.html#%28part._for_and_for_%29) |\n|       [11.3 for/list and for*/list](for.html#%28part._for_list_and_for__list%29) |\n|       [11.4 for/vector and for*/vector](for.html#%28part._for_vector_and_for__vector%29) |\n|       [11.5 for/and and for/or](for.html#%28part._for_and_and_for_or%29) |\n|       [11.6 for/first and for/last](for.html#%28part._for_first_and_for_last%29) |\n|       [11.7 for/fold and for*/fold](for.html#%28part._for%2Ffold%29) |\n|       [11.8 Multiple-Valued Sequences](for.html#%28part._.Multiple-.Valued_.Sequences%29) |\n|       [11.9 Breaking an Iteration](for.html#%28part._.Breaking_an_.Iteration%29) |\n|       [11.10 Iteration Performance](for.html#%28part._for-performance%29) |\n| |\n|     [12 Pattern Matching](match.html) |\n| |\n|     [13 Classes and Objects](classes.html) |\n|       [13.1 Methods](classes.html#%28part._methods%29) |\n|       [13.2 Initialization Arguments](classes.html#%28part._initargs%29) |\n|       [13.3 Internal and External Names](classes.html#%28part._intnames%29) |\n|       [13.4 Interfaces](classes.html#%28part._.Interfaces%29) |\n|       [13.5 Final, Augment, and Inner](classes.html#%28part._inner%29) |\n|       [13.6 Controlling the Scope of External Names](classes.html#%28part._extnames%29) |\n|       [13.7 Mixins](classes.html#%28part._.Mixins%29) |\n|         [13.7.1 Mixins and Interfaces](classes.html#%28part._.Mixins_and_.Interfaces%29) |\n|         [13.7.2 The mixin Form](classes.html#%28part._.The_mixin_.Form%29) |\n|         [13.7.3 Parameterized Mixins](classes.html#%28part._parammixins%29) |\n|       [13.8 Traits](classes.html#%28part._.Traits%29) |\n|         [13.8.1 Traits as Sets of Mixins](classes.html#%28part._.Traits_as_.Sets_of_.Mixins%29) |\n|         [13.8.2 Inherit and Super in Traits](classes.html#%28part._.Inherit_and_.Super_in_.Traits%29) |\n|         [13.8.3 The trait Form](classes.html#%28part._.The_trait_.Form%29) |\n|       [13.9 Class Contracts](classes.html#%28part._.Class_.Contracts%29) |\n|         [13.9.1 External Class Contracts](classes.html#%28part._.External_.Class_.Contracts%29) |\n|         [13.9.2 Internal Class Contracts](classes.html#%28part._.Internal_.Class_.Contracts%29) |\n| |\n|     [14 Units (Components)](units.html) |\n|       [14.1 Signatures and Units](Signatures_and_Units.html) |\n|       [14.2 Invoking Units](Invoking_Units.html) |\n|       [14.3 Linking Units](Linking_Units.html) |\n|       [14.4 First-Class Units](firstclassunits.html) |\n|       [14.5 Whole-module Signatures and Units](Whole-module_Signatures_and_Units.html) |\n|       [14.6 Contracts for Units](Contracts_for_Units.html) |\n|         [14.6.1 Adding Contracts to Signatures](Contracts_for_Units.html#%28part._.Adding_.Contracts_to_.Signatures%29) |\n|         [14.6.2 Adding Contracts to Units](Contracts_for_Units.html#%28part._.Adding_.Contracts_to_.Units%29) |\n|       [14.7 unit versus module](unit_versus_module.html) |\n| |\n|     [15 Reflection and Dynamic Evaluation](reflection.html) |\n|       [15.1 eval](eval.html) |\n|         [15.1.1 Local Scopes](eval.html#%28part._.Local_.Scopes%29) |\n|         [15.1.2 Namespaces](eval.html#%28part._namespaces%29) |\n|         [15.1.3 Namespaces and Modules](eval.html#%28part._.Namespaces_and_.Modules%29) |\n|       [15.2 Manipulating Namespaces](mk-namespace.html) |\n|         [15.2.1 Creating and Installing Namespaces](mk-namespace.html#%28part._.Creating_and_.Installing_.Namespaces%29) |\n|         [15.2.2 Sharing Data and Code Across Namespaces](mk-namespace.html#%28part._.Sharing_.Data_and_.Code_.Across_.Namespaces%29) |\n|       [15.3 Scripting Evaluation and Using load](load.html) |\n|       [15.4 Code Inspectors for Trusted and Untrusted Code](code-inspectors_protect.html) |\n| |\n|     [16 Macros](macros.html) |\n|       [16.1 Pattern-Based Macros](pattern-macros.html) |\n|         [16.1.1 define-syntax-rule](pattern-macros.html#%28part._define-syntax-rule%29) |\n|         [16.1.2 Lexical Scope](pattern-macros.html#%28part._.Lexical_.Scope%29) |\n|         [16.1.3 define-syntax and syntax-rules](pattern-macros.html#%28part._define-syntax_and_syntax-rules%29) |\n|         [16.1.4 Matching Sequences](pattern-macros.html#%28part._.Matching_.Sequences%29) |\n|         [16.1.5 Identifier Macros](pattern-macros.html#%28part._.Identifier_.Macros%29) |\n|         [16.1.6 set! Transformers](pattern-macros.html#%28part._set__.Transformers%29) |\n|         [16.1.7 Macro-Generating Macros](pattern-macros.html#%28part._.Macro-.Generating_.Macros%29) |\n|         [16.1.8 Extended Example: Call-by-Reference Functions](pattern-macros.html#%28part._pattern-macro-example%29) |\n|       [16.2 General Macro Transformers](proc-macros.html) |\n|         [16.2.1 Syntax Objects](stx-obj.html) |\n|         [16.2.2 Macro Transformer Procedures](macro-transformers.html) |\n|         [16.2.3 Mixing Patterns and Expressions: syntax-case](syntax-case.html) |\n|         [16.2.4 with-syntax and generate-temporaries](with-syntax.html) |\n|         [16.2.5 Compile and Run-Time Phases](stx-phases.html) |\n|         [16.2.6 General Phase Levels](phases.html) |\n|           [16.2.6.1 Phases and Bindings](phases.html#%28part._.Phases_and_.Bindings%29) |\n|           [16.2.6.2 Phases and Modules](phases.html#%28part._.Phases_and_.Modules%29) |\n|         [16.2.7 Tainted Syntax](stx-certs.html) |\n|       [16.3 Module Instantiations and Visits](macro-module.html) |\n|         [16.3.1 Declaration versus Instantiation](macro-module.html#%28part._.Declaration_versus_.Instantiation%29) |\n|         [16.3.2 Compile-Time Instantiation](macro-module.html#%28part._compile-time-instantiation%29) |\n|         [16.3.3 Visiting Modules](macro-module.html#%28part._.Visiting_.Modules%29) |\n|         [16.3.4 Lazy Visits via Available Modules](macro-module.html#%28part._stx-available-module%29) |\n| |\n|     [17 Creating Languages](languages.html) |\n|       [17.1 Module Languages](module-languages.html) |\n|         [17.1.1 Implicit Form Bindings](module-languages.html#%28part._implicit-forms%29) |\n|         [17.1.2 Using #lang s-exp](module-languages.html#%28part._s-exp%29) |\n|       [17.2 Reader Extensions](hash-reader.html) |\n|         [17.2.1 Source Locations](hash-reader.html#%28part._.Source_.Locations%29) |\n|         [17.2.2 Readtables](hash-reader.html#%28part._readtable%29) |\n|       [17.3 Defining new #lang Languages](hash-languages.html) |\n|         [17.3.1 Designating a #lang Language](hash-lang_syntax.html) |\n|         [17.3.2 Using #lang reader](hash-lang_reader.html) |\n|         [17.3.3 Using #lang s-exp syntax/module-reader](syntax_module-reader.html) |\n|         [17.3.4 Installing a Language](language-collection.html) |\n|         [17.3.5 Source-Handling Configuration](language-get-info.html) |\n|         [17.3.6 Module-Handling Configuration](module-runtime-config.html) |\n| |\n|     [18 Concurrency and Synchronization](concurrency.html) |\n|       [18.1 Threads](concurrency.html#%28part._.Threads%29) |\n|       [18.2 Thread Mailboxes](concurrency.html#%28part._.Thread_.Mailboxes%29) |\n|       [18.3 Semaphores](concurrency.html#%28part._.Semaphores%29) |\n|       [18.4 Channels](concurrency.html#%28part._.Channels%29) |\n|       [18.5 Buffered Asynchronous Channels](concurrency.html#%28part._.Buffered_.Asynchronous_.Channels%29) |\n|       [18.6 Synchronizable Events and sync](concurrency.html#%28part._.Synchronizable_.Events_and_sync%29) |\n|       [18.7 Building Your Own Synchronization Patterns](concurrency.html#%28part._.Building_.Your_.Own_.Synchronization_.Patterns%29) |\n| |\n|     [19 Performance](performance.html) |\n|       [19.1 Performance in DrRacket](performance.html#%28part._.Dr.Racket-perf%29) |\n|       [19.2 Racket Virtual Machine Implementations](performance.html#%28part._virtual-machines%29) |\n|       [19.3 Bytecode, Machine Code, and Just-in-Time (JIT) Compilers](performance.html#%28part._.J.I.T%29) |\n|       [19.4 Modules and Performance](performance.html#%28part._modules-performance%29) |\n|       [19.5 Function-Call Optimizations](performance.html#%28part._func-call-performance%29) |\n|       [19.6 Mutation and Performance](performance.html#%28part._.Mutation_and_.Performance%29) |\n|       [19.7 letrec Performance](performance.html#%28part._letrec-performance%29) |\n|       [19.8 Fixnum and Flonum Optimizations](performance.html#%28part._fixnums%2Bflonums%29) |\n|       [19.9 Unchecked, Unsafe Operations](performance.html#%28part._unchecked-unsafe%29) |\n|       [19.10 Foreign Pointers](performance.html#%28part._ffi-pointer-access%29) |\n|       [19.11 Regular Expression Performance](performance.html#%28part._regexp-perf%29) |\n|       [19.12 Memory Management](performance.html#%28part._gc-perf%29) |\n|       [19.13 Reachability and Garbage Collection](performance.html#%28part._.Reachability._and._.Garbage._.Collection%29) |\n|       [19.14 Weak Boxes and Testing](performance.html#%28part._.Weak_.Boxes_and_.Testing%29) |\n|       [19.15 Reducing Garbage Collection Pauses](performance.html#%28part._.Reducing_.Garbage_.Collection_.Pauses%29) |\n| |\n|     [20 Parallelism](parallelism.html) |\n|       [20.1 Parallel Threads](parallelism.html#%28part._parallel-threads%29) |\n|       [20.2 Parallelism with Futures](parallelism.html#%28part._effective-futures%29) |\n|       [20.3 Parallelism with Places](parallelism.html#%28part._effective-places%29) |\n|       [20.4 Distributed Places](parallelism.html#%28part._distributed-places%29) |\n| |\n|     [21 Running and Creating Executables](running.html) |\n|       [21.1 Running racket and gracket](racket.html) |\n|         [21.1.1 Interactive Mode](racket.html#%28part._start-interactive-mode%29) |\n|         [21.1.2 Module Mode](racket.html#%28part._start-module-mode%29) |\n|         [21.1.3 Load Mode](racket.html#%28part._start-load-mode%29) |\n|       [21.2 Scripts](scripts.html) |\n|         [21.2.1 Unix Scripts](scripts.html#%28part._.Unix_.Scripts%29) |\n|         [21.2.2 Windows Batch Files](scripts.html#%28part._.Windows_.Batch_.Files%29) |\n|       [21.3 Creating Stand-Alone Executables](exe.html) |\n| |\n|     [22 More Libraries](More_Libraries.html) |\n|       [22.1 Graphics and GUIs](More_Libraries.html#%28part._graphics%29) |\n|       [22.2 The Web Server](More_Libraries.html#%28part._.The_.Web_.Server%29) |\n|       [22.3 Using Foreign Libraries](More_Libraries.html#%28part._.Using_.Foreign_.Libraries%29) |\n|       [22.4 And More](More_Libraries.html#%28part._.And_.More%29) |\n| |\n|     [23 Dialects of Racket and Scheme](dialects.html) |\n|       [23.1 More Rackets](more-hash-lang.html) |\n|       [23.2 Standards](standards.html) |\n|         [23.2.1 R5RS](standards.html#%28part._r5rs%29) |\n|         [23.2.2 R6RS](standards.html#%28part._.R6.R.S%29) |\n|       [23.3 Teaching](teaching-langs.html) |\n| |\n|     [24 Command-Line Tools and Your Editor of Choice](other-editors.html) |\n|       [24.1 Command-Line Tools](cmdline-tools.html) |\n|         [24.1.1 Compilation and Configuration: raco](cmdline-tools.html#%28part._compile%29) |\n|         [24.1.2 Interactive evaluation](cmdline-tools.html#%28part._.Interactive_evaluation%29) |\n|         [24.1.3 Shell completion](cmdline-tools.html#%28part._.Shell_completion%29) |\n|       [24.2 Emacs](Emacs.html) |\n|         [24.2.1 Major Modes](Emacs.html#%28part._.Major_.Modes%29) |\n|         [24.2.2 Minor Modes](Emacs.html#%28part._.Minor_.Modes%29) |\n|         [24.2.3 Packages specific to Evil Mode](Emacs.html#%28part._.Packages_specific_to_.Evil_.Mode%29) |\n|       [24.3 Vim](Vim.html) |\n|         [24.3.1 Enhanced Racket Support](Vim.html#%28part._vim-racket%29) |\n|         [24.3.2 Indentation](Vim.html#%28part._.Indentation%29) |\n|         [24.3.3 Highlighting](Vim.html#%28part._.Highlighting%29) |\n|         [24.3.4 Structured Editing](Vim.html#%28part._.Structured_.Editing%29) |\n|         [24.3.5 REPLs](Vim.html#%28part._.R.E.P.Ls%29) |\n|         [24.3.6 Scribble](Vim.html#%28part._.Scribble%29) |\n|         [24.3.7 Miscellaneous](Vim.html#%28part._.Miscellaneous%29) |\n|         [24.3.8 Older Versions of Vim](Vim.html#%28part._vim-versions%29) |\n|       [24.4 Sublime Text](Sublime_Text.html) |\n|       [24.5 Visual Studio Code](Visual_Studio_Code.html) |\n| |\n|     [Bibliography](doc-bibliography.html) |\n| |\n|     [Index](doc-index.html) |"} {"text": "# The Racket Guide\n------------------------------------------------------------------------"} {"text": "# 1 Welcome to Racket"} {"text": "## 1 Welcome to Racket\nDepending on how you look at it, Racket is\n- a programming language—a dialect of Lisp and a descendant of Scheme;\n > > > See [Dialects of Racket and Scheme](dialects.html) for more information on other dialects of Lisp and how they relate to Racket.\n- a family of programming languages—variants of Racket, and more; or\n- a set of tools—for using a family of programming languages.\nWhere there is no room for confusion, we use simply Racket.\nRacket’s main tools are\n- racket, the core compiler, interpreter, and run-time system;\n- DrRacket, the programming environment; and\n- raco, a command-line tool for executing Racket commands that install packages, build libraries, and more.\nMost likely, you’ll want to explore the Racket language using DrRacket, especially at the beginning. If you prefer, you can also work with the command-line racket interpreter (see [Running racket and gracket](racket.html)) and your favorite text editor (see [Command-Line Tools and Your Editor of Choice](other-editors.html)). The rest of this guide presents the language mostly independent of your choice of editor.\nIf you’re using DrRacket, you’ll need to choose the proper language, because DrRacket accommodates many different variants of Racket, as well as other languages. Assuming that you’ve never used DrRacket before, start it up, type the line\n> [#lang](Module_Syntax.html#%28part._hash-lang%29) [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13)"} {"text": "# 1 Welcome to Racket\nin DrRacket’s top text area, and then click the Run button that’s above the text area. DrRacket then understands that you mean to work in the normal variant of Racket (as opposed to the smaller [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) or many other possibilities).\n> > > [More Rackets](more-hash-lang.html) describes some of the other possibilities.\nIf you’ve used DrRacket before with something other than a program that starts [#lang](Module_Syntax.html#%28part._hash-lang%29), DrRacket will remember the last language that you used, instead of inferring the language from the [#lang](Module_Syntax.html#%28part._hash-lang%29) line. In that case, use the Language\\|Choose Language... menu item. In the dialog that appears, select the first item, which tells DrRacket to use the language that is declared in a source program via [#lang](Module_Syntax.html#%28part._hash-lang%29). Put the [#lang](Module_Syntax.html#%28part._hash-lang%29) line above in the top text area, still."} {"text": "### 1.1 Interacting with Racket\nDrRacket’s bottom text area and the racket command-line program (when started with no options) both act as a kind of calculator. You type a Racket expression, hit the Return key, and the answer is printed. In the terminology of Racket, this kind of calculator is called a read-eval-print loop or REPL.\nA number by itself is an expression, and the answer is just the number:\n> ```racket\n> > 5\n> 5\n> ```\nA string is also an expression that evaluates to itself. A string is written with double quotes at the start and end of the string:\n> ```racket\n> > \"Hello, world!\"\n> \"Hello, world!\"\n> ```\nRacket uses parentheses to wrap larger expressions—almost any kind of expression, other than simple constants. For example, a function call is written: open parenthesis, function name, argument expression, and closing parenthesis. The following expression calls the built-in function [substring](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._substring%2529%2529&version=8.18.0.13) with the arguments \"the boy out of the country\", 4, and 7:\n> ```racket\n> > ( substring \"the boy out of the country\" 4 7 )\n> \"boy\"\n> ```"} {"text": "### 1.2 Definitions and Interactions\nYou can define your own functions that work like [substring](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._substring%2529%2529&version=8.18.0.13) by using the [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) form, like this:\n>
( define ( extract str )\n> ( substring str 4 7 ) )

 

> ( extract "the boy out of the country" )\n> "boy"\n> > ( extract "the country out of the boy" )\n> "cou"
\nAlthough you can evaluate the [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) form in the [REPL](#%28tech._repl%29), definitions are normally a part of a program that you want to keep and use later. So, in DrRacket, you’d normally put the definition in the top text area—called the definitions area—along with the [#lang](Module_Syntax.html#%28part._hash-lang%29) prefix:"} {"text": "### 1.2 Definitions and Interactions\n> ```racket\n> #lang racket\n> ( define ( extract str )\n> ( substring str 4 7 ) )\n> ```\nIf calling (extract \"the boy\") is part of the main action of your program, that would go in the [definitions area](#%28tech._definitions._area%29), too. But if it was just an example expression that you were using to explore extract, then you’d more likely leave the [definitions area](#%28tech._definitions._area%29) as above, click Run, and then evaluate (extract \"the boy\") in the [REPL](#%28tech._repl%29).\nWhen using command-line racket instead of DrRacket, you’d save the above text in a file using your favorite editor. If you save it as \"extract.rkt\", then after starting racket in the same directory, you’d evaluate the following sequence:\n> > > If you use [xrepl](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=xrepl&rel=index.html&version=8.18.0.13), you can use [,enter extract.rkt](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=xrepl&rel=index.html%23%2528xrepl._enter%2529&version=8.18.0.13).\n> ```racket\n> > ( enter! \"extract.rkt\" )\n> > ( extract \"the gal out of the city\" )\n> \"gal\"\n> ```\nThe [enter!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=interactive.html%23%2528form._%2528%2528lib._racket%252Fenter..rkt%2529._enter%2521%2529%2529&version=8.18.0.13) form both loads the code and switches the evaluation context to the inside of the module, just like DrRacket’s Run button."} {"text": "### 1.3 Creating Executables\nIf your file (or [definitions area](#%28tech._definitions._area%29) in DrRacket) contains\n> ```racket\n> #lang racket\n> ( define ( extract str )\n> ( substring str 4 7 ) )\n> ( extract \"the cat out of the bag\" )\n> ```\nthen it is a complete program that prints “cat” when run. You can run the program within DrRacket or using [enter!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=interactive.html%23%2528form._%2528%2528lib._racket%252Fenter..rkt%2529._enter%2521%2529%2529&version=8.18.0.13) in racket, but if the program is saved in ‹src-filename›, you can also run it from a command line with\n  racket ‹src-filename›\nTo package the program as an executable, you have a few options:\n- In DrRacket, you can select the Racket\\|Create Executable... menu item.\n- From a command-line prompt, run raco exe ‹src-filename›, where ‹src-filename› contains the program. See [raco exe: Creating Stand-Alone Executables](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=exe.html&version=8.18.0.13) for more information.\n- With Unix or Mac OS, you can turn the program file into an executable script by inserting the line\n > > > See [Scripts](scripts.html) for more information on script files.\n | |\n |--------------------------|\n |   #! /usr/bin/env racket |\n at the very beginning of the file. Also, change the file permissions to executable using chmod +x ‹filename› on the command line."} {"text": "### 1.3 Creating Executables\n The script works as long as racket is in the user’s executable search path. Alternately, use a full path to racket after #! (with a space between #! and the path), in which case the user’s executable search path does not matter."} {"text": "### 1.4 A Note to Readers with Lisp/Scheme Experience\nIf you already know something about Scheme or Lisp, you might be tempted to put just\n> ```racket\n> ( define ( extract str )\n> ( substring str 4 7 ) )\n> ```\ninto \"extract.rktl\" and run racket with\n> ```racket\n> > ( load \"extract.rktl\" )\n> > ( extract \"the dog out\" )\n> \"dog\"\n> ```\nThat will work, because racket is willing to imitate a traditional Lisp environment, but we strongly recommend against using [load](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=eval.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._load%2529%2529&version=8.18.0.13) or writing programs outside of a module.\nWriting definitions outside of a module leads to bad error messages, bad performance, and awkward scripting to combine and run programs. The problems are not specific to racket; they’re fundamental limitations of the traditional top-level environment, which Scheme and Lisp implementations have historically fought with ad hoc command-line flags, compiler directives, and build tools. The module system is designed to avoid these problems, so start with [#lang](Module_Syntax.html#%28part._hash-lang%29), and you’ll be happier with Racket in the long run.\n------------------------------------------------------------------------"} {"text": "# 2 Racket Essentials"} {"text": "## 2 Racket Essentials\nThis chapter provides a quick introduction to Racket as background for the rest of the guide. Readers with some Racket experience can safely skip to [Built-In Datatypes](datatypes.html).\n| |\n|----------------------------------------------------------------------------------------------------------------------------------------------------------------|\n|     [2.1 Simple Values](Simple_Values.html) |\n|     [2.2 Simple Definitions and Expressions](syntax-overview.html) |\n|       [2.2.1 Definitions](syntax-overview.html#%28part._.Definitions%29) |\n|       [2.2.2 An Aside on Indenting Code](syntax-overview.html#%28part._indentation%29) |\n|       [2.2.3 Identifiers](syntax-overview.html#%28part._.Identifiers%29) |\n|       [2.2.4 Function Calls (Procedure Applications)](syntax-overview.html#%28part._.Function_.Calls__.Procedure_.Applications_%29) |\n|       [2.2.5 Conditionals with if, and, or, and cond](syntax-overview.html#%28part._.Conditionals_with_if__and__or__and_cond%29) |\n|       [2.2.6 Function Calls, Again](syntax-overview.html#%28part._.Function_.Calls__.Again%29) |\n|       [2.2.7 Anonymous Functions with lambda](syntax-overview.html#%28part._.Anonymous_.Functions_with_lambda%29) |\n|       [2.2.8 Local Binding with define, let, and let*](syntax-overview.html#%28part._local-binding-intro%29) |\n|     [2.3 Lists, Iteration, and Recursion](Lists__Iteration__and_Recursion.html) |\n|       [2.3.1 Predefined List Loops](Lists__Iteration__and_Recursion.html#%28part._.Predefined_.List_.Loops%29) |\n|       [2.3.2 List Iteration from Scratch](Lists__Iteration__and_Recursion.html#%28part._.List_.Iteration_from_.Scratch%29) |\n|       [2.3.3 Tail Recursion](Lists__Iteration__and_Recursion.html#%28part._tail-recursion%29) |\n|       [2.3.4 Recursion versus Iteration](Lists__Iteration__and_Recursion.html#%28part._.Recursion_versus_.Iteration%29) |\n|     [2.4 Pairs, Lists, and Racket Syntax](Pairs__Lists__and_Racket_Syntax.html) |\n|       [2.4.1 Quoting Pairs and Symbols with quote](Pairs__Lists__and_Racket_Syntax.html#%28part._quoting-lists%29) |\n|       [2.4.2 Abbreviating quote with '](Pairs__Lists__and_Racket_Syntax.html#%28part._.Abbreviating_quote_with__%29) |\n|       [2.4.3 Lists and Racket Syntax](Pairs__Lists__and_Racket_Syntax.html#%28part._lists-and-syntax%29) |"} {"text": "# 2 Racket Essentials\n------------------------------------------------------------------------"} {"text": "# 2.1 Simple Values"} {"text": "### 2.1 Simple Values\nRacket values include numbers, booleans, strings, and byte strings. In DrRacket and documentation examples (when you read the documentation in color), value expressions are shown in green.\nNumbers are written in the usual way, including fractions and imaginary numbers:\n> > > \"+\"[Numbers](numbers.html) (later in this guide) explains more about numbers.\n> ```racket\n> 1 3.14\n> 1/2 6.02e+23\n> 1+2i 9999999999999999999999\n> ```\nBooleans are #t for true and #f for false. In conditionals, however, all non-#f values are treated as true.\n> > > \"+\"[Booleans](booleans.html) (later in this guide) explains more about booleans.\nStrings are written between doublequotes. Within a string, backslash is an escaping character; for example, a backslash followed by a doublequote includes a literal doublequote in the string. Except for an unescaped doublequote or backslash, any Unicode character can appear in a string constant.\n> > > \"+\"[Strings (Unicode)](strings.html) (later in this guide) explains more about strings.\n> ```racket\n> \"Hello, world!\"\n> \"Benjamin \\\"Bugsy\\\" Siegel\"\n> \"λx:(μα.α→α).xx\"\n> ```"} {"text": "# 2.1 Simple Values\nWhen a constant is evaluated in the [REPL](intro.html#%28tech._repl%29), it typically prints the same as its input syntax. In some cases, the printed form is a normalized version of the input syntax. In documentation and in DrRacket’s [REPL](intro.html#%28tech._repl%29), results are printed in blue instead of green to highlight the difference between an input expression and a printed result.\nExamples:\n> ```racket\n> > 1.0000\n> 1.0\n> > \"Bugs \\u0022Figaro\\u0022 Bunny\"\n> \"Bugs \\\"Figaro\\\" Bunny\"\n> ```\n------------------------------------------------------------------------"} {"text": "# 2.2 Simple Definitions and Expressions"} {"text": "### 2.2 Simple Definitions and Expressions\nA program module is written as\n> #lang ‹langname› ‹topform›\\*\nwhere a ‹topform› is either a ‹definition› or an ‹expr›. The [REPL](intro.html#%28tech._repl%29) also evaluates ‹topform›s.\nIn syntax specifications, text with a gray background, such as #lang, represents literal text. Whitespace must appear between such literals and nonterminals like ‹id›, except that whitespace is not required before or after (, ), \\[, or \\]. A comment, which starts with ; and runs until the end of the line, is treated the same as whitespace.\n> > > \"+\"[Reading Comments](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=reader.html%23%2528part._parse-comment%2529&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on different forms of comments.\nFollowing the usual conventions, \\* in a grammar means zero or more repetitions of the preceding element, + means one or more repetitions of the preceding element, and {} groups a sequence as an element for repetition."} {"text": "#### 2.2.1 Definitions\nA definition of the form\n> > > \"+\"[Definitions: define](define.html) (later in this guide) explains more about definitions.\n> ( define ‹id› ‹expr› )\nbinds ‹id› to the result of ‹expr›, while\n> ( define ( ‹id› ‹id›\\* ) ‹expr›+ )\nbinds the first ‹id› to a function (also called a procedure) that takes arguments as named by the remaining ‹id›s. In the function case, the ‹expr›s are the body of the function. When the function is called, it returns the result of the last ‹expr›.\nExamples:\n> ```racket\n> ( define pie 3 ) ; defines pie to be 3\n> ( define ( piece str ) ; defines piece as a function ( substring str 0 pie ) ) ; of one argument\n> > pie\n> 3\n> > ( piece \"key lime\" )\n> \"key\"\n> ```\nUnder the hood, a function definition is really the same as a non-function definition, and a function name does not have to be used in a function call. A function is just another kind of value, though the printed form is necessarily less complete than the printed form of a number or string.\nExamples:\n> ```racket\n> > piece\n> #\n> > substring\n> #\n> ```\nA function definition can include multiple expressions for the function’s body. In that case, only the value of the last expression is returned when the function is called. The other expressions are evaluated only for some side-effect, such as printing.\nExamples:\n> ```racket\n> ( define ( bake flavor ) ( printf \"preheating oven...\\n\" ) ( string-append flavor \" pie\" ) )\n> > ( bake \"apple\" )\n> preheating oven...\n> \"apple pie\"\n> ```"} {"text": "# 2.2 Simple Definitions and Expressions\nRacket programmers prefer to avoid side-effects, so a definition usually has just one expression in its body. It’s important, though, to understand that multiple expressions are allowed in a definition body, because it explains why the following nobake function fails to include its argument in its result:\n>
( define ( nobake flavor )\n> string-append flavor "jello" )

 

> ( nobake "green" )\n> "jello"
\nWithin nobake, there are no parentheses around [string-append](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._string-append%2529%2529&version=8.18.0.13) flavor \"jello\", so they are three separate expressions instead of one function-call expression. The expressions [string-append](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._string-append%2529%2529&version=8.18.0.13) and flavor are evaluated, but the results are never used. Instead, the result of the function is just the result of the final expression, \"jello\"."} {"text": "#### 2.2.2 An Aside on Indenting Code\nLine breaks and indentation are not significant for parsing Racket programs, but most Racket programmers use a standard set of conventions to make code more readable. For example, the body of a definition is typically indented under the first line of the definition. Identifiers are written immediately after an open parenthesis with no extra space, and closing parentheses never go on their own line.\nDrRacket automatically indents according to the standard style when you type Enter in a program or [REPL](intro.html#%28tech._repl%29) expression. For example, if you hit Enter after typing (define (greet name), then DrRacket automatically inserts two spaces for the next line. If you change a region of code, you can select it in DrRacket and hit Tab, and DrRacket will re-indent the code (without inserting any line breaks). Editors like Emacs offer a Racket or Scheme mode with similar indentation support.\nRe-indenting not only makes the code easier to read, it gives you extra feedback that your parentheses match in the way that you intended. For example, if you leave out a closing parenthesis after the last argument to a function, automatic indentation starts the next line under the first argument, instead of under the [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) keyword:"} {"text": "# 2.2 Simple Definitions and Expressions\n> ```racket\n> ( define ( halfbake flavor\n> ( string-append flavor \" creme brulee\" ) ) )\n> ```\nIn this case, indentation helps highlight the mistake. In other cases, where the indentation may be normal while an open parenthesis has no matching close parenthesis, both racket and DrRacket use the source’s indentation to suggest where a parenthesis might be missing."} {"text": "#### 2.2.3 Identifiers\nRacket’s syntax for identifiers is especially liberal. Excluding the special characters\n> > > \"+\"[Identifiers and Binding](binding.html) (later in this guide) explains more about identifiers.\n   ( ) \\[ \\] { } \" , ' \\` ; # \\| \\\\\nand except for the sequences of characters that make number constants, almost any sequence of non-whitespace characters forms an ‹id›. For example substring is an identifier. Also, string-append and a+b are identifiers, as opposed to arithmetic expressions. Here are several more examples:\n> ```racket\n> +\n> integer?\n> pass/fail\n> Hfuhruhurr&Uumellmahaye\n> john-jacob-jingleheimer-schmidt\n> a-b-c+1-2-3\n> ```"} {"text": "#### 2.2.4 Function Calls (Procedure Applications)\nWe have already seen many function calls, which are called procedure applications in more traditional terminology. The syntax of a function call is\n> > > \"+\"[Function Calls](application.html) (later in this guide) explains more about function calls.\n> ( ‹id› ‹expr›\\* )\nwhere the number of ‹expr›s determines the number of arguments supplied to the function named by ‹id›.\nThe [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) language pre-defines many function identifiers, such as [substring](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._substring%2529%2529&version=8.18.0.13) and [string-append](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._string-append%2529%2529&version=8.18.0.13). More examples are below.\nIn example Racket code throughout the documentation, uses of pre-defined names are hyperlinked to the reference manual. So, you can click on an identifier to get full details about its use."} {"text": "# 2.2 Simple Definitions and Expressions\n> ```racket\n> > ( string-append \"rope\" \"twine\" \"yarn\" ) ; append strings\n> \"ropetwineyarn\"\n> > ( substring \"corduroys\" 0 4 ) ; extract a substring\n> \"cord\"\n> > ( string-prefix? \"shoelace\" \"shoe\" ) ; recognize string prefix/suffix\n> #t\n> > ( string-suffix? \"shoelace\" \"shoe\" )\n> #f\n> > ( string? \"Ceci n'est pas une string.\" ) ; recognize strings\n> #t\n> > ( string? 1 )\n> #f\n> > ( sqrt 16 ) ; find a square root\n> 4\n> > ( sqrt -1 6 )\n> 0+4i\n> > ( + 1 2 ) ; add numbers\n> 3\n> > ( - 2 1 ) ; subtract numbers\n> 1\n> > ( < 2 1 ) ; compare numbers> #f\n> > ( >= 2 1 )\n> #t\n> > ( number? \"c'est une number\" ) ; recognize numbers\n> #f\n> > ( number? 1 )\n> #t\n> > ( equal? 6 \"half dozen\" ) ; compare anything\n> #f\n> > ( equal? 6 6 )\n> #t\n> > ( equal? \"half dozen\" \"half dozen\" )\n> #t\n> ```"} {"text": "#### 2.2.5 Conditionals with [if](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._if%2529%2529&version=8.18.0.13), [and](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._and%2529%2529&version=8.18.0.13), [or](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._or%2529%2529&version=8.18.0.13), and [cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._cond%2529%2529&version=8.18.0.13)\nThe next simplest kind of expression is an [if](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._if%2529%2529&version=8.18.0.13) conditional:\n> ( if ‹expr› ‹expr› ‹expr› )\n> > > \"+\"[Conditionals](conditionals.html) (later in this guide) explains more about conditionals."} {"text": "# 2.2 Simple Definitions and Expressions\nThe first ‹expr› is always evaluated. If it produces a non-#f value, then the second ‹expr› is evaluated for the result of the whole [if](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._if%2529%2529&version=8.18.0.13) expression, otherwise the third ‹expr› is evaluated for the result.\nExample:\n> ```racket\n> > ( if ( > 2 3 ) \"2 is bigger than 3\" \"2 is smaller than 3\" )\n> \"2 is smaller than 3\"\n> ```\n>
( define ( reply s )\n> ( if ( string-prefix? s "hello " )\n> "hi!"\n> "huh?" ) )

 

> ( reply "hello racket" )\n> "hi!"\n> > ( reply "λx:(μα.α→α).xx" )\n> "huh?"
"} {"text": "# 2.2 Simple Definitions and Expressions\nComplex conditionals can be formed by nesting [if](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._if%2529%2529&version=8.18.0.13) expressions. For example, in the previous reply example, the input must be a string because [string-prefix?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528lib._racket%252Fstring..rkt%2529._string-prefix%7E3f%2529%2529&version=8.18.0.13) would error when given non-strings. You can remove this restriction by adding another [if](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._if%2529%2529&version=8.18.0.13) to check first if the input is a string:\n> ```racket\n> ( define ( reply-non-string s )\n> ( if ( string? s )\n> ( if ( string-prefix? s \"hello \" )\n> \"hi!\"\n> \"huh?\" )\n> \"huh?\" ) )\n> ```\nInstead of duplicating the \"huh?\" case, this function is better written as\n> ```racket\n> ( define ( reply-non-string s )\n> ( if ( if ( string? s )\n> ( string-prefix? s \"hello \" )\n> #f )\n> \"hi!\"\n> \"huh?\" ) )\n> ```"} {"text": "# 2.2 Simple Definitions and Expressions\nbut these kinds of nested [if](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._if%2529%2529&version=8.18.0.13)s are difficult to read. Racket provides more readable shortcuts through the [and](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._and%2529%2529&version=8.18.0.13) and [or](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._or%2529%2529&version=8.18.0.13) forms:\n> > > \"+\"[Combining Tests: and and or](conditionals.html#%28part._and%2Bor%29) (later in this guide) explains more about [and](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._and%2529%2529&version=8.18.0.13) and [or](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._or%2529%2529&version=8.18.0.13).\n> ```racket\n> ( and ‹ expr › * )\n> ( or ‹ expr › * )\n> ```"} {"text": "# 2.2 Simple Definitions and Expressions\nThe [and](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._and%2529%2529&version=8.18.0.13) form short-circuits: it stops and returns #f when an expression produces #f, otherwise it keeps going. The [or](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._or%2529%2529&version=8.18.0.13) form similarly short-circuits when it encounters a true result.\nExamples:\n> ```racket\n> ( define ( reply-non-string s ) ( if ( and ( string? s ) ( string-prefix? s \"hello \" ) ) \"hi!\" \"huh?\" ) )\n> > ( reply-non-string \"hello racket\" )\n> \"hi!\"\n> > ( reply-non-string 17 )\n> \"huh?\"\n> ```\nNote that in the above grammar, the [and](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._and%2529%2529&version=8.18.0.13) and [or](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._or%2529%2529&version=8.18.0.13) forms work with any number of expressions.\nExamples:"} {"text": "# 2.2 Simple Definitions and Expressions\n> ```racket\n> ( define ( reply-only-enthusiastic s ) ( if ( and ( string? s ) ( string-prefix? s \"hello \" ) ( string-suffix? s \"!\" ) ) \"hi!\" \"huh?\" ) )\n> > ( reply-only-enthusiastic \"hello racket!\" )\n> \"hi!\"\n> > ( reply-only-enthusiastic \"hello racket\" )\n> \"huh?\"\n> ```\nAnother common pattern of nested [if](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._if%2529%2529&version=8.18.0.13)s involves a sequence of tests, each with its own result:\n> ```racket\n> ( define ( reply-more s )\n> ( if ( string-prefix? s \"hello \" )\n> \"hi!\"\n> ( if ( string-prefix? s \"goodbye \" )\n> \"bye!\"\n> ( if ( string-suffix? s \"?\" )\n> \"I don't know\"\n> \"huh?\" ) ) ) )\n> ```\nThe shorthand for a sequence of tests is the [cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._cond%2529%2529&version=8.18.0.13) form:\n> > > \"+\"[Chaining Tests: cond](conditionals.html#%28part._cond%29) (later in this guide) explains more about [cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._cond%2529%2529&version=8.18.0.13).\n> ( cond {\\[ ‹expr› ‹expr›\\* \\]}\\* )"} {"text": "# 2.2 Simple Definitions and Expressions\nA [cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._cond%2529%2529&version=8.18.0.13) form contains a sequence of clauses between square brackets. In each clause, the first ‹expr› is a test expression. If it produces true, then the clause’s remaining ‹expr›s are evaluated, and the last one in the clause provides the answer for the entire [cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._cond%2529%2529&version=8.18.0.13) expression; the rest of the clauses are ignored. If the test ‹expr› produces #f, then the clause’s remaining ‹expr›s are ignored, and evaluation continues with the next clause. The last clause can use [else](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._else%2529%2529&version=8.18.0.13) as a synonym for a #t test expression.\nUsing [cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._cond%2529%2529&version=8.18.0.13), the reply-more function can be more clearly written as follows:\n> ```\n(define (reply-more s)"} {"text": "# 2.2 Simple Definitions and Expressions\n> ( cond\n> [ ( string-prefix? s \"hello \" )\n> \"hi!\" ]\n> [ ( string-prefix? s \"goodbye \" )\n> \"bye!\" ]\n> [ ( string-suffix? s \"?\" )\n> \"I don't know\" ]\n> [ else \"huh?\" ] ) )\n> ( reply-more \"hello racket\" )\n> \"hi!\"\n> > ( reply-more \"goodbye cruel world\" )\n> \"bye!\"\n> > ( reply-more \"what is your favorite color?\" )\n> \"I don't know\"\n> > ( reply-more \"mine is lime green\" )\n> \"huh?\"\n```\nThe use of square brackets for cond clauses is a convention. In Racket, parentheses and square brackets are actually interchangeable, as long as ( is matched with ) and \\[ is matched with \\]. Using square brackets in a few key places makes Racket code even more readable.\n\n#### 2.2.6 Function Calls, Again\n\nIn our earlier grammar of function calls, we oversimplified. The actual syntax of a function call allows an arbitrary expression for the function, instead of just an ‹id›:\n\n> > > \"+\"Function Calls (later in this guide) explains more about function calls.\n\n> ( ‹expr› ‹expr›\\* )\n\nThe first ‹expr› is often an ‹id›, such as string-append or +, but it can be anything that evaluates to a function. For example, it can be a conditional expression:\n\n>
( define ( double v )\n> ( ( if ( string? v ) string-append + ) v v ) )

 

> ( double \"mnah\" )\n> \"mnahmnah\"\n> > ( double 5 )\n> 10
\n\nSyntactically, the first expression in a function call could even be a number—but that leads to an error, since a number is not a function.\n\n> ```racket\n> > ( 1 2 3 4 )\n> application: not a procedure;\n> expected a procedure that can be applied to arguments\n> given: 1\n> ```\n\nWhen you accidentally omit a function name or when you use extra parentheses around an expression, you’ll most often get an “expected a procedure” error like this one.\n\n#### 2.2.7 Anonymous Functions with lambda\n\nProgramming in Racket would be tedious if you had to name all of your numbers. Instead of writing (+ 1 2), you’d have to write\n\n> > > \"+\"Functions: lambda (later in this guide) explains more about lambda.\n\n> ```racket\n> > ( define a 1 )\n> > ( define b 2 )\n> > ( + a b )\n> 3\n> ```\n\nIt turns out that having to name all your functions can be tedious, too. For example, you might have a function twice that takes a function and an argument. Using twice is convenient if you already have a name for the function, such as sqrt:\n\n>
( define ( twice f v )\n> ( f ( f v ) ) )

 

> ( twice sqrt 16 )\n> 2
\n\nIf you want to call a function that is not yet defined, you could define it, and then pass it to twice:\n\n>
( define ( louder s )\n> ( string-append s \"!\" ) )

 

> ( twice louder \"hello\" )\n> \"hello!!\"
\n\nBut if the call to twice is the only place where louder is used, it’s a shame to have to write a whole definition. In Racket, you can use a lambda expression to produce a function directly. The lambda form is followed by identifiers for the function’s arguments, and then the function’s body expressions:\n\n> ( lambda ( ‹id›\\* ) ‹expr›+ )\n\nEvaluating a lambda form by itself produces a function:\n\n> ```racket\n> > ( lambda ( s ) ( string-append s \"!\" ) )\n> #\n> ```\n\nUsing lambda, the above call to twice can be re-written as\n\n> ```racket\n> > ( twice ( lambda ( s ) ( string-append s \"!\" ) ) \"hello\" )\n> \"hello!!\"\n> > ( twice ( lambda ( s ) ( string-append s \"?!\" ) ) \"hello\" )\n> \"hello?!?!\"\n> ```\n\nAnother use of lambda is as a result for a function that generates functions:\n\n> ```\n(define (make-add-suffix s2)\n> ( lambda ( s ) ( string-append s s2 ) ) )\n \n> ( twice ( make-add-suffix \"!\" ) \"hello\" )\n> \"hello!!\"\n> > ( twice ( make-add-suffix \"?!\" ) \"hello\" )\n> \"hello?!?!\"\n> > ( twice ( make-add-suffix \"...\" ) \"hello\" )\n> \"hello......\"```\n\n\nRacket is a lexically scoped language, which means that s2 in the function returned by make-add-suffix always refers to the argument for the call that created the function. In other words, the [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13)-generated function “remembers” the right s2:\n\n> ```racket\n> > ( define louder ( make-add-suffix \"!\" ) )\n> > ( define less-sure ( make-add-suffix \"?\" ) )\n> > ( twice less-sure \"really\" )\n> \"really??\"\n> > ( twice louder \"really\" )\n> \"really!!\"\n> ```\n\nWe have so far referred to definitions of the form ([define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) ‹id› ‹expr›) as “non-function definitions.” This characterization is misleading, because the ‹expr› could be a [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) form, in which case the definition is equivalent to using the “function” definition form. For example, the following two definitions of louder are equivalent:\n\n>
( define ( louder s )\n> ( string-append s "!" ) )\n> ( define louder\n> ( lambda ( s )\n> ( string-append s "!" ) ) )

 

> louder\n> #<procedure:louder>
\n\nNote that the expression for louder in the second case is an “anonymous” function written with [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13), but, if possible, the compiler infers a name, anyway, to make printing and error reporting as informative as possible.\n\n#### 2.2.8 Local Binding with [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13), [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13), and [let*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%252A%2529%2529&version=8.18.0.13)\n\nIt’s time to retract another simplification in our grammar of Racket. In the body of a function, definitions can appear before the body expressions:\n\n> > > \"+\"[Internal Definitions](define.html#%28part._intdefs%29) (later in this guide) explains more about local (internal) definitions.\n\n> ```racket\n> ( define ( ‹ id › ‹ id › * ) ‹ definition › * ‹ expr › + )\n> ( lambda ( ‹ id › * ) ‹ definition › * ‹ expr › + )\n> ```\n\nDefinitions at the start of a function body are local to the function body.\n\nExamples:\n\n> ```racket\n> ( define ( converse s ) ( define ( starts? s2 ) ; local to converse ( define spaced-s2 ( string-append s2 \" \" ) ) ; local to starts? ( string-prefix? s spaced-s2 ) ) ( cond [ ( starts? \"hello\" ) \"hi!\" ] [ ( starts? \"goodbye\" ) \"bye!\" ] [ else \"huh?\" ] ) )\n> > ( converse \"hello world\" )\n> \"hi!\"\n> > ( converse \"hellonearth\" )\n> \"huh?\"\n> > ( converse \"goodbye friends\" )\n> \"bye!\"\n> > ( converse \"urp\" )\n> \"huh?\"\n> > starts? ; outside of converse , so...\n> starts?: undefined;\n> cannot reference an identifier before its definition\n> in module: top-level\n> ```\n\nAnother way to create local bindings is the [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) form. An advantage of [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) is that it can be used in any expression position. Also, [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) binds many identifiers at once, instead of requiring a separate [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) for each identifier.\n\n> > > \"+\"[Internal Definitions](define.html#%28part._intdefs%29) (later in this guide) explains more about [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) and [let*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%252A%2529%2529&version=8.18.0.13).\n\n> ( let ( {\\[ ‹id› ‹expr› \\]}\\* ) ‹expr›+ )\n\nEach binding clause is an ‹id› and an ‹expr› surrounded by square brackets, and the expressions after the clauses are the body of the [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13). In each clause, the ‹id› is bound to the result of the ‹expr› for use in the body.\n\n> ```racket\n> > ( let ( [ x ( random 4 ) ] [ o ( random 4 ) ] ) ( cond [ ( > x o ) \"X wins\" ] [ ( > o x ) \"O wins\" ] [ else \"cat's game\" ] ) )\n> \"cat's game\"\n> ```\n\nThe bindings of a [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) form are available only in the body of the [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13), so the binding clauses cannot refer to each other. The [let*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%252A%2529%2529&version=8.18.0.13) form, in contrast, allows later clauses to use earlier bindings:\n\n> ```racket\n> > ( let* ( [ x ( random 4 ) ] [ o ( random 4 ) ] [ diff ( number->string ( abs ( - x o ) ) ) ] ) ( cond [ ( > x o ) ( string-append \"X wins by \" diff ) ] [ ( > o x ) ( string-append \"O wins by \" diff ) ] [ else \"cat's game\" ] ) )\n> \"O wins by 2\"\n> ```\n\n------------------------------------------------------------------------\n\n# 2.3 Lists, Iteration, and Recursion\n\n### 2.3 Lists, Iteration, and Recursion\n\nRacket is a dialect of the language Lisp, whose name originally stood for “LISt Processor.” The built-in list datatype remains a prominent feature of the language.\n\nThe [list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._list%2529%2529&version=8.18.0.13) function takes any number of values and returns a list containing the values:\n\n> ```racket\n> > ( list \"red\" \"green\" \"blue\" )\n> '(\"red\" \"green\" \"blue\")\n> > ( list 1 2 3 4 5 )\n> '(1 2 3 4 5)\n> ```\n\n> > > A list usually prints with ', but the printed form of a list depends on its content. See [Pairs and Lists](pairs.html) for more information.\n\nAs you can see, a list result prints in the [REPL](intro.html#%28tech._repl%29) as a quote ' and then a pair of parentheses wrapped around the printed form of the list elements. There’s an opportunity for confusion here, because parentheses are used for both expressions, such as ([list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._list%2529%2529&version=8.18.0.13) \"red\" \"green\" \"blue\"), and printed results, such as '(\"red\" \"green\" \"blue\"). In addition to the quote, parentheses for results are printed in blue in the documentation and in DrRacket, whereas parentheses for expressions are brown.\n\nMany predefined functions operate on lists. Here are a few examples:\n\n> ```racket\n> > ( length ( list \"hop\" \"skip\" \"jump\" ) ) ; count the elements\n> 3\n> > ( list-ref ( list \"hop\" \"skip\" \"jump\" ) 0 ) ; extract by position\n> \"hop\"\n> > ( list-ref ( list \"hop\" \"skip\" \"jump\" ) 1 )\n> \"skip\"\n> > ( append ( list \"hop\" \"skip\" ) ( list \"jump\" ) ) ; combine lists\n> '(\"hop\" \"skip\" \"jump\")\n> > ( reverse ( list \"hop\" \"skip\" \"jump\" ) ) ; reverse order\n> '(\"jump\" \"skip\" \"hop\")\n> > ( member \"fall\" ( list \"hop\" \"skip\" \"jump\" ) ) ; check for an element\n> #f\n> ```\n\n#### 2.3.1 Predefined List Loops\n\nIn addition to simple operations like [append](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._append%2529%2529&version=8.18.0.13), Racket includes functions that iterate over the elements of a list. These iteration functions play a role similar to [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) in Java, Racket, and other languages. The body of a Racket iteration is packaged into a function to be applied to each element, so the [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) form becomes particularly handy in combination with iteration functions.\n\nDifferent list-iteration functions combine iteration results in different ways. The [map](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fmap..rkt%2529._map%2529%2529&version=8.18.0.13) function uses the per-element results to create a new list:\n\n> ```racket\n> > ( map sqrt ( list 1 4 9 16 ) )\n> '(1 2 3 4)\n> > ( map ( lambda ( i ) ( string-append i \"!\" ) ) ( list \"peanuts\" \"popcorn\" \"crackerjack\" ) )\n> '(\"peanuts!\" \"popcorn!\" \"crackerjack!\")\n> ```\n\nThe [andmap](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fmap..rkt%2529._andmap%2529%2529&version=8.18.0.13) and [ormap](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fmap..rkt%2529._ormap%2529%2529&version=8.18.0.13) functions combine the results by [and](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._and%2529%2529&version=8.18.0.13)ing or [or](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._or%2529%2529&version=8.18.0.13)ing:\n\n> ```racket\n> > ( andmap string? ( list \"a\" \"b\" \"c\" ) )\n> #t\n> > ( andmap string? ( list \"a\" \"b\" 6 ) )\n> #f\n> > ( ormap number? ( list \"a\" \"b\" 6 ) )\n> #t\n> ```\n\nThe [map](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fmap..rkt%2529._map%2529%2529&version=8.18.0.13), [andmap](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fmap..rkt%2529._andmap%2529%2529&version=8.18.0.13), and [ormap](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fmap..rkt%2529._ormap%2529%2529&version=8.18.0.13) functions can all handle multiple lists, instead of just a single list. The lists must all have the same length, and the given function must accept one argument for each list:\n\n> ```racket\n> > ( map ( lambda ( s n ) ( substring s 0 n ) ) ( list \"peanuts\" \"popcorn\" \"crackerjack\" ) ( list 6 3 7 ) )\n> '(\"peanut\" \"pop\" \"cracker\")\n> ```\n\nThe [filter](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Flist..rkt%2529._filter%2529%2529&version=8.18.0.13) function keeps elements for which the body result is true, and discards elements for which it is #f:\n\n> ```racket\n> > ( filter string? ( list \"a\" \"b\" 6 ) )\n> '(\"a\" \"b\")\n> > ( filter positive? ( list 1 -2 6 7 0 ) )\n> '(1 6 7)\n> ```\n\nThe [foldl](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Flist..rkt%2529._foldl%2529%2529&version=8.18.0.13) function generalizes some iteration functions. It uses the per-element function to both process an element and combine it with the “current” value, so the per-element function takes an extra first argument. Also, a starting “current” value must be provided before the lists:\n\n> ```racket\n> > ( foldl ( lambda ( elem v ) ( + v ( * elem elem ) ) ) 0 ' ( 1 2 3 ) )\n> 14\n> ```\n\nDespite its generality, [foldl](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Flist..rkt%2529._foldl%2529%2529&version=8.18.0.13) is not as popular as the other functions. One reason is that [map](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fmap..rkt%2529._map%2529%2529&version=8.18.0.13), [ormap](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fmap..rkt%2529._ormap%2529%2529&version=8.18.0.13), [andmap](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fmap..rkt%2529._andmap%2529%2529&version=8.18.0.13), and [filter](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Flist..rkt%2529._filter%2529%2529&version=8.18.0.13) cover the most common kinds of list loops.\n\nRacket provides a general list comprehension form [for/list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252Flist%2529%2529&version=8.18.0.13), which builds a list by iterating through sequences. List comprehensions and related iteration forms are described in [Iterations and Comprehensions](for.html).\n\n#### 2.3.2 List Iteration from Scratch\n\nAlthough [map](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fmap..rkt%2529._map%2529%2529&version=8.18.0.13) and other iteration functions are predefined, they are not primitive in any interesting sense. You can write equivalent iterations using a handful of list primitives.\n\nSince a Racket list is a linked list, the two core operations on a non-empty list are\n\n- [first](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Flist..rkt%2529._first%2529%2529&version=8.18.0.13): get the first thing in the list; and\n\n- [rest](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Flist..rkt%2529._rest%2529%2529&version=8.18.0.13): get the rest of the list.\n\nExamples:\n\n> ```racket\n> > ( first ( list 1 2 3 ) )\n> 1\n> > ( rest ( list 1 2 3 ) )\n> '(2 3)\n> ```\n\nTo create a new node for a linked list—that is, to add to the front of the list—use the [cons](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cons%2529%2529&version=8.18.0.13) function, which is short for “construct.” To get an empty list to start with, use the [empty](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Flist..rkt%2529._empty%2529%2529&version=8.18.0.13) constant:\n\n> ```racket\n> > empty\n> '()\n> > ( cons \"head\" empty )\n> '(\"head\")\n> > ( cons \"dead\" ( cons \"head\" empty ) )\n> '(\"dead\" \"head\")\n> ```\n\nTo process a list, you need to be able to distinguish empty lists from non-empty lists, because [first](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Flist..rkt%2529._first%2529%2529&version=8.18.0.13) and [rest](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Flist..rkt%2529._rest%2529%2529&version=8.18.0.13) work only on non-empty lists. The [empty?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Flist..rkt%2529._empty%7E3f%2529%2529&version=8.18.0.13) function detects empty lists, and [cons?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Flist..rkt%2529._cons%7E3f%2529%2529&version=8.18.0.13) detects non-empty lists:\n\n> ```racket\n> > ( empty? empty )\n> #t\n> > ( empty? ( cons \"head\" empty ) )\n> #f\n> > ( cons? empty )\n> #f\n> > ( cons? ( cons \"head\" empty ) )\n> #t\n> ```\n\nWith these pieces, you can write your own versions of the [length](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._length%2529%2529&version=8.18.0.13) function, [map](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fmap..rkt%2529._map%2529%2529&version=8.18.0.13) function, and more.\n\nExamples:\n\n> ```racket\n> ( define ( my-length lst ) ( cond [ ( empty? lst ) 0 ] [ else ( + 1 ( my-length ( rest lst ) ) ) ] ) )\n> > ( my-length empty )\n> 0\n> > ( my-length ( list \"a\" \"b\" \"c\" ) )\n> 3\n> ```\n\n> ```\n(define (my-map f lst)\n> ( cond\n> [ ( empty? lst ) empty ]\n> [ else ( cons ( f ( first lst ) )\n> ( my-map f ( rest lst ) ) ) ] ) )\n \n> ( my-map string-upcase ( list \"ready\" \"set\" \"go\" ) )\n> '(\"READY\" \"SET\" \"GO\")\n```"} {"text": "# 2.2 Simple Definitions and Expressions\nIf the derivation of the above definitions is mysterious to you, consider reading How to Design Programs. If you are merely suspicious of the use of recursive calls instead of a looping construct, then read on."} {"text": "#### 2.3.3 Tail Recursion\nBoth the my-length and my-map functions run in O(n) space for a list of length n. This is easy to see by imagining how (my-length (list \"a\" \"b\" \"c\")) must evaluate:\n> ```racket\n> ( my-length ( list \"a\" \"b\" \"c\" ) )\n> = ( + 1 ( my-length ( list \"b\" \"c\" ) ) )\n> = ( + 1 ( + 1 ( my-length ( list \"c\" ) ) ) )\n> = ( + 1 ( + 1 ( + 1 ( my-length ( list ) ) ) ) )\n> = ( + 1 ( + 1 ( + 1 0 ) ) )\n> = ( + 1 ( + 1 1 ) )\n> = ( + 1 2 )\n> = 3\n> ```\nFor a list with n elements, evaluation will stack up n (+ 1 ...) additions, and then finally add them up when the list is exhausted.\nYou can avoid piling up additions by adding along the way. To accumulate a length this way, we need a function that takes both a list and the length of the list seen so far; the code below uses a local function iter that accumulates the length in an argument len:\n> ```racket\n> ( define ( my-length lst )\n> ; local function iter :\n> ( define ( iter lst len )\n> ( cond\n> [ ( empty? lst ) len ]\n> [ else ( iter ( rest lst ) ( + len 1 ) ) ] ) )\n> ; body of my-length calls iter :\n> ( iter lst 0 ) )\n> ```\nNow evaluation looks like this:\n> ```racket\n> ( my-length ( list \"a\" \"b\" \"c\" ) )\n> = ( iter ( list \"a\" \"b\" \"c\" ) 0 )\n> = ( iter ( list \"b\" \"c\" ) 1 )\n> = ( iter ( list \"c\" ) 2 )\n> = ( iter ( list ) 3 )\n> 3\n> ```"} {"text": "# 2.2 Simple Definitions and Expressions\nThe revised my-length runs in constant space, just as the evaluation steps above suggest. That is, when the result of a function call, like (iter (list \"b\" \"c\") 1), is exactly the result of some other function call, like (iter (list \"c\") 2), then the first one doesn’t have to wait around for the second one, because that takes up space for no good reason.\nThis evaluation behavior is sometimes called tail-call optimization, but it’s not merely an “optimization” in Racket; it’s a guarantee about the way the code will run. More precisely, an expression in tail position with respect to another expression does not take extra computation space over the other expression.\nIn the case of my-map, O(n) space complexity is reasonable, since it has to generate a result of size O(n). Nevertheless, you can reduce the constant factor by accumulating the result list. The only catch is that the accumulated list will be backwards, so you’ll have to reverse it at the very end:\n> > > Attempting to reduce a constant factor like this is usually not worthwhile, as discussed below.\n> ```racket\n> ( define ( my-map f lst )\n> ( define ( iter lst backward-result )\n> ( cond\n> [ ( empty? lst ) ( reverse backward-result ) ]\n> [ else ( iter ( rest lst )\n> ( cons ( f ( first lst ) )\n> backward-result ) ) ] ) )\n> ( iter lst empty ) )\n> ```\nIt turns out that if you write\n> ```racket\n> ( define ( my-map f lst )\n> ( for/list ( [ i lst ] )\n> ( f i ) ) )\n> ```"} {"text": "# 2.2 Simple Definitions and Expressions\nthen the for/list form in the function is expanded to essentially the same code as the iter local definition and use. The difference is merely syntactic convenience."} {"text": "#### 2.3.4 Recursion versus Iteration\nThe my-length and my-map examples demonstrate that iteration is just a special case of recursion. In many languages, it’s important to try to fit as many computations as possible into iteration form. Otherwise, performance will be bad, and moderately large inputs can lead to stack overflow. Similarly, in Racket, it is sometimes important to make sure that tail recursion is used to avoid O(n) space consumption when the computation is easily performed in constant space.\nAt the same time, recursion does not lead to particularly bad performance in Racket, and there is no such thing as stack overflow; you can run out of memory if a computation involves too much context, but exhausting memory typically requires orders of magnitude deeper recursion than would trigger a stack overflow in other languages. These considerations, combined with the fact that tail-recursive programs automatically run the same as a loop, lead Racket programmers to embrace recursive forms rather than avoid them.\nSuppose, for example, that you want to remove consecutive duplicates from a list. While such a function can be written as a loop that remembers the previous element for each iteration, a Racket programmer would more likely just write the following:\n> ```\n(define (remove-dups l)\n> ( cond\n> [ ( empty? l ) empty ]\n> [ ( empty? ( rest l ) ) l ]\n> [ else\n> ( let ( [ i ( first l ) ] )\n> ( if ( equal? i ( first ( rest l ) ) )\n> ( remove-dups ( rest l ) )\n> ( cons i ( remove-dups ( rest l ) ) ) ) ) ] ) )"} {"text": "# 2.2 Simple Definitions and Expressions\n> ( remove-dups ( list \"a\" \"b\" \"b\" \"b\" \"c\" \"c\" ) )\n> '(\"a\" \"b\" \"c\")```\nIn general, this function consumes O(n) space for an input list of length n, but that’s fine, since it produces an O(n) result. If the input list happens to be mostly consecutive duplicates, then the resulting list can be much smaller than O(n)—and remove-dups will also use much less than O(n) space! The reason is that when the function discards duplicates, it returns the result of a remove-dups call directly, so the tail-call “optimization” kicks in:\n> ```racket\n> ( remove-dups ( list \"a\" \"b\" \"b\" \"b\" \"b\" \"b\" ) )\n> = ( cons \"a\" ( remove-dups ( list \"b\" \"b\" \"b\" \"b\" \"b\" ) ) )\n> = ( cons \"a\" ( remove-dups ( list \"b\" \"b\" \"b\" \"b\" ) ) )\n> = ( cons \"a\" ( remove-dups ( list \"b\" \"b\" \"b\" ) ) )\n> = ( cons \"a\" ( remove-dups ( list \"b\" \"b\" ) ) )\n> = ( cons \"a\" ( remove-dups ( list \"b\" ) ) )\n> = ( cons \"a\" ( list \"b\" ) )\n> = ( list \"a\" \"b\" )\n> ```\n------------------------------------------------------------------------"} {"text": "# 2.4 Pairs, Lists, and Racket Syntax"} {"text": "### 2.4 Pairs, Lists, and Racket Syntax\nThe [cons](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cons%2529%2529&version=8.18.0.13) function actually accepts any two values, not just a list for the second argument. When the second argument is not [empty](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Flist..rkt%2529._empty%2529%2529&version=8.18.0.13) and not itself produced by [cons](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cons%2529%2529&version=8.18.0.13), the result prints in a special way. The two values joined with [cons](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cons%2529%2529&version=8.18.0.13) are printed between parentheses, but with a dot (i.e., a period surrounded by whitespace) in between:\n> ```racket\n> > ( cons 1 2 )\n> '(1 . 2)\n> > ( cons \"banana\" \"split\" )\n> '(\"banana\" . \"split\")\n> ```"} {"text": "# 2.4 Pairs, Lists, and Racket Syntax\nThus, a value produced by [cons](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cons%2529%2529&version=8.18.0.13) is not always a list. In general, the result of [cons](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cons%2529%2529&version=8.18.0.13) is a pair. The more traditional name for the [cons?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Flist..rkt%2529._cons%7E3f%2529%2529&version=8.18.0.13) function is [pair?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._pair%7E3f%2529%2529&version=8.18.0.13), and we’ll use the traditional name from now on."} {"text": "# 2.4 Pairs, Lists, and Racket Syntax\nThe name [rest](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Flist..rkt%2529._rest%2529%2529&version=8.18.0.13) also makes less sense for non-list pairs; the more traditional names for [first](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Flist..rkt%2529._first%2529%2529&version=8.18.0.13) and [rest](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Flist..rkt%2529._rest%2529%2529&version=8.18.0.13) are [car](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._car%2529%2529&version=8.18.0.13) and [cdr](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cdr%2529%2529&version=8.18.0.13), respectively. (Granted, the traditional names are also nonsense. Just remember that “a” comes before “d,” and [cdr](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cdr%2529%2529&version=8.18.0.13) is pronounced “could-er.”)\nExamples:"} {"text": "# 2.4 Pairs, Lists, and Racket Syntax\n> ```racket\n> > ( car ( cons 1 2 ) )\n> 1\n> > ( cdr ( cons 1 2 ) )\n> 2\n> > ( pair? empty )\n> #f\n> > ( pair? ( cons 1 2 ) )\n> #t\n> > ( pair? ( list 1 2 3 ) )\n> #t\n> ```\nRacket’s pair datatype and its relation to lists is essentially a historical curiosity, along with the dot notation for printing and the funny names [car](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._car%2529%2529&version=8.18.0.13) and [cdr](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cdr%2529%2529&version=8.18.0.13). Pairs are deeply wired into the culture, specification, and implementation of Racket, however, so they survive in the language.\nYou are perhaps most likely to encounter a non-list pair when making a mistake, such as accidentally reversing the arguments to [cons](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cons%2529%2529&version=8.18.0.13):\n> ```racket\n> > ( cons ( list 2 3 ) 1 )\n> '((2 3) . 1)\n> > ( cons 1 ( list 2 3 ) )\n> '(1 2 3)\n> ```"} {"text": "# 2.4 Pairs, Lists, and Racket Syntax\nNon-list pairs are used intentionally, sometimes. For example, the [make-hash](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=hashtables.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._make-hash%2529%2529&version=8.18.0.13) function takes a list of pairs, where the [car](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._car%2529%2529&version=8.18.0.13) of each pair is a key and the [cdr](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cdr%2529%2529&version=8.18.0.13) is an arbitrary value.\nThe only thing more confusing to new Racketeers than non-list pairs is the printing convention for pairs where the second element is a pair, but is not a list:\n> ```racket\n> > ( cons 0 ( cons 1 2 ) )\n> '(0 1 . 2)\n> ```\nIn general, the rule for printing a pair is as follows: use the dot notation unless the dot is immediately followed by an open parenthesis. In that case, remove the dot, the open parenthesis, and the matching close parenthesis. Thus, '(0 . (1 . 2)) becomes '(0 1 . 2), and '(1 . (2 . (3 . ()))) becomes '(1 2 3)."} {"text": "#### 2.4.1 Quoting Pairs and Symbols with [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13)\nA list prints with a quote mark before it, but if an element of a list is itself a list, then no quote mark is printed for the inner list:\n> ```racket\n> > ( list ( list 1 ) ( list 2 3 ) ( list 4 ) )\n> '((1) (2 3) (4))\n> ```\nFor nested lists, especially, the [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) form lets you write a list as an expression in essentially the same way that the list prints:\n> ```racket\n> > ( quote ( \"red\" \"green\" \"blue\" ) )\n> '(\"red\" \"green\" \"blue\")\n> > ( quote ( ( 1 ) ( 2 3 ) ( 4 ) ) )\n> '((1) (2 3) (4))\n> > ( quote ( ) )\n> '()\n> ```\nThe [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) form works with the dot notation, too, whether the quoted form is normalized by the dot-parenthesis elimination rule or not:\n> ```racket\n> > ( quote ( 1 . 2 ) )\n> '(1 . 2)\n> > ( quote ( 0 . ( 1 . 2 ) ) )\n> '(0 1 . 2)\n> ```\nNaturally, lists of any kind can be nested:"} {"text": "# 2.4 Pairs, Lists, and Racket Syntax\n> ```racket\n> > ( list ( list 1 2 3 ) 5 ( list \"a\" \"b\" \"c\" ) )\n> '((1 2 3) 5 (\"a\" \"b\" \"c\"))\n> > ( quote ( ( 1 2 3 ) 5 ( \"a\" \"b\" \"c\" ) ) )\n> '((1 2 3) 5 (\"a\" \"b\" \"c\"))\n> ```\nIf you wrap an identifier with [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13), then you get output that looks like an identifier, but with a ' prefix:\n> ```racket\n> > ( quote jane-doe )\n> 'jane-doe\n> ```\nA value that prints like a quoted identifier is a symbol. In the same way that parenthesized output should not be confused with expressions, a printed symbol should not be confused with an identifier. In particular, the symbol ([quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) map) has nothing to do with the map identifier or the predefined function that is bound to [map](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fmap..rkt%2529._map%2529%2529&version=8.18.0.13), except that the symbol and the identifier happen to be made up of the same letters."} {"text": "# 2.4 Pairs, Lists, and Racket Syntax\nIndeed, the intrinsic value of a symbol is nothing more than its character content. In this sense, symbols and strings are almost the same thing, and the main difference is how they print. The functions [symbol->string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=symbols.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._symbol-%7E3estring%2529%2529&version=8.18.0.13) and [string->symbol](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=symbols.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._string-%7E3esymbol%2529%2529&version=8.18.0.13) convert between them.\nExamples:\n> ```racket\n> > map\n> #\n> > ( quote map )\n> 'map\n> > ( symbol? ( quote map ) )\n> #t\n> > ( symbol? map )\n> #f\n> > ( procedure? map )\n> #t\n> > ( string->symbol \"map\" )\n> 'map\n> > ( symbol->string ( quote map ) )\n> \"map\"\n> ```"} {"text": "# 2.4 Pairs, Lists, and Racket Syntax\nIn the same way that [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) for a list automatically applies itself to nested lists, [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) on a parenthesized sequence of identifiers automatically applies itself to the identifiers to create a list of symbols:\n> ```racket\n> > ( car ( quote ( road map ) ) )\n> 'road\n> > ( symbol? ( car ( quote ( road map ) ) ) )\n> #t\n> ```\nWhen a symbol is inside a list that is printed with ', the ' on the symbol is omitted, since ' is doing the job already:\n> ```racket\n> > ( quote ( road map ) )\n> '(road map)\n> ```\nThe [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) form has no effect on a literal expression such as a number or string:\n> ```racket\n> > ( quote 42 )\n> 42\n> > ( quote \"on the record\" )\n> \"on the record\"\n> ```"} {"text": "#### 2.4.2 Abbreviating [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) with '\nAs you may have guessed, you can abbreviate a use of [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) by just putting ' in front of a form to quote:\n> ```racket\n> > ' ( 1 2 3 )\n> '(1 2 3)\n> > ' road\n> 'road\n> > ' ( ( 1 2 3 ) road ( \"a\" \"b\" \"c\" ) )\n> '((1 2 3) road (\"a\" \"b\" \"c\"))\n> ```\nIn the documentation, ' within an expression is printed in green along with the form after it, since the combination is an expression that is a constant. In DrRacket, only the ' is colored green. DrRacket is more precisely correct, because the meaning of [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) can vary depending on the context of an expression. In the documentation, however, we routinely assume that standard bindings are in scope, and so we paint quoted forms in green for extra clarity."} {"text": "# 2.4 Pairs, Lists, and Racket Syntax\nA ' expands to a [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) form in quite a literal way. You can see this if you put a ' in front of a form that has a ':\n> ```racket\n> > ( car ' ' road )\n> 'quote\n> > ( car ' ( quote road ) )\n> 'quote\n> ```\nThe ' abbreviation works in output as well as input. The [REPL](intro.html#%28tech._repl%29)’s printer recognizes the symbol 'quote as the first element of a two-element list when printing output, in which case it uses ’ to print the output:\n> ```racket\n> > ( quote ( quote road ) )\n> ''road\n> > ' ( quote road )\n> ''road\n> > ' ' road\n> ''road\n> ```"} {"text": "#### 2.4.3 Lists and Racket Syntax\nNow that you know the truth about pairs and lists, and now that you’ve seen [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13), you’re ready to understand the main way in which we have been simplifying Racket’s true syntax.\nThe syntax of Racket is not defined directly in terms of character streams. Instead, the syntax is determined by two layers:\n- a reader layer, which turns a sequence of characters into lists, symbols, and other constants; and\n- an expander layer, which processes the lists, symbols, and other constants to parse them as an expression.\nThe rules for printing and reading go together. For example, a list is printed with parentheses, and reading a pair of parentheses produces a list. Similarly, a non-list pair is printed with the dot notation, and a dot on input effectively runs the dot-notation rules in reverse to obtain a pair.\nOne consequence of the read layer for expressions is that you can use the dot notation in expressions that are not quoted forms:\n> ```racket\n> > ( + 1 . ( 2 ) )\n> 3\n> ```"} {"text": "# 2.4 Pairs, Lists, and Racket Syntax\nThis works because ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) 1 . (2)) is just another way of writing ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) 1 2). It is practically never a good idea to write application expressions using this dot notation; it’s just a consequence of the way Racket’s syntax is defined.\nNormally, . is allowed by the reader only with a parenthesized sequence, and only before the last element of the sequence. However, a pair of .s can also appear around a single element in a parenthesized sequence, as long as the element is not first or last. Such a pair triggers a reader conversion that moves the element between .s to the front of the list. The conversion enables a kind of general infix notation:\n> ```racket\n> > ( 1 . < . 2 )> #t\n> > ' ( 1 . < . 2 )> '(< 1 2)> ```"} {"text": "# 2.4 Pairs, Lists, and Racket Syntax\nThis two-dot convention is non-traditional, and it has essentially nothing to do with the dot notation for non-list pairs. Racket programmers use the infix convention sparingly—mostly for asymmetric binary operators such as [<](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%7E3c%2529%2529&version=8.18.0.13) and [is-a?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objectutils.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._is-a%7E3f%2529%2529&version=8.18.0.13).\n------------------------------------------------------------------------"} {"text": "# 3 Built-In Datatypes"} {"text": "## 3 Built-In Datatypes\nThe [previous chapter](to-scheme.html) introduced some of Racket’s built-in datatypes: numbers, booleans, strings, lists, and procedures. This section provides a more complete coverage of the built-in datatypes for simple forms of data.\n| |\n|-------------------------------------------------------------------------------|\n|     [3.1 Booleans](booleans.html) |\n|     [3.2 Numbers](numbers.html) |\n|     [3.3 Characters](characters.html) |\n|     [3.4 Strings (Unicode)](strings.html) |\n|     [3.5 Bytes and Byte Strings](bytestrings.html) |\n|     [3.6 Symbols](symbols.html) |\n|     [3.7 Keywords](keywords.html) |\n|     [3.8 Pairs and Lists](pairs.html) |\n|     [3.9 Vectors](vectors.html) |\n|     [3.10 Hash Tables](hash-tables.html) |\n|     [3.11 Boxes](boxes.html) |\n|     [3.12 Void and Undefined](void_undefined.html) |\n------------------------------------------------------------------------"} {"text": "# 3.1 Booleans"} {"text": "### 3.1 Booleans\nRacket has two distinguished constants to represent boolean values: #t for true and #f for false. Uppercase #T and #F are parsed as the same values, but the lowercase forms are preferred.\nThe [boolean?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=booleans.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._boolean%7E3f%2529%2529&version=8.18.0.13) procedure recognizes the two boolean constants. In the result of a test expression for [if](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._if%2529%2529&version=8.18.0.13), [cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._cond%2529%2529&version=8.18.0.13), [and](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._and%2529%2529&version=8.18.0.13), [or](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._or%2529%2529&version=8.18.0.13), etc., however, any value other than #f counts as true.\nExamples:"} {"text": "# 3.1 Booleans\n> ```racket\n> > ( = 2 ( + 1 1 ) )\n> #t\n> > ( boolean? #t )\n> #t\n> > ( boolean? #f )\n> #t\n> > ( boolean? \"no\" )\n> #f\n> > ( if \"no\" 1 0 )\n> 1\n> ```\n------------------------------------------------------------------------"} {"text": "# 3.2 Numbers"} {"text": "### 3.2 Numbers\nA Racket number is either exact or inexact:\n- An exact number is either\n - an arbitrarily large or small integer, such as 5, 99999999999999999, or -17;\n - a rational that is exactly the ratio of two arbitrarily small or large integers, such as 1/2, 99999999999999999/2, or -3/4; or\n - a complex number with exact real and imaginary parts (where the imaginary part is not zero), such as 1+2i or 1/2+3/4i.\n- An inexact number is either\n - an IEEE floating-point representation of a number, such as 2.0 or 3.14e+87, where the IEEE infinities and not-a-number are written +inf.0, -inf.0, and +nan.0 (or -nan.0); or\n - a complex number with real and imaginary parts that are IEEE floating-point representations, such as 2.0+3.0i or -inf.0+nan.0i; as a special case, an inexact complex number can have an exact zero real part with an inexact imaginary part.\nInexact numbers print with a decimal point or exponent specifier, and exact numbers print as integers and fractions. The same conventions apply for reading number constants, but #e or #i can prefix a number to force its parsing as an exact or inexact number. The prefixes #b, #o, and #x specify binary, octal, and hexadecimal interpretation of digits."} {"text": "# 3.2 Numbers\n> > > \"+\"[Reading Numbers](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=reader.html%23%2528part._parse-number%2529&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) documents the fine points of the syntax of numbers.\nExamples:\n> ```racket\n> > 0.5\n> 0.5\n> > #e0.5\n> 1/2\n> > #x03BB\n> 955\n> ```\nComputations that involve an inexact number produce inexact results, so that inexactness acts as a kind of taint on numbers. Beware, however, that Racket offers no “inexact booleans,” so computations that branch on the comparison of inexact numbers can nevertheless produce exact results. The procedures [exact->inexact](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._exact-%7E3einexact%2529%2529&version=8.18.0.13) and [inexact->exact](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._inexact-%7E3eexact%2529%2529&version=8.18.0.13) convert between the two types of numbers.\nExamples:\n> ```racket\n> > ( / 1 2 )\n> 1/2\n> > ( / 1 2.0 )\n> 0.5\n> > ( if ( = 3.0 2.999 ) 1 2 )\n> 2\n> > ( inexact->exact 0.1 )\n> 3602879701896397/36028797018963968\n> ```"} {"text": "# 3.2 Numbers\nInexact results are also produced by procedures such as [sqrt](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._sqrt%2529%2529&version=8.18.0.13), [log](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._log%2529%2529&version=8.18.0.13), and [sin](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._sin%2529%2529&version=8.18.0.13) when an exact result would require representing real numbers that are not rational. Racket can represent only rational numbers and complex numbers with rational parts.\nExamples:\n> ```racket\n> > ( sin 0 ) ; rational...\n> 0\n> > ( sin 1/2 ) ; not rational...\n> 0.479425538604203\n> ```\nIn terms of performance, computations with small integers are typically the fastest, where “small” means that the number fits into one bit less than the machine’s word-sized representation for signed numbers. Computation with very large exact integers or with non-integer exact numbers can be much more expensive than computation with inexact numbers.\n> ```\n(define (sigma f a b)\n> ( if ( = a b )\n> 0\n> ( + ( f a ) ( sigma f ( + a 1 ) b ) ) ) )"} {"text": "# 3.2 Numbers\n> ( time ( round ( sigma ( lambda ( x ) ( / 1 x ) ) 1 2000 ) ) )\n> cpu time: 21 real time: 3 gc time: 0\n> 8\n> > ( time ( round ( sigma ( lambda ( x ) ( / 1.0 x ) ) 1 2000 ) ) )\n> cpu time: 0 real time: 0 gc time: 0\n> 8.0\n```\n(Unicode)\t→\t\n(-> integer → char 65)```\n\n\nThe above example says that, within a something-else form, a thing is either an identifier or a keyword.\n\n------------------------------------------------------------------------\n\n# 4.2 Identifiers and Binding\n\n### 4.2 Identifiers and Binding\n\nThe context of an expression determines the meaning of identifiers that appear in the expression. In particular, starting a module with the language [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13), as in\n\n> [#lang](Module_Syntax.html#%28part._hash-lang%29) [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13)\n\nmeans that, within the module, the identifiers described in this guide start with the meaning described here: [cons](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cons%2529%2529&version=8.18.0.13) refers to the function that creates a pair, [car](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._car%2529%2529&version=8.18.0.13) refers to the function that extracts the first element of a pair, and so on.\n\n> > > \"+\"[Symbols](symbols.html) introduces the syntax of identifiers.\n\nForms like [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13), [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13), and [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) associate a meaning with one or more identifiers; that is, they bind identifiers. The part of the program for which the binding applies is the scope of the binding. The set of bindings in effect for a given expression is the expression’s environment.\n\nFor example, in\n\n> ```racket\n> #lang racket\n> ( define f\n> ( lambda ( x )\n> ( let ( [ y 5 ] )\n> ( + x y ) ) ) )\n> ( f 10 )\n> ```\n\nthe [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) is a binding of f, the [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) has a binding for x, and the [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) has a binding for y. The scope of the binding for f is the entire module; the scope of the x binding is ([let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) (\\[y 5\\]) ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) x y)); and the scope of the y binding is just ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) x y). The environment of ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) x y) includes bindings for y, x, and f, as well as everything in [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13).\n\nA module-level [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) can bind only identifiers that are not already defined or [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)d into the module. A local [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) or other binding forms, however, can give a new local binding for an identifier that already has a binding; such a binding shadows the existing binding.\n\nExamples:\n\n> ```racket\n> ( define f ( lambda ( append ) ( define cons ( append \"ugly\" \"confusing\" ) ) ( let ( [ append ' this-was ] ) ( list append cons ) ) ) )\n> > ( f list )\n> '(this-was (\"ugly\" \"confusing\"))\n> ```\n\nSimilarly, a module-level [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) can [shadow](#%28tech._shadow%29) a binding from the module’s language. For example, ([define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) [cons](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cons%2529%2529&version=8.18.0.13) 1) in a [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) module shadows the [cons](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cons%2529%2529&version=8.18.0.13) that is provided by [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13). Intentionally shadowing a language binding is rarely a good idea—especially for widely used bindings like [cons](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cons%2529%2529&version=8.18.0.13)—but shadowing relieves a programmer from having to avoid every obscure binding that is provided by a language.\n\nEven identifiers like [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) and [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) get their meanings from bindings, though they have transformer bindings (which means that they indicate syntactic forms) instead of value bindings. Since [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) has a transformer binding, the identifier define cannot be used by itself to get a value. However, the normal binding for define can be shadowed.\n\nExamples:\n\n> ```racket\n> > define\n> eval:1:0: define: bad syntax\n> in: define\n> > ( let ( [ define 5 ] ) define )\n> 5\n> ```\n\nAgain, shadowing standard bindings in this way is rarely a good idea, but the possibility is an inherent part of Racket’s flexibility.\n\n------------------------------------------------------------------------\n\n# 4.3 Function Calls\n\n### 4.3 Function Calls (Procedure Applications)\n\nAn expression of the form\n\n> > | |\n> > |--------------------------|\n> > | (proc-expr arg-expr ...) |\n\nis a function call—also known as a procedure application—when proc-expr is not an identifier that is bound as a syntax transformer (such as [if](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._if%2529%2529&version=8.18.0.13) or [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13)).\n\n#### 4.3.1 Evaluation Order and Arity\n\nA function call is evaluated by first evaluating the proc-expr and all arg-exprs in order (left to right). Then, if proc-expr produces a function that accepts as many arguments as supplied arg-exprs, the function is called. Otherwise, an exception is raised.\n\nExamples:\n\n> ```racket\n> > ( cons 1 null )\n> '(1)\n> > ( + 1 2 3 )\n> 6\n> > ( cons 1 2 3 )\n> cons: arity mismatch;\n> the expected number of arguments does not match the given\n> number\n> expected: 2\n> given: 3\n> > ( 1 2 3 )\n> application: not a procedure;\n> expected a procedure that can be applied to arguments\n> given: 1\n> ```\n\nSome functions, such as [cons](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cons%2529%2529&version=8.18.0.13), accept a fixed number of arguments. Some functions, such as [+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) or [list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._list%2529%2529&version=8.18.0.13), accept any number of arguments. Some functions accept a range of argument counts; for example [substring](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._substring%2529%2529&version=8.18.0.13) accepts either two or three arguments. A function’s arity is the number of arguments that it accepts.\n\n#### 4.3.2 Keyword Arguments\n\nSome functions accept keyword arguments in addition to by-position arguments. For that case, an arg can be an arg-keyword arg-expr sequence instead of just a arg-expr:\n\n> > > \"+\"[Keywords](keywords.html) introduces keywords.\n\n> > ```\n(proc-expr arg ...)\n \narg   =   arg-expr\n    |   arg-keyword arg-expr\n```"} {"text": "# 3.2 Numbers\nFor example,\n> (go \"super.rkt\" #:mode 'fast)\ncalls the function bound to go with \"super.rkt\" as a by-position argument, and with 'fast as an argument associated with the #:mode keyword. A keyword is implicitly paired with the expression that follows it.\nSince a keyword by itself is not an expression, then\n> (go \"super.rkt\" #:mode #:fast)\nis a syntax error. The #:mode keyword must be followed by an expression to produce an argument value, and #:fast is not an expression.\nThe order of keyword args determines the order in which arg-exprs are evaluated, but a function accepts keyword arguments independent of their position in the argument list. The above call to go can be equivalently written\n> (go #:mode 'fast \"super.rkt\")\n> > > \"+\"Procedure Applications and #%app in The Racket Reference provides more on procedure applications."} {"text": "#### 4.3.3 The apply Function\nThe syntax for function calls supports any number of arguments, but a specific call always specifies a fixed number of arguments. As a result, a function that takes a list of arguments cannot directly apply a function like + to all of the items in a list:\n> ```\n(define (avg lst) ; doesn’t work...\n> ( / ( + lst ) ( length lst ) ) )\n> ( avg ' ( 1 2 3 ) )\n> +: contract violation\n> expected: number?\n> given: '(1 2 3)```\n> ```\n(define (avg lst) ; doesn’t always work...\n> ( / ( + ( list-ref lst 0 ) ( list-ref lst 1 ) ( list-ref lst 2 ) )\n> ( length lst ) ) )\n> ( avg ' ( 1 2 3 ) )\n> 2\n> > ( avg ' ( 1 2 ) )\n> list-ref: index too large for list\n> index: 2\n> in: '(1 2)"} {"text": "# 3.2 Numbers\n```\nThe apply function offers a way around this restriction. It takes a function and a list argument, and it applies the function to the values in the list:\n\n>
( define ( avg lst )\n> ( / ( apply + lst ) ( length lst ) ) )

 

> ( avg ' ( 1 2 3 ) )\n> 2\n> > ( avg ' ( 1 2 ) )\n> 3/2\n> > ( avg ' ( 1 2 3 4 ) )\n> 5/2
\n\nAs a convenience, the apply function accepts additional arguments between the function and the list. The additional arguments are effectively consed onto the argument list:\n\n>
( define ( anti-sum lst )\n> ( apply - 0 lst ) )

 

> ( anti-sum ' ( 1 2 3 ) )\n> -6
\n\nThe apply function accepts keyword arguments, too, and it passes them along to the called function:\n\n> ```racket\n> ( apply go #:mode ' fast ' ( \"super.rkt\" ) )\n> ( apply go ' ( \"super.rkt\" ) #:mode ' fast )\n> ```\n\nKeywords that are included in apply’s list argument do not count as keyword arguments for the called function; instead, all arguments in this list are treated as by-position arguments. To pass a list of keyword arguments to a function, use the keyword-apply function, which accepts a function to apply and three lists. The first two lists are in parallel, where the first list contains keywords (sorted by keyword ```racket\n> ( keyword-apply go\n> ' ( #:mode )\n> ' ( fast )\n> ' ( \"super.rkt\" ) )\n> ```\n\n------------------------------------------------------------------------\n\n# 4.4 Functions: lambda\n\n### 4.4 Functions (Procedures): lambda\n\nA lambda expression creates a function. In the simplest case, a lambda expression has the form\n\n> > ```\n(lambda (arg-id ...)\n> > body ...+ )```\n\n\nA [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) form with n arg-ids accepts n arguments:\n\n> ```racket\n> > ( ( lambda ( x ) x ) 1 )\n> 1\n> > ( ( lambda ( x y ) ( + x y ) ) 1 2 )\n> 3\n> > ( ( lambda ( x y ) ( + x y ) ) 1 )\n> arity mismatch;\n> the expected number of arguments does not match the given\n> number\n> expected: 2\n> given: 1\n> ```\n\n#### 4.4.1 Declaring a Rest Argument\n\nA [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) expression can also have the form\n\n> > ```\n(lambda rest-id\n> > body ...+ )\n```"} {"text": "# 3.2 Numbers\nThat is, a lambda expression can have a single rest-id that is not surrounded by parentheses. The resulting function accepts any number of arguments, and the arguments are put into a list bound to rest-id.\nExamples:\n> ```racket\n> > ( ( lambda x x ) 1 2 3 )\n> '(1 2 3)\n> > ( ( lambda x x ) )\n> '()\n> > ( ( lambda x ( car x ) ) 1 2 3 )\n> 1\n> ```\nFunctions with a rest-id often use apply to call another function that accepts any number of arguments.\n> > > \"+\"The apply Function describes apply.\nExamples:\n> ```racket\n> ( define max-mag ( lambda nums ( apply max ( map magnitude nums ) ) ) )\n> > ( max 1 -2 0 )\n> 1\n> > ( max-mag 1 -2 0 )\n> 2\n> ```\nThe lambda form also supports required arguments combined with a rest-id:\n> > ```\n(lambda (arg-id ...+ . rest-id)\n> > body ...+ )```\nThe result of this form is a function that requires at least as many arguments as arg-ids, and also accepts any number of additional arguments.\nExamples:\n> ```racket\n> ( define max-mag ( lambda ( num . nums ) ( apply max ( map magnitude ( cons num nums ) ) ) ) )\n> > ( max-mag 1 -2 0 )\n> 2\n> > ( max-mag )\n> max-mag: arity mismatch;\n> the expected number of arguments does not match the given\n> number\n> expected: at least 1\n> given: 0\n> ```\nA rest-id variable is sometimes called a rest argument, because it accepts the “rest” of the function arguments. A function with a rest argument is sometimes called a variadic function, with elements in the rest argument called variadic arguments."} {"text": "#### 4.4.2 Declaring Optional Arguments\nInstead of just an identifier, an argument (other than a rest argument) in a [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) form can be specified with an identifier and a default value:\n> > ```\n(lambda gen-formals\n> > body ...+ )\ngen-formals   =   (arg ...)\n    |   rest-id\n    |   (arg ...+ . rest-id)\narg   =   arg-id\n    |   [arg-id default-expr]\n```\nAn argument of the form \\[arg-id default-expr\\] is optional. When the argument is not supplied in an application, default-expr produces the default value. The default-expr can refer to any preceding arg-id, and every following arg-id must have a default as well.\n\nExamples:\n\n> ```racket\n> ( define greet ( lambda ( given [ surname \"Smith\" ] ) ( string-append \"Hello, \" given \" \" surname ) ) )\n> > ( greet \"John\" )\n> \"Hello, John Smith\"\n> > ( greet \"John\" \"Doe\" )\n> \"Hello, John Doe\"\n> ```\n\n> ```\n(define greet\n> ( lambda ( given [ surname ( if ( equal? given \"John\" )\n> \"Doe\"\n> \"Smith\" ) ] )\n> ( string-append \"Hello, \" given \" \" surname ) ) )\n \n> ( greet \"John\" )\n> \"Hello, John Doe\"\n> > ( greet \"Adam\" )\n> \"Hello, Adam Smith\"```\n\n\n#### 4.4.3 Declaring Keyword Arguments\n\nA [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) form can declare an argument to be passed by keyword, instead of position. Keyword arguments can be mixed with by-position arguments, and default-value expressions can be supplied for either kind of argument:\n\n> > > \"+\"[Keyword Arguments](application.html#%28part._keyword-args%29) introduces function calls with keywords.\n\n> > ```\n(lambda gen-formals\n> > body ...+ )\n \ngen-formals   =   (arg ...)\n    |   rest-id\n    |   (arg ...+ . rest-id)\n         \narg   =   arg-id\n    |   [arg-id default-expr]\n    |   arg-keyword arg-id\n    |   arg-keyword [arg-id default-expr]\n```"} {"text": "# 3.2 Numbers\nAn argument specified as arg-keyword arg-id is supplied by an application using the same arg-keyword. The position of the keyword–identifier pair in the argument list does not matter for matching with arguments in an application, because it will be matched to an argument value by keyword instead of by position.\n>
( define greet\n> ( lambda ( given #:last surname )\n> ( string-append \"Hello, \" given \" \" surname ) ) )

 

> ( greet \"John\" #:last \"Smith\" )\n> \"Hello, John Smith\"\n> > ( greet #:last \"Doe\" \"John\" )\n> \"Hello, John Doe\"
\nAn arg-keyword \\[arg-id default-expr\\] argument specifies a keyword-based argument with a default value.\nExamples:\n> ```racket\n> ( define greet ( lambda ( #:hi [ hi \"Hello\" ] given #:last [ surname \"Smith\" ] ) ( string-append hi \", \" given \" \" surname ) ) )\n> > ( greet \"John\" )\n> \"Hello, John Smith\"\n> > ( greet \"Karl\" #:last \"Marx\" )\n> \"Hello, Karl Marx\"\n> > ( greet \"John\" #:hi \"Howdy\" )\n> \"Howdy, John Smith\"\n> > ( greet \"Karl\" #:last \"Marx\" #:hi \"Guten Tag\" )\n> \"Guten Tag, Karl Marx\"\n> ```"} {"text": "# 3.2 Numbers\nThe lambda form does not directly support the creation of a function that accepts “rest” keywords. To construct a function that accepts all keyword arguments, use make-keyword-procedure. The function supplied to make-keyword-procedure receives keyword arguments through parallel lists in the first two (by-position) arguments, and then all by-position arguments from an application as the remaining by-position arguments.\n> > > \"+\"The apply Function introduces keyword-apply.\nExamples:\n> ```racket\n> ( define ( trace-wrap f ) ( make-keyword-procedure ( lambda ( kws kw-args . rest ) ( printf \"Called with ~s ~s ~s\\n\" kws kw-args rest ) ( keyword-apply f kws kw-args rest ) ) ) )\n> > ( ( trace-wrap greet ) \"John\" #:hi \"Howdy\" )\n> Called with (#:hi) (\"Howdy\") (\"John\")\n> \"Howdy, John Smith\"\n> ```\n> > > \"+\"Procedure Expressions: lambda and case-lambda in The Racket Reference provides more on function expressions."} {"text": "#### 4.4.4 Arity-Sensitive Functions: case-lambda\nThe case-lambda form creates a function that can have completely different behaviors depending on the number of arguments that are supplied. A case-lambda expression has the form\n> > ```\n(case-lambda\n> > [ formals body ...+ ]\n> > ... )\nformals   =   (arg-id ...)\n    |   rest-id\n    |   (arg-id ...+ . rest-id)```\nwhere each \\[formals body ...+\\] is analogous to ([lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) formals body ...+). Applying a function produced by [case-lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._case-lambda%2529%2529&version=8.18.0.13) is like applying a [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) for the first case that matches the number of given arguments.\nExamples:"} {"text": "# 3.2 Numbers\n> ```racket\n> ( define greet ( case-lambda [ ( name ) ( string-append \"Hello, \" name ) ] [ ( given surname ) ( string-append \"Hello, \" given \" \" surname ) ] ) )\n> > ( greet \"John\" )\n> \"Hello, John\"\n> > ( greet \"John\" \"Smith\" )\n> \"Hello, John Smith\"\n> > ( greet )\n> greet: arity mismatch;\n> the expected number of arguments does not match the given\n> number\n> given: 0\n> ```\nA [case-lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._case-lambda%2529%2529&version=8.18.0.13) function cannot directly support optional or keyword arguments.\n------------------------------------------------------------------------"} {"text": "# 4.5 Definitions: define"} {"text": "### 4.5 Definitions: [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13)\nA basic definition has the form\n> > | |\n> > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) id expr) |\nin which case id is bound to the result of expr.\nExamples:\n> ```racket\n> ( define salutation ( list-ref ' ( \"Hi\" \"Hello\" ) ( random 2 ) ) )\n> > salutation\n> \"Hi\"\n> ```"} {"text": "#### 4.5.1 Function Shorthand\nThe [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) form also supports a shorthand for function definitions:\n> > | |\n> > |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) (id arg ...) body ...+) |\nwhich is a shorthand for"} {"text": "### 4.5 Definitions: [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13)\n> ([define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) id ([lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) (arg [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13)) body ...+))\nExamples:\n> ```racket\n> ( define ( greet name ) ( string-append salutation \", \" name ) )\n> > ( greet \"John\" )\n> \"Hi, John\"\n> ```\n> ```\n(define (greet first [surname \"Smith\"] #:hi [hi salutation])\n> ( string-append hi \", \" first \" \" surname ) )\n> ( greet \"John\" )\n> \"Hi, John Smith\"\n> > ( greet \"John\" #:hi \"Hey\" )\n> \"Hey, John Smith\"\n> > ( greet \"John\" \"Doe\" )\n> \"Hi, John Doe\""} {"text": "### 4.5 Definitions: [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13)\n```\nThe function shorthand via define also supports a rest argument (i.e., a final argument to collect extra arguments in a list):\n\n> > | |\n> > |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | (define (id arg ... . rest-id) body ...+) |\n\nwhich is a shorthand\n\n> (define id (lambda (arg ... . rest-id) body ...+))\n\nExamples:\n\n> ```racket\n> ( define ( avg . l ) ( / ( apply + l ) ( length l ) ) )\n> > ( avg 1 2 3 )\n> 2\n> ```\n\n#### 4.5.2 Curried Function Shorthand\n\nConsider the following make-add-suffix function that takes a string and returns another function that takes a string:\n\n>
( define make-add-suffix\n> ( lambda ( s2 )\n> ( lambda ( s ) ( string-append s s2 ) ) ) )

 

\n\nAlthough it’s not common, the result of make-add-suffix could be called directly, like this:\n\n> ```racket\n> > ( ( make-add-suffix \"!\" ) \"hello\" )\n> \"hello!\"\n> ```\n\nIn a sense, make-add-suffix is a function that takes two arguments, but it takes them one at a time. A function that takes some of its arguments and returns a function to consume more is sometimes called a curried function.\n\nUsing the function-shorthand form of define, make-add-suffix can be written equivalently as\n\n> ```racket\n> ( define ( make-add-suffix s2 )\n> ( lambda ( s ) ( string-append s s2 ) ) )\n> ```\n\nThis shorthand reflects the shape of the function call (make-add-suffix \"!\"). The define form further supports a shorthand for defining curried functions that reflects nested function calls:\n\n>
( define ( ( make-add-suffix s2 ) s )\n> ( string-append s s2 ) )

 

> ( ( make-add-suffix \"!\" ) \"hello\" )\n> \"hello!\"
\n\n>
( define louder ( make-add-suffix \"!\" ) )\n> ( define less-sure ( make-add-suffix \"?\" ) )

 

> ( less-sure \"really\" )\n> \"really?\"\n> > ( louder \"really\" )\n> \"really!\"
\n\nThe full syntax of the function shorthand for define is as follows:\n\n> >
(define (head args) body ...+)
 
head = id
  | (head args)
     
args = arg ...
  | arg ... . rest-id
\n\nThe expansion of this shorthand has one nested lambda form for each head in the definition, where the innermost head corresponds to the outermost lambda.\n\n#### 4.5.3 Multiple Values and define-values\n\nA Racket expression normally produces a single result, but some expressions can produce multiple results. For example, quotient and remainder each produce a single value, but quotient/remainder produces the same two values at once:\n\n> ```racket\n> > ( quotient 13 3 )\n> 4\n> > ( remainder 13 3 )\n> 1\n> > ( quotient/remainder 13 3 )\n> 4 1\n> ```\n\nAs shown above, the REPL prints each result value on its own line.\n\nMultiple-valued functions can be implemented in terms of the values function, which takes any number of values and returns them as the results:\n\n> ```racket\n> > ( values 1 2 3 )\n> 1 2 3\n> ```\n\n> ```\n(define (split-name name)\n> ( let ( [ parts ( regexp-split \" \" name ) ] )\n> ( if ( = ( length parts ) 2 )\n> ( values ( list-ref parts 0 ) ( list-ref parts 1 ) )\n> ( error \"not a name\" ) ) ) )\n \n> ( split-name \"Adam Smith\" )\n> \"Adam\" \"Smith\"```\n\n\nThe [define-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._define-values%2529%2529&version=8.18.0.13) form binds multiple identifiers at once to multiple results produced from a single expression:\n\n> > | |\n> > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([define-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._define-values%2529%2529&version=8.18.0.13) (id ...) expr) |\n\nThe number of results produced by the expr must match the number of ids.\n\nExamples:\n\n> ```racket\n> ( define-values ( given surname ) ( split-name \"Adam Smith\" ) )\n> > given\n> \"Adam\"\n> > surname\n> \"Smith\"\n> ```\n\nA [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) form (that is not a function shorthand) is equivalent to a [define-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._define-values%2529%2529&version=8.18.0.13) form with a single id.\n\n> > > \"+\"[Definitions: define, define-syntax, ...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on definitions.\n\n#### 4.5.4 Internal Definitions\n\nWhen the grammar for a syntactic form specifies body, then the corresponding form can be either a definition or an expression. A definition as a body is an internal definition.\n\nExpressions and internal definitions in a body sequence can be mixed, as long as the last body is an expression.\n\nFor example, the syntax of [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) is\n\n> > ```\n(lambda gen-formals\n> > body ...+ )\n```"} {"text": "### 4.5 Definitions: [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13)\nso the following are valid instances of the grammar:\n> ```racket\n> ( lambda ( f ) ; no definitions\n> ( printf \"running\\n\" )\n> ( f 0 ) )\n> ( lambda ( f ) ; one definition\n> ( define ( log-it what )\n> ( printf \"~a\\n\" what ) )\n> ( log-it \"running\" )\n> ( f 0 )\n> ( log-it \"done\" ) )\n> ( lambda ( f n ) ; two definitions\n> ( define ( call n )\n> ( if ( zero? n )\n> ( log-it \"done\" )\n> ( begin\n> ( log-it \"running\" )\n> ( f n )\n> ( call ( - n 1 ) ) ) ) )\n> ( define ( log-it what )\n> ( printf \"~a\\n\" what ) )\n> ( call n ) )\n> ```\nInternal definitions in a particular body sequence are mutually recursive; that is, any definition can refer to any other definition—as long as the reference isn’t actually evaluated before its definition takes place. If a definition is referenced too early, an error occurs.\nExamples:\n> ```racket\n> ( define ( weird ) ( define x x ) x )\n> > ( weird )\n> x: undefined;\n> cannot use before initialization\n> ```\nA sequence of internal definitions using just define is easily translated to an equivalent letrec form (as introduced in the next section). However, other definition forms can appear as a body, including define-values, struct (see Programmer-Defined Datatypes) or define-syntax (see Macros)."} {"text": "### 4.5 Definitions: [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13)\n> > > \"+\"Internal Definitions in The Racket Reference documents the fine points of internal definitions.\n------------------------------------------------------------------------"} {"text": "# 4.6 Local Binding"} {"text": "### 4.6 Local Binding\nAlthough internal defines can be used for local binding, Racket provides three forms that give the programmer more control over bindings: let, let*, and letrec."} {"text": "#### 4.6.1 Parallel Binding: let\n> > > \"+\"Local Binding: let, let*, letrec, ... in The Racket Reference also documents let.\nA let form binds a set of identifiers, each to the result of some expression, for use in the let body:\n> > | |\n> > |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | (let (\\[id expr\\] ...) body ...+) |\nThe ids are bound “in parallel.” That is, no id is bound in the right-hand side expr for any id, but all are available in the body. The ids must be different from each other.\nExamples:\n> ```racket\n> > ( let ( [ me \"Bob\" ] ) me )\n> \"Bob\"\n> > ( let ( [ me \"Bob\" ] [ myself \"Robert\" ] [ I \"Bobby\" ] ) ( list me myself I ) )\n> '(\"Bob\" \"Robert\" \"Bobby\")\n> > ( let ( [ me \"Bob\" ] [ me \"Robert\" ] ) me )\n> eval:3:0: let: duplicate identifier\n> at: me\n> in: (let ((me \"Bob\") (me \"Robert\")) me)\n> ```\nThe fact that an id’s expr does not see its own binding is often useful for wrappers that must refer back to the old value:\n> ```racket\n> > ( let ( [ + ( lambda ( x y ) ( if ( string? x ) ( string-append x y ) ( + x y ) ) ) ] ) ; use original + ( list ( + 1 2 ) ( + \"see\" \"saw\" ) ) )\n> '(3 \"seesaw\")\n> ```\nOccasionally, the parallel nature of let bindings is convenient for swapping or rearranging a set of bindings:"} {"text": "# 4.6 Local Binding\n> ```racket\n> > ( let ( [ me \"Tarzan\" ] [ you \"Jane\" ] ) ( let ( [ me you ] [ you me ] ) ( list me you ) ) )\n> '(\"Jane\" \"Tarzan\")\n> ```\nThe characterization of let bindings as “parallel” is not meant to imply concurrent evaluation. The exprs are evaluated in order, even though the bindings are delayed until all exprs are evaluated."} {"text": "#### 4.6.2 Sequential Binding: let*\n> > > \"+\"Local Binding: let, let*, letrec, ... in The Racket Reference also documents let*.\nThe syntax of let* is the same as let:\n> > | |\n> > |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | (let* (\\[id expr\\] ...) body ...+) |\nThe difference is that each id is available for use in later exprs, as well as in the body. Furthermore, the ids need not be distinct, and the most recent binding is the visible one.\nExamples:\n> ```racket\n> > ( let* ( [ x ( list \"Burroughs\" ) ] [ y ( cons \"Rice\" x ) ] [ z ( cons \"Edgar\" y ) ] ) ( list x y z ) )\n> '((\"Burroughs\") (\"Rice\" \"Burroughs\") (\"Edgar\" \"Rice\" \"Burroughs\"))\n> > ( let* ( [ name ( list \"Burroughs\" ) ] [ name ( cons \"Rice\" name ) ] [ name ( cons \"Edgar\" name ) ] ) name )\n> '(\"Edgar\" \"Rice\" \"Burroughs\")\n> ```\nIn other words, a let* form is equivalent to nested let forms, each with a single binding:\n> ```racket\n> > ( let ( [ name ( list \"Burroughs\" ) ] ) ( let ( [ name ( cons \"Rice\" name ) ] ) ( let ( [ name ( cons \"Edgar\" name ) ] ) name ) ) )\n> '(\"Edgar\" \"Rice\" \"Burroughs\")\n> ```"} {"text": "#### 4.6.3 Recursive Binding: letrec\n> > > \"+\"Local Binding: let, let*, letrec, ... in The Racket Reference also documents letrec.\nThe syntax of letrec is also the same as let:\n> > | |\n> > |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | (letrec (\\[id expr\\] ...) body ...+) |\nWhile let makes its bindings available only in the bodys, and let* makes its bindings available to any later binding expr, letrec makes its bindings available to all other exprs—even earlier ones. In other words, letrec bindings are recursive.\nThe exprs in a letrec form are most often lambda forms for recursive and mutually recursive functions:\n> ```racket\n> > ( letrec ( [ swing ( lambda ( t ) ( if ( eq? ( car t ) ' tarzan ) ( cons ' vine ( cons ' tarzan ( cddr t ) ) ) ( cons ( car t ) ( swing ( cdr t ) ) ) ) ) ] ) ( swing ' ( vine tarzan vine vine ) ) )\n> '(vine vine tarzan vine)\n> ```"} {"text": "# 4.6 Local Binding\n> ```racket\n> > ( letrec ( [ tarzan-near-top-of-tree? ( lambda ( name path depth ) ( or ( equal? name \"tarzan\" ) ( and ( directory-exists? path ) ( tarzan-in-directory? path depth ) ) ) ) ] [ tarzan-in-directory? ( lambda ( dir depth ) ( cond [ ( zero? depth ) #f ] [ else ( ormap ( λ ( elem ) ( tarzan-near-top-of-tree? ( path-element → string elem ) ( build-path dir elem ) ( - depth 1 ) ) ) ( directory-list dir ) ) ] ) ) ] ) ( tarzan-near-top-of-tree? \"tmp\" ( find-system-path ' temp-dir ) 4 ) )\n> #f\n> ```\nWhile the exprs of a letrec form are typically lambda expressions, they can be any expression. The expressions are evaluated in order, and after each value is obtained, it is immediately associated with its corresponding id. If an id is referenced before its value is ready, an error is raised, just as for internal definitions.\n> ```racket\n> > ( letrec ( [ quicksand quicksand ] ) quicksand )\n> quicksand: undefined;\n> cannot use before initialization\n> ```"} {"text": "#### 4.6.4 Named let\nA named let is an iteration and recursion form. It uses the same syntactic keyword let as for local binding, but an identifier after the let (instead of an immediate open parenthesis) triggers a different parsing.\n> > ```\n(let proc-id ([arg-id init-expr] ...)\n> > body ...+ )```\nA named [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) form is equivalent to\n> ```racket\n> ( ( letrec ( [ proc-id ( lambda ( arg-id ... )\n> body ...+ ) ] )\n> proc-id )\n> init-expr ... )\n> ```\nThat is, a named [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) binds a function identifier that is visible only in the function’s body, and it implicitly calls the function with the values of some initial expressions.\nExamples:\n> ```racket\n> ( define ( duplicate pos lst ) ( let dup ( [ i 0 ] [ lst lst ] ) ( cond [ ( = i pos ) ( cons ( car lst ) lst ) ] [ else ( cons ( car lst ) ( dup ( + i 1 ) ( cdr lst ) ) ) ] ) ) )\n> > ( duplicate 1 ( list \"apple\" \"cheese burger!\" \"banana\" ) )\n> '(\"apple\" \"cheese burger!\" \"cheese burger!\" \"banana\")\n> ```"} {"text": "#### 4.6.5 Multiple Values: [let-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._let-values%2529%2529&version=8.18.0.13), [let*-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%252A-values%2529%2529&version=8.18.0.13), [letrec-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._letrec-values%2529%2529&version=8.18.0.13)\n> > > \"+\"[Local Binding: let, let*, letrec, ...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) also documents multiple-value binding forms."} {"text": "# 4.6 Local Binding\nIn the same way that [define-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._define-values%2529%2529&version=8.18.0.13) binds multiple results in a definition (see [Multiple Values and define-values](define.html#%28part._multiple-values%29)), [let-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._let-values%2529%2529&version=8.18.0.13), [let*-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%252A-values%2529%2529&version=8.18.0.13), and [letrec-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._letrec-values%2529%2529&version=8.18.0.13) bind multiple results locally.\n> > ```\n(let-values ([(id ...) expr] ...)\n> > body ...+ )\n```\n> > ```\n(let*-values ([(id ...) expr] ...)\n> > body ...+ )```\n\n\n> > ```\n(letrec-values ([(id ...) expr] ...)\n> > body ...+ )\n```"} {"text": "# 4.6 Local Binding\nEach expr must produce as many values as corresponding ids. The binding rules are the same for the forms without -values forms: the ids of let-values are bound only in the bodys, the ids of let*-valuess are bound in exprs of later clauses, and the ids of letrec-values are bound for all exprs.\nExample:\n> ```racket\n> > ( let-values ( [ ( q r ) ( quotient/remainder 14 3 ) ] ) ( list q r ) )\n> '(4 2)\n> ```\n------------------------------------------------------------------------"} {"text": "# 4.7 Conditionals"} {"text": "### 4.7 Conditionals\nMost functions used for branching, such as < and string?, produce either #t or #f. Racket’s branching forms, however, treat any value other than #f as true. We say a true value to mean any value other than #f.\nThis convention for “true value” meshes well with protocols where #f can serve as failure or to indicate that an optional value is not supplied. (Beware of overusing this trick, and remember that an exception is usually a better mechanism to report failure.)\nFor example, the member function serves double duty; it can be used to find the tail of a list that starts with a particular item, or it can be used to simply check whether an item is present in a list:\n> ```racket\n> > ( member \"Groucho\" ' ( \"Harpo\" \"Zeppo\" ) )\n> #f\n> > ( member \"Groucho\" ' ( \"Harpo\" \"Groucho\" \"Zeppo\" ) )\n> '(\"Groucho\" \"Zeppo\")\n> > ( if ( member \"Groucho\" ' ( \"Harpo\" \"Zeppo\" ) ) ' yep ' nope )\n> 'nope\n> > ( if ( member \"Groucho\" ' ( \"Harpo\" \"Groucho\" \"Zeppo\" ) ) ' yep ' nope )\n> 'yep\n> ```"} {"text": "#### 4.7.1 Simple Branching: if\n> > > \"+\"Conditionals: if, cond, and, and or in The Racket Reference also documents if.\nIn an if form,\n> > | |\n> > |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | (if test-expr then-expr else-expr) |\nthe test-expr is always evaluated. If it produces any value other than #f, then then-expr is evaluated. Otherwise, else-expr is evaluated.\nAn if form must have both a then-expr and an else-expr; the latter is not optional. To perform (or skip) side-effects based on a test-expr, use when or unless, which we describe later in Sequencing."} {"text": "#### 4.7.2 Combining Tests: and and or\n> > > \"+\"Conditionals: if, cond, and, and or in The Racket Reference also documents and and or.\nRacket’s and and or are syntactic forms, rather than functions. Unlike a function, the and and or forms can skip evaluation of later expressions if an earlier one determines the answer.\n> > | |\n> > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | (and expr ...) |\nAn and form produces #f if any of its exprs produces #f. Otherwise, it produces the value of its last expr. As a special case, (and) produces #t.\n> > | |\n> > |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | (or expr ...) |\nThe or form produces #f if all of its exprs produce #f. Otherwise, it produces the first non-#f value from its exprs. As a special case, (or) produces #f.\nExamples:\n> ```racket\n> > ( define ( got-milk? lst ) ( and ( not ( null? lst ) ) ( or ( eq? ' milk ( car lst ) ) ( got-milk? ( cdr lst ) ) ) ) ) ; recurs only if needed\n> > ( got-milk? ' ( apple banana ) )\n> #f\n> > ( got-milk? ' ( apple milk banana ) )\n> #t\n> ```"} {"text": "# 4.7 Conditionals\nIf evaluation reaches the last expr of an and or or form, then the expr’s value directly determines the and or or result. Therefore, the last expr is in tail position, which means that the above got-milk? function runs in constant space.\n> > > \"+\"Tail Recursion introduces tail calls and tail positions."} {"text": "#### 4.7.3 Chaining Tests: cond\nThe cond form chains a series of tests to select a result expression. To a first approximation, the syntax of cond is as follows:\n> > > \"+\"Conditionals: if, cond, and, and or in The Racket Reference also documents cond.\n> > ```\n(cond [test-expr body ...+]\n> > ... )```\nEach test-expr is evaluated in order. If it produces #f, the corresponding bodys are ignored, and evaluation proceeds to the next test-expr. As soon as a test-expr produces a true value, the associated bodys are evaluated to produce the result for the [cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._cond%2529%2529&version=8.18.0.13) form, and no further test-exprs are evaluated."} {"text": "# 4.7 Conditionals\nThe last test-expr in a [cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._cond%2529%2529&version=8.18.0.13) can be replaced by [else](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._else%2529%2529&version=8.18.0.13). In terms of evaluation, [else](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._else%2529%2529&version=8.18.0.13) serves as a synonym for #t, but it clarifies that the last clause is meant to catch all remaining cases. If [else](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._else%2529%2529&version=8.18.0.13) is not used, then it is possible that no test-exprs produce a true value; in that case, the result of the [cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=if.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._cond%2529%2529&version=8.18.0.13) expression is [#](void_undefined.html).\nExamples:"} {"text": "# 4.7 Conditionals\n> ```racket\n> > ( cond [ ( = 2 3 ) ( error \"wrong!\" ) ] [ ( = 2 2 ) ' ok ] )\n> 'ok\n> > ( cond [ ( = 2 3 ) ( error \"wrong!\" ) ] )\n> > ( cond [ ( = 2 3 ) ( error \"wrong!\" ) ] [ else ' ok ] )\n> 'ok\n> ```\n> ```\n(define (got-milk? lst)\n> ( cond\n> [ ( null? lst ) #f ]\n> [ ( eq? ' milk ( car lst ) ) #t ]\n> [ else ( got-milk? ( cdr lst ) ) ] ) )\n> ( got-milk? ' ( apple banana ) )\n> #f\n> > ( got-milk? ' ( apple milk banana ) )\n> #t\n```\n(make-running-total)\t→```\n\n\n#### 4.9.1 Guidelines for Using Assignment\n\nAlthough using [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) is sometimes appropriate, Racket style generally discourages the use of [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13). The following guidelines may help explain when using [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) is appropriate.\n\n- As in any modern language, assigning to a shared identifier is no substitute for passing an argument to a procedure or getting its result.\n\n \n\n Really awful example:\n\n \n\n \n\n >
( define name "unknown" )\n    > ( define result "unknown" )\n    > ( define ( greet )\n    > ( set! result ( string-append "Hello, " name ) ) )

 

> ( set! name "John" )\n    > > ( greet )\n    > > result\n    > "Hello, John"
\n\n \n\n \n\n Ok example:\n\n \n\n \n\n >
( define ( greet name )\n    > ( string-append "Hello, " name ) )

 

> ( greet "John" )\n    > "Hello, John"\n    > > ( greet "Anna" )\n    > "Hello, Anna"
\n\n \n\n- A sequence of assignments to a local variable is far inferior to nested bindings.\n\n \n\n Bad example:\n\n \n\n \n\n > ```racket\n > > ( let ( [ tree 0 ] ) ( set! tree ( list tree 1 tree ) ) ( set! tree ( list tree 2 tree ) ) ( set! tree ( list tree 3 tree ) ) tree )\n > '(((0 1 0) 2 (0 1 0)) 3 ((0 1 0) 2 (0 1 0)))\n > ```\n\n \n\n \n\n Ok example:\n\n \n\n \n\n > ```racket\n > > ( let* ( [ tree 0 ] [ tree ( list tree 1 tree ) ] [ tree ( list tree 2 tree ) ] [ tree ( list tree 3 tree ) ] ) tree )\n > '(((0 1 0) 2 (0 1 0)) 3 ((0 1 0) 2 (0 1 0)))\n > ```\n\n \n\n- Using assignment to accumulate results from an iteration is bad style. Accumulating through a loop argument is better.\n\n \n\n Somewhat bad example:\n\n \n\n \n\n > ```\n(define (sum lst)\n> ( let ( [ s 0 ] )\n> ( for-each ( lambda ( i ) ( set! s ( + i s ) ) )\n> lst )\n> s ) )\n \n> ( sum ' ( 1 2 3 ) )\n> 6\n```"} {"text": "# 4.7 Conditionals\nOk example:\n> ```\n(define (sum lst)\n> ( let loop ( [ lst lst ] [ s 0 ] )\n> ( if ( null? lst )\n> s\n> ( loop ( cdr lst ) ( + s ( car lst ) ) ) ) ) )\n> ( sum ' ( 1 2 3 ) )\n> 6```\n Better (use an existing function) example:\n >
( define ( sum lst )\n    > ( apply + lst ) )

 

> ( sum ' ( 1 2 3 ) )\n    > 6
\n Good (a general approach) example:\n > ```\n(define (sum lst)\n> ( for/fold ( [ s 0 ] )\n> ( [ i ( in-list lst ) ] )\n> ( + s i ) ) )\n> ( sum ' ( 1 2 3 ) )\n> 6"} {"text": "# 4.7 Conditionals\n```\n- For cases where stateful objects are necessary or appropriate, then implementing the object’s state with set! is fine.\n\n\n\nOk example:\n\n\n\n\n\n> ```\n(define next-number!\n> ( let ( [ n 0 ] )\n> ( lambda ( )\n> ( set! n ( add1 n ) )\n> n ) ) )\n \n> ( next-number! )\n> 1\n> > ( next-number! )\n> 2\n> > ( next-number! )\n> 3```\n\n\n \n\nAll else being equal, a program that uses no assignments or mutation is always preferable to one that uses assignments or mutation. While side effects are to be avoided, however, they should be used if the resulting code is significantly more readable or if it implements a significantly better algorithm.\n\nThe use of mutable values, such as vectors and hash tables, raises fewer suspicions about the style of a program than using [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) directly. Nevertheless, simply replacing [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13)s in a program with [vector-set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=vectors.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._vector-set%2521%2529%2529&version=8.18.0.13)s obviously does not improve the style of the program.\n\n#### 4.9.2 Multiple Values: [set!-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._set%2521-values%2529%2529&version=8.18.0.13)\n\n> > > \"+\"[Assignment: set! and set!-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) also documents [set!-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._set%2521-values%2529%2529&version=8.18.0.13).\n\nThe [set!-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._set%2521-values%2529%2529&version=8.18.0.13) form assigns to multiple variables at once, given an expression that produces an appropriate number of values:\n\n> > | |\n> > |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([set!-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._set%2521-values%2529%2529&version=8.18.0.13) (id ...) expr) |\n\nThis form is equivalent to using [let-values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._let-values%2529%2529&version=8.18.0.13) to receive multiple results from expr, and then assigning the results individually to the ids using [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13).\n\nExamples:\n\n> ```racket\n> ( define game ( let ( [ w 0 ] [ l 0 ] ) ( lambda ( win? ) ( if win? ( set! w ( + w 1 ) ) ( set! l ( + l 1 ) ) ) ( begin0 ( values w l ) ; swap sides... ( set!-values ( w l ) ( values l w ) ) ) ) ) )\n> > ( game #t )\n> 1 0\n> > ( game #t )\n> 1 1\n> > ( game #f )\n> 1 2\n> ```\n\n------------------------------------------------------------------------\n\n# 4.10 Quoting: quote and '\n\n### 4.10 Quoting: [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) and ’\n\n> > > \"+\"[Literals: quote and #%datum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) also documents [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13).\n\nThe [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) form produces a constant:\n\n> > | |\n> > |---------------|\n> > | (quote datum) |\n\nThe syntax of a datum is technically specified as anything that the [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13) function parses as a single element. The value of the [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) form is the same value that [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13) would produce given datum.\n\nThe datum can be a symbol, a boolean, a number, a (character or byte) string, a character, a keyword, an empty list, a pair (or list) containing more such values, a vector containing more such values, a hash table containing more such values, or a box containing another such value.\n\nExamples:\n\n> ```racket\n> > ( quote apple )\n> 'apple\n> > ( quote #t )\n> #t\n> > ( quote 42 )\n> 42\n> > ( quote \"hello\" )\n> \"hello\"\n> > ( quote ( ) )\n> '()\n> > ( quote ( ( 1 2 3 ) # ( \"z\" x ) . the-end ) )\n> '((1 2 3) #(\"z\" x) . the-end)\n> > ( quote ( 1 2 . ( 3 ) ) )\n> '(1 2 3)\n> ```\n\nAs the last example above shows, the datum does not have to match the normalized printed form of a value. A datum cannot be a printed representation that starts with #\\<, so it cannot be [#](void_undefined.html), [#](void_undefined.html), or a procedure.\n\nThe [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) form is rarely used for a datum that is a boolean, number, or string by itself, since the printed forms of those values can already be used as constants. The [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) form is more typically used for symbols and lists, which have other meanings (identifiers, function calls, etc.) when not quoted.\n\nAn expression\n\n> > | |\n> > |--------|\n> > | 'datum |\n\nis a shorthand for\n\n> (quote datum)\n\nand this shorthand is almost always used instead of [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13). The shorthand applies even within the datum, so it can produce a list containing [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13).\n\n> > > \"+\"[Reading Quotes](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=reader.html%23%2528part._parse-quote%2529&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on the ' shorthand.\n\nExamples:\n\n> ```racket\n> > ' apple\n> 'apple\n> > ' \"hello\"\n> \"hello\"\n> > ' ( 1 2 3 )\n> '(1 2 3)\n> > ( display ' ( you can ' me ) )\n> (you can (quote me))\n> ```\n\n------------------------------------------------------------------------\n\n# 4.11 Quasiquoting: quasiquote and lsquo\n\n### 4.11 Quasiquoting: [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) and ‘\n\n> > > \"+\"[Quasiquoting: quasiquote, unquote, and unquote-splicing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) also documents [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13).\n\nThe [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) form is similar to [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13):\n\n> > | |\n> > |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) datum) |\n\nHowever, for each ([unquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote%2529%2529&version=8.18.0.13) expr) that appears within the datum, the expr is evaluated to produce a value that takes the place of the [unquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote%2529%2529&version=8.18.0.13) sub-form.\n\nExample:\n\n> ```racket\n> > ( quasiquote ( 1 2 ( unquote ( + 1 2 ) ) ( unquote ( - 5 1 ) ) ) )\n> '(1 2 3 4)\n> ```\n\nThis form can be used to write functions that build lists according to certain patterns.\n\nExamples:\n\n> ```racket\n> > ( define ( deep n ) ( cond [ ( zero? n ) 0 ] [ else ( quasiquote ( ( unquote n ) ( unquote ( deep ( - n 1 ) ) ) ) ) ] ) )\n> > ( deep 8 )\n> '(8 (7 (6 (5 (4 (3 (2 (1 0))))))))\n> ```\n\nOr even to cheaply construct expressions programmatically. (Of course, 9 times out of 10, you should be using a [macro](macros.html) to do this (the 10th time being when you’re working through a textbook like [PLAI](https://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/)).)\n\nExamples:\n\n> ```racket\n> > ( define ( build-exp n ) ( add-lets n ( make-sum n ) ) )\n> > ( define ( add-lets n body ) ( cond [ ( zero? n ) body ] [ else ( quasiquote ( let ( [ ( unquote ( n->var n ) ) ( unquote n ) ] ) ( unquote ( add-lets ( - n 1 ) body ) ) ) ) ] ) )\n> > ( define ( make-sum n ) ( cond [ ( = n 1 ) ( n->var 1 ) ] [ else ( quasiquote ( + ( unquote ( n->var n ) ) ( unquote ( make-sum ( - n 1 ) ) ) ) ) ] ) )\n> > ( define ( n->var n ) ( string->symbol ( format \"x~a\" n ) ) )\n> > ( build-exp 3 )\n> '(let ((x3 3)) (let ((x2 2)) (let ((x1 1)) (+ x3 (+ x2 x1)))))\n> ```\n\nThe [unquote-splicing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote-splicing%2529%2529&version=8.18.0.13) form is similar to [unquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote%2529%2529&version=8.18.0.13), but its expr must produce a list, and the [unquote-splicing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote-splicing%2529%2529&version=8.18.0.13) form must appear in a context that produces either a list or a vector. As the name suggests, the resulting list is spliced into the context of its use.\n\nExample:\n\n> ```racket\n> > ( quasiquote ( 1 2 ( unquote-splicing ( list ( + 1 2 ) ( - 5 1 ) ) ) 5 ) )\n> '(1 2 3 4 5)\n> ```\n\nUsing splicing we can revise the construction of our example expressions above to have just a single [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) expression and a single [+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) expression.\n\nExamples:\n\n> ```racket\n> > ( define ( build-exp n ) ( add-lets n ( quasiquote ( + ( unquote-splicing ( build-list n ( λ ( x ) ( n->var ( + x 1 ) ) ) ) ) ) ) ) )\n> > ( define ( add-lets n body ) ( quasiquote ( let ( unquote ( build-list n ( λ ( n ) ( quasiquote [ ( unquote ( n->var ( + n 1 ) ) ) ( unquote ( + n 1 ) ) ] ) ) ) ) ( unquote body ) ) ) )\n> > ( define ( n->var n ) ( string->symbol ( format \"x~a\" n ) ) )\n> > ( build-exp 3 )\n> '(let ((x1 1) (x2 2) (x3 3)) (+ x1 x2 x3))\n> ```\n\nIf a [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) form appears within an enclosing [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) form, then the inner [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) effectively cancels one layer of [unquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote%2529%2529&version=8.18.0.13) and [unquote-splicing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote-splicing%2529%2529&version=8.18.0.13) forms, so that a second [unquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote%2529%2529&version=8.18.0.13) or [unquote-splicing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote-splicing%2529%2529&version=8.18.0.13) is needed.\n\nExamples:\n\n> ```racket\n> > ( quasiquote ( 1 2 ( quasiquote ( unquote ( + 1 2 ) ) ) ) )\n> '(1 2 (quasiquote (unquote (+ 1 2))))\n> > ( quasiquote ( 1 2 ( quasiquote ( unquote ( unquote ( + 1 2 ) ) ) ) ) )\n> '(1 2 (quasiquote (unquote 3)))\n> > ( quasiquote ( 1 2 ( quasiquote ( ( unquote ( + 1 2 ) ) ( unquote ( unquote ( - 5 1 ) ) ) ) ) ) )\n> '(1 2 (quasiquote ((unquote (+ 1 2)) (unquote 4))))\n> ```\n\nThe evaluations above will not actually print as shown. Instead, the shorthand form of [quasiquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._quasiquote%2529%2529&version=8.18.0.13) and [unquote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote%2529%2529&version=8.18.0.13) will be used: \\` (i.e., a backquote) and , (i.e., a comma). The same shorthands can be used in expressions:\n\nExample:\n\n> ```racket\n> > ` ( 1 2 ` ( , ( + 1 2 ) , , ( - 5 1 ) ) )\n> '(1 2 `(,(+ 1 2) ,4))\n> ```\n\nThe shorthand form of [unquote-splicing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quasiquote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._unquote-splicing%2529%2529&version=8.18.0.13) is ,@:\n\nExample:\n\n> ```racket\n> > ` ( 1 2 ,@ ( list ( + 1 2 ) ( - 5 1 ) ) )\n> '(1 2 3 4)\n> ```\n\n------------------------------------------------------------------------\n\n# 4.12 Simple Dispatch: case\n\n### 4.12 Simple Dispatch: [case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=case.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._case%2529%2529&version=8.18.0.13)\n\nThe [case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=case.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._case%2529%2529&version=8.18.0.13) form dispatches to a clause by matching the result of an expression to the values for the clause:\n\n> > ```\n(case expr\n> > [ ( datum ...+ ) body ...+ ]\n> > ... )\n```"} {"text": "# 4.7 Conditionals\n(parameter)\t→```\n> > > The term “parameter” is sometimes used to refer to the arguments of a function, but “parameter” in Racket has the more specific meaning described here.\nFor example, the [error-print-width](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=exns.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._error-print-width%2529%2529&version=8.18.0.13) parameter controls how many characters of a value are printed in an error message:\n> ```racket\n> > ( parameterize ( [ error-print-width 5 ] ) ( car ( expt 10 1024 ) ) )\n> car: contract violation\n> expected: pair?\n> given: 10...\n> > ( parameterize ( [ error-print-width 10 ] ) ( car ( expt 10 1024 ) ) )\n> car: contract violation\n> expected: pair?\n> given: 1000000...\n> ```\nMore generally, parameters implement a kind of dynamic binding. The [make-parameter](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._make-parameter%2529%2529&version=8.18.0.13) function takes any value and returns a new parameter that is initialized to the given value. Applying the parameter as a function returns its current value:\n> ```racket\n> > ( define location ( make-parameter \"here\" ) )\n> > ( location )\n> \"here\"\n> ```"} {"text": "# 4.7 Conditionals\nIn a [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form, each parameter-expr must produce a parameter. During the evaluation of the bodys, each specified parameter is given the result of the corresponding value-expr. When control leaves the [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form—either through a normal return, an exception, or some other escape—the parameter reverts to its earlier value:\n> ```racket\n> > ( parameterize ( [ location \"there\" ] ) ( location ) )\n> \"there\"\n> > ( location )\n> \"here\"\n> > ( parameterize ( [ location \"in a house\" ] ) ( list ( location ) ( parameterize ( [ location \"with a mouse\" ] ) ( location ) ) ( location ) ) )\n> '(\"in a house\" \"with a mouse\" \"in a house\")\n> > ( parameterize ( [ location \"in a box\" ] ) ( car ( location ) ) )\n> car: contract violation\n> expected: pair?\n> given: \"in a box\"\n> > ( location )\n> \"here\"\n> ```"} {"text": "# 4.7 Conditionals\nThe [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form is not a binding form like [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13); each use of location above refers directly to the original definition. A [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form adjusts the value of a parameter during the whole time that the [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) body is evaluated, even for uses of the parameter that are textually outside of the [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) body:"} {"text": "# 4.7 Conditionals\n> ```racket\n> > ( define ( would-you-could-you? ) ( and ( not ( equal? ( location ) \"here\" ) ) ( not ( equal? ( location ) \"there\" ) ) ) )\n> > ( would-you-could-you? )\n> #f\n> > ( parameterize ( [ location \"on a bus\" ] ) ( would-you-could-you? ) )\n> #t\n> ```\nIf a use of a parameter is textually inside the body of a [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) but not evaluated before the [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form produces a value, then the use does not see the value installed by the [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form:\n> ```racket\n> > ( let ( [ get ( parameterize ( [ location \"with a fox\" ] ) ( lambda ( ) ( location ) ) ) ] ) ( get ) )\n> \"here\"\n> ```"} {"text": "# 4.7 Conditionals\nThe current binding of a parameter can be adjusted imperatively by calling the parameter as a function with a value. If a [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) has adjusted the value of the parameter, then directly applying the parameter procedure affects only the value associated with the active [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13):\n> ```racket\n> > ( define ( try-again! where ) ( location where ) )\n> > ( location )\n> \"here\"\n> > ( parameterize ( [ location \"on a train\" ] ) ( list ( location ) ( begin ( try-again! \"in a boat\" ) ( location ) ) ) )\n> '(\"on a train\" \"in a boat\")\n> > ( location )\n> \"here\"\n> ```"} {"text": "# 4.7 Conditionals\nUsing [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) is generally preferable to updating a parameter value imperatively—for much the same reasons that binding a fresh variable with [let](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=let.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fletstx-scheme..rkt%2529._let%2529%2529&version=8.18.0.13) is preferable to using [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) (see [Assignment: set!](set_.html)).\nIt may seem that variables and [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) can solve many of the same problems that parameters solve. For example, lokation could be defined as a string, and [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) could be used to adjust its value:"} {"text": "# 4.7 Conditionals\n> ```racket\n> > ( define lokation \"here\" )\n> > ( define ( would-ya-could-ya? ) ( and ( not ( equal? lokation \"here\" ) ) ( not ( equal? lokation \"there\" ) ) ) )\n> > ( set! lokation \"on a bus\" )\n> > ( would-ya-could-ya? )\n> #t\n> ```\nParameters, however, offer several crucial advantages over [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13):\n- The [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form helps automatically reset the value of a parameter when control escapes due to an exception. Adding exception handlers and other forms to rewind a [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) is relatively tedious."} {"text": "# 4.7 Conditionals\n- Parameters work nicely with tail calls (see [Tail Recursion](Lists__Iteration__and_Recursion.html#%28part._tail-recursion%29)). The last body in a [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form is in [tail position](Lists__Iteration__and_Recursion.html#%28tech._tail._position%29) with respect to the [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form.\n- Parameters work properly with threads (see [Threads](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=threads.html&version=8.18.0.13)). The [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13) form adjusts the value of a parameter only for evaluation in the current thread, which avoids race conditions with other threads.\n------------------------------------------------------------------------"} {"text": "# 5 Programmer-Defined Datatypes"} {"text": "## 5 Programmer-Defined Datatypes\n> > > \"+\"[Structures](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=structures.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) also documents structure types.\nNew datatypes are normally created with the [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) form, which is the topic of this chapter. The class-based object system, which we defer to [Classes and Objects](classes.html), offers an alternate mechanism for creating new datatypes, but even classes and objects are implemented in terms of structure types."} {"text": "### 5.1 Simple Structure Types: [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13)\n> > > \"+\"[Defining Structure Types: struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) also documents [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13).\nTo a first approximation, the syntax of [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) is"} {"text": "### 5.1 Simple Structure Types: [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13)\n> > | |\n> > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) struct-id (field-id ...)) |\nExamples:\n> ([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) posn (x y))"} {"text": "### 5.1 Simple Structure Types: [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13)\nThe [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) form binds struct-id and a number of identifiers that are built from struct-id and the field-ids:\n- struct-id : a constructor function that takes as many arguments as the number of field-ids, and returns an instance of the structure type.\n Example:\n > ```racket\n > > ( posn 1 2 )\n > #\n > ```\n- struct-id? : a predicate function that takes a single argument and returns #t if it is an instance of the structure type, #f otherwise.\n Examples:\n > ```racket\n > > ( posn? 3 )\n > #f\n > > ( posn? ( posn 1 2 ) )\n > #t\n > ```\n- struct-id-field-id : for each field-id, an accessor that extracts the value of the corresponding field from an instance of the structure type.\n Examples:\n > ```racket\n > > ( posn-x ( posn 1 2 ) )\n > 1\n > > ( posn-y ( posn 1 2 ) )\n > 2\n > ```\n- struct:struct-id : a structure type descriptor, which is a value that represents the structure type as a first-class value (with #:super, as discussed later in [More Structure Type Options](#%28part._struct-options%29))."} {"text": "### 5.1 Simple Structure Types: [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13)\nA [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) form places no constraints on the kinds of values that can appear for fields in an instance of the structure type. For example, (posn \"apple\" #f) produces an instance of posn, even though \"apple\" and #f are not valid coordinates for the obvious uses of posn instances. Enforcing constraints on field values, such as requiring them to be numbers, is normally the job of a contract, as discussed later in [Contracts](contracts.html)."} {"text": "### 5.2 Copying and Update\nThe [struct-copy](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=struct-copy.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct-copy%2529%2529&version=8.18.0.13) form clones a structure and optionally updates specified fields in the clone. This process is sometimes called a functional update, because the result is a structure with updated field values. but the original structure is not modified.\n> > | |\n> > |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([struct-copy](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=struct-copy.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct-copy%2529%2529&version=8.18.0.13) struct-id struct-expr \\[field-id expr\\] ...) |"} {"text": "### 5.2 Copying and Update\nThe struct-id that appears after [struct-copy](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=struct-copy.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct-copy%2529%2529&version=8.18.0.13) must be a structure type name bound by [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13). The struct-expr must produce an instance of the structure type. The result is a new instance of the structure type that is like the old one, except that the field indicated by each field-id gets the value of the corresponding expr.\nExamples:\n> ```racket\n> > ( define p1 ( posn 1 2 ) )\n> > ( define p2 ( struct-copy posn p1 [ x 3 ] ) )\n> > ( list ( posn-x p2 ) ( posn-y p2 ) )\n> '(3 2)\n> > ( list ( posn-x p1 ) ( posn-y p1 ) )\n> '(1 2)\n> ```"} {"text": "### 5.3 Structure Subtypes\nAn extended form of [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) can be used to define a structure subtype, which is a structure type that extends an existing structure type:\n> > | |\n> > |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) struct-id super-id (field-id ...)) |"} {"text": "### 5.3 Structure Subtypes\nThe super-id must be a structure type name bound by [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) (i.e., the name that cannot be used directly as an expression).\nExamples:\n> ```racket\n> ( struct posn ( x y ) )\n> ( struct 3d-posn posn ( z ) )\n> ```\nA structure subtype inherits the fields of its supertype, and the subtype constructor accepts the values for the subtype fields after values for the supertype fields. An instance of a structure subtype can be used with the predicate and accessors of the supertype.\nExamples:\n> ```racket\n> > ( define p ( 3d-posn 1 2 3 ) )\n> > p\n> #<3d-posn>\n> > ( posn? p )\n> #t\n> > ( 3d-posn-z p )\n> 3\n> ; a 3d-posn has an x field, but there is no 3d-posn-x selector:\n> > ( 3d-posn-x p )\n> 3d-posn-x: undefined;\n> cannot reference an identifier before its definition\n> in module: top-level\n> ; use the supertype's posn-x selector to access the x field:\n> > ( posn-x p )\n> 1\n> ```"} {"text": "### 5.4 Opaque versus Transparent Structure Types\nWith a structure type definition like\n> ([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) posn (x y))\nan instance of the structure type prints in a way that does not show any information about the fields’ values. That is, structure types by default are opaque. If the accessors and mutators of a structure type are kept private to a module, then no other module can rely on the representation of the type’s instances.\nTo make a structure type transparent, use the #:transparent keyword after the field-name sequence:\n>
( struct posn ( x y )\n> #:transparent )

 

> ( posn 1 2 )\n> (posn 1 2)
"} {"text": "### 5.4 Opaque versus Transparent Structure Types\nAn instance of a transparent structure type prints like a call to the constructor, so that it shows the structures field values. A transparent structure type also allows reflective operations, such as [struct?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=structutils.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._struct%7E3f%2529%2529&version=8.18.0.13) and [struct-info](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=inspectors.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._struct-info%2529%2529&version=8.18.0.13), to be used on its instances (see [Reflection and Dynamic Evaluation](reflection.html)).\nStructure types are opaque by default, because opaque structure instances provide more encapsulation guarantees. That is, a library can use an opaque structure to encapsulate data, and clients of the library cannot manipulate the data in the structure except as allowed by the library."} {"text": "### 5.5 Structure Comparisons\nA generic [equal?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._equal%7E3f%2529%2529&version=8.18.0.13) comparison automatically recurs on the fields of a transparent structure type, but [equal?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._equal%7E3f%2529%2529&version=8.18.0.13) defaults to mere instance identity for opaque structure types:\n>
([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) glass (width height) #:transparent)

 

> ( equal? ( glass 1 2 ) ( glass 1 2 ) )\n> #t
"} {"text": "### 5.5 Structure Comparisons\n>
([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) lead (width height))

 

> ( define slab ( lead 1 2 ) )\n> > ( equal? slab slab )\n> #t\n> > ( equal? slab ( lead 1 2 ) )\n> #f
\nTo support instances comparisons via [equal?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._equal%7E3f%2529%2529&version=8.18.0.13) without making the structure type transparent, you can use the #:methods keyword, [gen:equal+hash](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._gen%7E3aequal%252Bhash%2529%2529&version=8.18.0.13), and implement three methods:\n> ```\n(struct lead (width height)"} {"text": "### 5.5 Structure Comparisons\n> #:methods\n> gen:equal+hash\n> [ ( define ( equal-proc a b equal?-recur )\n> ; compare a and b\n> ( and ( equal?-recur ( lead-width a ) ( lead-width b ) )\n> ( equal?-recur ( lead-height a ) ( lead-height b ) ) ) )\n> ( define ( hash-proc a hash-recur )\n> ; compute primary hash code of a\n> ( + ( hash-recur ( lead-width a ) )\n> ( * 3 ( hash-recur ( lead-height a ) ) ) ) )\n> ( define ( hash2-proc a hash2-recur )\n> ; compute secondary hash code of a\n> ( + ( hash2-recur ( lead-width a ) )\n> ( hash2-recur ( lead-height a ) ) ) ) ] )\n> ( equal? ( lead 1 2 ) ( lead 1 2 ) )\n> #t"} {"text": "### 5.5 Structure Comparisons\n```\nThe first function in the list implements the equal? test on two leads; the third argument to the function is used instead of equal? for recursive equality testing, so that data cycles can be handled correctly. The other two functions compute primary and secondary hash codes for use with hash tables:\n\n> ```racket\n> > ( define h ( make-hash ) )\n> > ( hash-set! h ( lead 1 2 ) 3 )\n> > ( hash-ref h ( lead 1 2 ) )\n> 3\n> > ( hash-ref h ( lead 2 1 ) )\n> hash-ref: no value found for key\n> key: #\n> ```\n\nThe first function provided with gen:equal+hash is not required to recursively compare the fields of the structure. For example, a structure type representing a set might implement equality by checking that the members of the set are the same, independent of the order of elements in the internal representation. Just take care that the hash functions produce the same value for any two structure types that are supposed to be equivalent.\n\n### 5.6 Structure Type Generativity\n\nEach time that a struct form is evaluated, it generates a structure type that is distinct from all existing structure types, even if some other structure type has the same name and fields.\n\nThis generativity is useful for enforcing abstractions and implementing programs such as interpreters, but beware of placing a struct form in positions that are evaluated multiple times.\n\nExamples:\n\n> ```racket\n> ( define ( add-bigger-fish lst ) ( struct fish ( size ) #:transparent ) ; new every time ( cond [ ( null? lst ) ( list ( fish 1 ) ) ] [ else ( cons ( fish ( * 2 ( fish-size ( car lst ) ) ) ) lst ) ] ) )\n> > ( add-bigger-fish null )\n> (list (fish 1))\n> > ( add-bigger-fish ( add-bigger-fish null ) )\n> fish-size: contract violation\n> expected: fish?\n> given: (fish 1)\n> ```\n\n> ```\n(struct fish (size) #:transparent)\n> ( define ( add-bigger-fish lst )\n> ( cond\n> [ ( null? lst ) ( list ( fish 1 ) ) ]\n> [ else ( cons ( fish ( * 2 ( fish-size ( car lst ) ) ) )\n> lst ) ] ) )\n \n> ( add-bigger-fish ( add-bigger-fish null ) )\n> (list (fish 2) (fish 1))```\n\n\n### 5.7 Prefab Structure Types\n\nAlthough a [transparent](#%28tech._transparent%29) structure type prints in a way that shows its content, the printed form of the structure cannot be used in an expression to get the structure back, unlike the printed form of a number, string, symbol, or list.\n\nA prefab (“previously fabricated”) structure type is a built-in type that is known to the Racket printer and expression reader. Infinitely many such types exist, and they are indexed by name, field count, supertype, and other such details. The printed form of a prefab structure is similar to a vector, but it starts #s instead of just #, and the first element in the printed form is the prefab structure type’s name.\n\nThe following examples show instances of the sprout prefab structure type that has one field. The first instance has a field value 'bean, and the second has field value 'alfalfa:\n\n> ```racket\n> > ' #s ( sprout bean )\n> '#s(sprout bean)\n> > ' #s ( sprout alfalfa )\n> '#s(sprout alfalfa)\n> ```\n\nLike numbers and strings, prefab structures are “self-quoting,” so the quotes above are optional:\n\n> ```racket\n> > #s ( sprout bean )\n> '#s(sprout bean)\n> ```\n\nWhen you use the #:prefab keyword with [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13), instead of generating a new structure type, you obtain bindings that work with the existing prefab structure type:\n\n> ```racket\n> > ( define lunch ' #s ( sprout bean ) )\n> > ( struct sprout ( kind ) #:prefab )\n> > ( sprout? lunch )\n> #t\n> > ( sprout-kind lunch )\n> 'bean\n> > ( sprout ' garlic )\n> '#s(sprout garlic)\n> ```\n\nThe field name kind above does not matter for finding the prefab structure type; only the name sprout and the number of fields matter. At the same time, the prefab structure type sprout with three fields is a different structure type than the one with a single field:\n\n> ```racket\n> > ( sprout? #s ( sprout bean #f 17 ) )\n> #f\n> > ( struct sprout ( kind yummy? count ) #:prefab ) ; redefine\n> > ( sprout? #s ( sprout bean #f 17 ) )\n> #t\n> > ( sprout? lunch )\n> #f\n> ```\n\nA prefab structure type can have another prefab structure type as its supertype, it can have mutable fields, and it can have auto fields. Variations in any of these dimensions correspond to different prefab structure types, and the printed form of the structure type’s name encodes all of the relevant details.\n\n> ```racket\n> > ( struct building ( rooms [ location #:mutable ] ) #:prefab )\n> > ( struct house building ( [ occupied #:auto ] ) #:prefab #:auto-value ' no )\n> > ( house 5 ' factory )\n> '#s((house (1 no) building 2 #(1)) 5 factory no)\n> ```\n\nEvery [prefab](#%28tech._prefab%29) structure type is [transparent](#%28tech._transparent%29)—but even less abstract than a [transparent](#%28tech._transparent%29) type, because instances can be created without any access to a particular structure-type declaration or existing examples. Overall, the different options for structure types offer a spectrum of possibilities from more abstract to more convenient:\n\n- [Opaque](#%28tech._opaque%29) (the default) : Instances cannot be inspected or forged without access to the structure-type declaration. As discussed in the next section, [constructor guards](#%28tech._constructor._guard%29) and [properties](#%28tech._property%29) can be attached to the structure type to further protect or to specialize the behavior of its instances.\n\n- [Transparent](#%28tech._transparent%29) : Anyone can inspect or create an instance without access to the structure-type declaration, which means that the value printer can show the content of an instance. All instance creation passes through a [constructor guard](#%28tech._constructor._guard%29), however, so that the content of an instance can be controlled, and the behavior of instances can be specialized through [properties](#%28tech._property%29). Since the structure type is generated by its definition, instances cannot be manufactured simply through the name of the structure type, and therefore cannot be generated automatically by the expression reader.\n\n- [Prefab](#%28tech._prefab%29) : Anyone can inspect or create an instance at any time, without prior access to a structure-type declaration or an example instance. Consequently, the expression reader can manufacture instances directly. The instance cannot have a [constructor guard](#%28tech._constructor._guard%29) or [properties](#%28tech._property%29).\n\nSince the expression reader can generate [prefab](#%28tech._prefab%29) instances, they are useful when convenient [serialization](serialization.html#%28tech._serialization%29) is more important than abstraction. [Opaque](#%28tech._opaque%29) and [transparent](#%28tech._transparent%29) structures also can be serialized, however, if they are defined with [serializable-struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528form._%2528%2528lib._racket%252Fserialize..rkt%2529._serializable-struct%2529%2529&version=8.18.0.13) as described in [Datatypes and Serialization](serialization.html).\n\n### 5.8 More Structure Type Options\n\nThe full syntax of [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) supports many options, both at the structure-type level and at the level of individual fields:\n\n> > ```\n(struct struct-id maybe-super (field ...)\n> > struct-option ... )\n \nmaybe-super   =  \n    |   super-id\n         \nfield   =   field-id\n    |   [field-id field-option ...]\n```"} {"text": "### 5.5 Structure Comparisons\n(find-user-collects-dir)\t→\t\n(-> error type-name \"bad name: ~e\" name)```\nwhere the name-id is a name for the module, initial-module-path is an initial import, and each decl is an import, export, definition, or expression. In the case of a file, name-id normally matches the name of the containing file, minus its directory path or file extension, but name-id is ignored when the module is [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)d through its file’s path."} {"text": "### 5.5 Structure Comparisons\nThe initial-module-path is needed because even the [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) form must be imported for further use in the module body. In other words, the initial-module-path import bootstraps the syntax that is available in the body. The most commonly used initial-module-path is [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13), which supplies most of the bindings described in this guide, including [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13), [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13), and [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13). Another commonly used initial-module-path is [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13), which provides less functionality, but still much of the most commonly needed functions and syntax."} {"text": "### 5.5 Structure Comparisons\nFor example, the \"cake.rkt\" example of the [previous section](module-basics.html) could be written as\n> ```racket\n> ( module cake racket\n> ( provide print-cake )\n> ( define ( print-cake n )\n> ( show \" ~a \" n #\\. )\n> ( show \" .-~a-. \" n #\\| )\n> ( show \" | ~a | \" n #\\space )\n> ( show \"---~a---\" n #\\- ) )\n> ( define ( show fmt n ch )\n> ( printf fmt ( make-string n ch ) )\n> ( newline ) ) )\n> ```\nFurthermore, this [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) form can be evaluated in a [REPL](intro.html#%28tech._repl%29) to declare a cake module that is not associated with any file. To refer to such an unassociated module, quote the module name:\nExamples:\n> ```racket\n> > ( require ' cake )\n> > ( print-cake 3 )\n> ... .-|||-. | | ---------\n> ```"} {"text": "### 5.5 Structure Comparisons\nDeclaring a module does not immediately evaluate the body definitions and expressions of the module. The module must be explicitly [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)d at the top level to trigger evaluation. After evaluation is triggered once, later [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)s do not re-evaluate the module body.\nExamples:\n> ```racket\n> > ( module hi racket ( printf \"Hello\\n\" ) )\n> > ( require ' hi )\n> Hello\n> > ( require ' hi )\n> ```"} {"text": "#### 6.2.2 The #lang Shorthand\nThe body of a #lang shorthand has no specific syntax, because the syntax is determined by the language name that follows #lang.\nIn the case of #lang [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13), the syntax is\n> ```racket\n> #lang racket\n> decl ...\n> ```\nwhich [reads](hash-lang_reader.html) the same as\n> ```racket\n> ( module name racket\n> decl ... )\n> ```\nwhere name is derived from the name of the file that contains the #lang form.\nThe #lang [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) form has the same syntax as #lang [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13), except that the longhand expansion uses [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) instead of [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13). The #lang [scribble/manual](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=scribble&rel=manual.html&version=8.18.0.13) form, in contrast, has a completely different syntax that doesn’t even look like Racket, and which we do not attempt to describe in this guide."} {"text": "### 5.5 Structure Comparisons\nUnless otherwise specified, a module that is documented as a “language” using the #lang notation will expand to [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) in the same way as #lang [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13). The documented language name can be used directly with [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) or [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13), too."} {"text": "#### 6.2.3 Submodules\nA [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) form can be nested within a module, in which case the nested [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) form declares a submodule. Submodules can be referenced directly by the enclosing module using a quoted name. The following example prints \"Tony\" by importing tiger from the zoo submodule:\n> > \"park.rkt\"\n> >\n> > > ```racket\n> > > #lang racket\n> > > ( module zoo racket\n> > > ( provide tiger )\n> > > ( define tiger \"Tony\" ) )\n> > > ( require ' zoo )\n> > > tiger\n> > > ```\nRunning a module does not necessarily run its submodules. In the above example, running \"park.rkt\" runs its submodule zoo only because the \"park.rkt\" module [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)s the zoo submodule. Otherwise, a module and each of its submodules can be run independently. Furthermore, if \"park.rkt\" is compiled to a bytecode file (via raco make), then the code for \"park.rkt\" or the code for zoo can be loaded independently."} {"text": "### 5.5 Structure Comparisons\nSubmodules can be nested within submodules, and a submodule can be referenced directly by a module other than its enclosing module by using a [submodule path](module-paths.html#%28elem._submod%29).\nA [module*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%252A%2529%2529&version=8.18.0.13) form is similar to a nested [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) form:\n> > ```\n(module* name-id initial-module-path-or-#f\n> > decl ... )"} {"text": "### 5.5 Structure Comparisons\n```\nThe module* form differs from module in that it inverts the possibilities for reference between the submodule and enclosing module:\n\n- A submodule declared with module can be required by its enclosing module, but the submodule cannot require the enclosing module or lexically reference the enclosing module’s bindings.\n\n- A submodule declared with module* can require its enclosing module, but the enclosing module cannot require the submodule.\n\nIn addition, a module* form can specify #f in place of an initial-module-path, in which case the submodule sees all of the enclosing module’s bindings—including bindings that are not exported via provide.\n\nOne use of submodules declared with module* and #f is to export additional bindings through a submodule that are not normally exported from the module:\n\n> > \"cake.rkt\"\n> >\n> > > ```racket\n> > > #lang racket\n> > > ( provide print-cake )\n> > > ( define ( print-cake n )\n> > > ( show \" ~a \" n #\\. )\n> > > ( show \" .-~a-. \" n #\\| )\n> > > ( show \" | ~a | \" n #\\space )\n> > > ( show \"---~a---\" n #\\- ) )\n> > > ( define ( show fmt n ch )\n> > > ( printf fmt ( make-string n ch ) )\n> > > ( newline ) )\n> > > ( module* extras #f\n> > > ( provide show ) )\n> > > ```\n\nIn this revised \"cake.rkt\" module, show is not imported by a module that uses (require \"cake.rkt\"), since most clients of \"cake.rkt\" will not want the extra function. A module can require the extra submodule using (require (submod \"cake.rkt\" extras)) to access the otherwise hidden show function.See submodule paths for more information on submod.\n\n#### 6.2.4 Main and Test Submodules\n\nThe following variant of \"cake.rkt\" includes a main submodule that calls print-cake:\n\n> > \"cake.rkt\"\n> >\n> > > ```racket\n> > > #lang racket\n> > > ( define ( print-cake n )\n> > > ( show \" ~a \" n #\\. )\n> > > ( show \" .-~a-. \" n #\\| )\n> > > ( show \" | ~a | \" n #\\space )\n> > > ( show \"---~a---\" n #\\- ) )\n> > > ( define ( show fmt n ch )\n> > > ( printf fmt ( make-string n ch ) )\n> > > ( newline ) )\n> > > ( module* main #f\n> > > ( print-cake 10 ) )\n> > > ```\n\nRunning a module does not run its module*-defined submodules. Nevertheless, running the above module via racket or DrRacket prints a cake with 10 candles, because the main submodule is a special case.\n\nWhen a module is provided as a program name to the racket executable or run directly within DrRacket, if the module has a main submodule, the main submodule is run after its enclosing module. Declaring a main submodule thus specifies extra actions to be performed when a module is run directly, instead of required as a library within a larger program.\n\nA main submodule does not have to be declared with module*. If the main module does not need to use bindings from its enclosing module, it can be declared with module. More commonly, main is declared using module+:\n\n> > ```\n(module+ name-id\n> > decl ... )```\n\n\nA submodule declared with [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) is like one declared with [module*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%252A%2529%2529&version=8.18.0.13) using #f as its initial-module-path. In addition, multiple [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) forms can specify the same submodule name, in which case the bodies of the [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) forms are combined to create a single submodule.\n\nThe combining behavior of [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) is particularly useful for defining a test submodule, which can be conveniently run using raco test in much the same way that main is conveniently run with racket. For example, the following \"physics.rkt\" module exports drop and to-energy functions, and it defines a test module to hold unit tests:\n\n> > \"physics.rkt\"\n> >\n> > > ```racket\n> > > #lang racket\n> > > ( module+ test\n> > > ( require rackunit )\n> > > ( define ε 1e-10 ) )\n> > > ( provide drop\n> > > to-energy )\n> > > ( define ( drop t )\n> > > ( * 1/2 9.8 t t ) )\n> > > ( module+ test\n> > > ( check-= ( drop 0 ) 0 ε )\n> > > ( check-= ( drop 10 ) 490 ε ) )\n> > > ( define ( to-energy m )\n> > > ( * m ( expt 299792458.0 2 ) ) )\n> > > ( module+ test\n> > > ( check-= ( to-energy 0 ) 0 ε )\n> > > ( check-= ( to-energy 1 ) 9e+16 1e+15 ) )\n> > > ```\n\nImporting \"physics.rkt\" into a larger program does not run the drop and to-energy tests—or even trigger the loading of the test code, if the module is compiled—but running raco test physics.rkt at a command line runs the tests.\n\nThe above \"physics.rkt\" module is equivalent to using [module*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%252A%2529%2529&version=8.18.0.13):\n\n> > \"physics.rkt\"\n> >\n> > > ```racket\n> > > #lang racket\n> > > ( provide drop\n> > > to-energy )\n> > > ( define ( drop t )\n> > > ( * 1/2 49/5 t t ) )\n> > > ( define ( to-energy m )\n> > > ( * m ( expt 299792458 2 ) ) )\n> > > ( module* test #f\n> > > ( require rackunit )\n> > > ( define ε 1e-10 )\n> > > ( check-= ( drop 0 ) 0 ε )\n> > > ( check-= ( drop 10 ) 490 ε )\n> > > ( check-= ( to-energy 0 ) 0 ε )\n> > > ( check-= ( to-energy 1 ) 9e+16 1e+15 ) )\n> > > ```\n\nUsing [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) instead of [module*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%252A%2529%2529&version=8.18.0.13) allows tests to be interleaved with function definitions.\n\nThe combining behavior of [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) is also sometimes helpful for a main module. Even when combining is not needed, ([module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) main ....) is preferred as it is more readable than ([module*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%252A%2529%2529&version=8.18.0.13) main #f ....).\n\n------------------------------------------------------------------------\n\n# 6.3 Module Paths\n\n### 6.3 Module Paths\n\nA module path is a reference to a module, as used with [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) or as the initial-module-path in a [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) form. It can be any of several forms:\n\n> > | |\n> > |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) id) |\n>\n> A [module path](#%28tech._module._path%29) that is a quoted identifier refers to a non-file [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) declaration using the identifier. This form of module reference makes the most sense in a [REPL](intro.html#%28tech._repl%29).\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module m racket ( provide color ) ( define color \"blue\" ) )\n> > > ( module n racket ( require ' m ) ( printf \"my favorite color is ~a\\n\" color ) )\n> > > ( require ' n )\n> > my favorite color is blue\n> > ```\n>\n> \n\n> > | |\n> > |------------|\n> > | rel-string |\n>\n> A string [module path](#%28tech._module._path%29) is a relative path using Unix-style conventions: / is the path separator, .. refers to the parent directory, and . refers to the same directory. The rel-string must not start or end with a path separator.\n>\n> The path is relative to the enclosing file, if any, or it is relative to the current directory. (More precisely, the path is relative to the value of ([current-load-relative-directory](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=eval.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-load-relative-directory%2529%2529&version=8.18.0.13)), which is set while loading a file.)\n>\n> [Module Basics](module-basics.html) shows examples using relative paths.\n>\n> If a relative path ends with a \".ss\" suffix, it is converted to \".rkt\". If the file that implements the referenced module actually ends in \".ss\", the suffix will be changed back when attempting to load the file (but a \".rkt\" suffix takes precedence). This two-way conversion provides compatibility with older versions of Racket.\n\n> > | |\n> > |-----|\n> > | id |\n>\n> A [module path](#%28tech._module._path%29) that is an unquoted identifier refers to an installed library. The id is constrained to contain only ASCII letters, ASCII numbers, +, -, \\_, and /, where / separates path elements within the identifier. The elements refer to [collection](module-basics.html#%28tech._collection%29)s and sub-[collections](module-basics.html#%28tech._collection%29), instead of directories and sub-directories.\n>\n> An example of this form is racket/date. It refers to the module whose source is the \"date.rkt\" file in the \"racket\" collection, which is installed as part of Racket. The \".rkt\" suffix is added automatically.\n>\n> Another example of this form is [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13), which is commonly used at the initial import. The path [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) is shorthand for racket/main; when an id has no /, then /main is automatically added to the end. Thus, [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) or racket/main refers to the module whose source is the \"main.rkt\" file in the \"racket\" collection.\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module m racket ( require racket/date ) ( printf \"Today is ~s\\n\" ( date->string ( seconds->date ( current-seconds ) ) ) ) )\n> > > ( require ' m )\n> > Today is \"Monday, September 1st, 2025\"\n> > ```\n>\n> \n\n>\n> When the full path of a module ends with \".rkt\", if no such file exists but one does exist with the \".ss\" suffix, then the \".ss\" suffix is substituted automatically. This transformation provides compatibility with older versions of Racket.\n\n> > | |\n> > |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) rel-string) |\n>\n> Like an unquoted-identifier path, but expressed as a string instead of an identifier. Also, the rel-string can end with a file suffix, in which case \".rkt\" is not automatically added.\n>\n> Example of this form include ([lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) \"racket/date.rkt\") and ([lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) \"racket/date\"), which are equivalent to racket/date. Other examples include ([lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) \"racket\"), ([lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) \"racket/main\"), and ([lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) \"racket/main.rkt\"), which are all equivalent to [racket](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13).\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module m ( lib \"racket\" ) ( require ( lib \"racket/date.rkt\" ) ) ( printf \"Today is ~s\\n\" ( date->string ( seconds->date ( current-seconds ) ) ) ) )\n> > > ( require ' m )\n> > Today is \"Monday, September 1st, 2025\"\n> > ```\n>\n> \n\n> > | |\n> > |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([planet](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._planet%2529%2529&version=8.18.0.13) id) |\n>\n> Accesses a third-party library that is distributed through the PLaneT server. The library is downloaded the first time that it is needed, and then the local copy is used afterward.\n>\n> The id encodes several pieces of information separated by a /: the package owner, then package name with optional version information, and an optional path to a specific library with the package. Like id as shorthand for a [lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) path, a \".rkt\" suffix is added automatically, and /main is used as the path if no sub-path element is supplied.\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module m ( lib \"racket\" ) ; Use \"schematics\" ' s \"random.plt\" 1.0, file \"random.rkt\" : ( require ( planet schematics/random:1/random ) ) ( display ( random-gaussian ) ) )\n> > > ( require ' m )\n> > 0.9050686838895684\n> > ```\n>\n> \n\n>\n> As with other forms, an implementation file ending with \".ss\" can be substituted automatically if no implementation file ending with \".rkt\" exists.\n\n> > | |\n> > |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([planet](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._planet%2529%2529&version=8.18.0.13) package-string) |\n>\n> Like the symbol form of a [planet](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._planet%2529%2529&version=8.18.0.13), but using a string instead of an identifier. Also, the package-string can end with a file suffix, in which case \".rkt\" is not added.\n>\n> As with other forms, an \".ss\" extension is converted to \".rkt\", while an implementation file ending with \".ss\" can be substituted automatically if no implementation file ending with \".rkt\" exists.\n\n> >
([planet](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._planet%2529%2529&version=8.18.0.13) rel-string (user-string pkg-string vers ...))
 
vers = nat
  | (nat nat)
  | ([=](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%7E3d%2529%2529&version=8.18.0.13) nat)
  | ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) nat)
  | ([-](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._-%2529%2529&version=8.18.0.13) nat)
\n>\n> A more general form to access a library from the PLaneT server. In this general form, a PLaneT reference starts like a [lib](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lib%2529%2529&version=8.18.0.13) reference with a relative path, but the path is followed by information about the producer, package, and version of the library. The specified package is downloaded and installed on demand.\n>\n> The verses specify a constraint on the acceptable version of the package, where a version number is a sequence of non-negative integers, and the constraints determine the allowable values for each element in the sequence. If no constraint is provided for a particular element, then any version is allowed; in particular, omitting all verses means that any version is acceptable. Specifying at least one vers is strongly recommended.\n>\n> For a version constraint, a plain nat is the same as ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) nat), which matches nat or higher for the corresponding element of the version number. A (start-nat end-nat) matches any number in the range start-nat to end-nat, inclusive. A ([=](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%7E3d%2529%2529&version=8.18.0.13) nat) matches only exactly nat. A ([-](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._-%2529%2529&version=8.18.0.13) nat) matches nat or lower.\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module m ( lib \"racket\" ) ( require ( planet \"random.rkt\" ( \"schematics\" \"random.plt\" 1 0 ) ) ) ( display ( random-gaussian ) ) )\n> > > ( require ' m )\n> > 0.9050686838895684\n> > ```\n>\n> \n\n>\n> The automatic \".ss\" and \".rkt\" conversions apply as with other forms.\n\n> > | |\n> > |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._file%2529%2529&version=8.18.0.13) string) |\n>\n> Refers to a file, where string is a relative or absolute path using the current platform’s conventions. This form is not portable, and it should not be used when a plain, portable rel-string suffices.\n>\n> The automatic \".ss\" and \".rkt\" conversions apply as with other forms.\n\n> >
([submod](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._submod%2529%2529&version=8.18.0.13) base element ...+)
 
base = module-path
  | \".\"
  | \"..\"
     
element = id
  | \"..\"
\n>\n> Refers to a submodule of base. The sequence of elements within [submod](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._submod%2529%2529&version=8.18.0.13) specify a path of submodule names to reach the final submodule.\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module zoo racket ( module monkey-house racket ( provide monkey ) ( define monkey \"Curious George\" ) ) )\n> > > ( require ( submod ' zoo monkey-house ) )\n> > > monkey\n> > \"Curious George\"\n> > ```\n>\n> \n\n>\n> Using \".\" as base within [submod](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._submod%2529%2529&version=8.18.0.13) stands for the enclosing module. Using \"..\" as base is equivalent to using \".\" followed by an extra \"..\". When a path of the form ([quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13) id) refers to a submodule, it is equivalent to ([submod](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._submod%2529%2529&version=8.18.0.13) \".\" id).\n>\n> Using \"..\" as an element cancels one submodule step, effectively referring to the enclosing module. For example, ([submod](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._submod%2529%2529&version=8.18.0.13) \"..\") refers to the enclosing module of the submodule in which the path appears.\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module zoo racket ( module monkey-house racket ( provide monkey ) ( define monkey \"Curious George\" ) ) ( module crocodile-house racket ( require ( submod \"..\" monkey-house ) ) ( provide dinner ) ( define dinner monkey ) ) )\n> > > ( require ( submod ' zoo crocodile-house ) )\n> > > dinner\n> > \"Curious George\"\n> > ```\n>\n> \n\n------------------------------------------------------------------------\n\n# 6.4 Imports: require\n\n### 6.4 Imports: [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)\n\nThe [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) form imports from another module. A [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) form can appear within a module, in which case it introduces bindings from the specified module into the importing module. A [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) form can also appear at the top level, in which case it both imports bindings and instantiates the specified module; that is, it evaluates the body definitions and expressions of the specified module, if they have not been evaluated already.\n\nA single [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) can specify multiple imports at once:\n\n> > | |\n> > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) require-spec ...) |\n\nSpecifying multiple require-specs in a single [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) is essentially the same as using multiple [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)s, each with a single require-spec. The difference is minor, and confined to the top-level: a single [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) can import a given identifier at most once, whereas a separate [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) can replace the bindings of a previous [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) (both only at the top level, outside of a module).\n\nThe allowed shape of a require-spec is defined recursively:\n\n> > > | |\n> > > |-------------|\n> > > | module-path |\n> >\n> > In its simplest form, a require-spec is a module-path (as defined in the previous section, [Module Paths](module-paths.html)). In this case, the bindings introduced by [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) are determined by [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) declarations within each module referenced by each module-path.\n> >\n> > \n\n> >\n> > Examples:\n> >\n> > \n\n> >\n> > \n\n> >\n> > > ```racket\n> > > > ( module m racket ( provide color ) ( define color \"blue\" ) )\n> > > > ( module n racket ( provide size ) ( define size 17 ) )\n> > > > ( require ' m ' n )\n> > > > ( list color size )\n> > > '(\"blue\" 17)\n> > > ```\n> >\n> > \n\n> > >
([only-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._only-in%2529%2529&version=8.18.0.13) require-spec id-maybe-renamed ...)
 
id-maybe-renamed = id
  | [orig-id bind-id]
\n> >\n> > An [only-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._only-in%2529%2529&version=8.18.0.13) form limits the set of bindings that would be introduced by a base require-spec. Also, [only-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._only-in%2529%2529&version=8.18.0.13) optionally renames each binding that is preserved: in a \\[orig-id bind-id\\] form, the orig-id refers to a binding implied by require-spec, and bind-id is the name that will be bound in the importing context instead of orig-id.\n> >\n> > \n\n> >\n> > Examples:\n> >\n> > \n\n> >\n> > \n\n> >\n> > > ```racket\n> > > > ( module m ( lib \"racket\" ) ( provide tastes-great? less-filling? ) ( define tastes-great? #t ) ( define less-filling? #t ) )\n> > > > ( require ( only-in ' m tastes-great? ) )\n> > > > tastes-great?\n> > > #t\n> > > > less-filling?\n> > > less-filling?: undefined;\n> > > cannot reference an identifier before its definition\n> > > in module: top-level\n> > > > ( require ( only-in ' m [ less-filling? lite? ] ) )\n> > > > lite?\n> > > #t\n> > > ```\n> >\n> > \n\n> > > | |\n> > > |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > > | ([except-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-in%2529%2529&version=8.18.0.13) require-spec id ...) |\n> >\n> > This form is the complement of [only-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._only-in%2529%2529&version=8.18.0.13): it excludes specific bindings from the set specified by require-spec.\n\n> > > | |\n> > > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > > | ([rename-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._rename-in%2529%2529&version=8.18.0.13) require-spec \\[orig-id bind-id\\] ...) |\n> >\n> > This form supports renaming like [only-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._only-in%2529%2529&version=8.18.0.13), but leaving alone identifiers from require-spec that are not mentioned as an orig-id.\n\n> > > | |\n> > > |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > > | ([prefix-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._prefix-in%2529%2529&version=8.18.0.13) prefix-id require-spec) |\n> >\n> > This is a shorthand for renaming, where prefix-id is added to the front of each identifier specified by require-spec.\n\nThe [only-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._only-in%2529%2529&version=8.18.0.13), [except-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-in%2529%2529&version=8.18.0.13), [rename-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._rename-in%2529%2529&version=8.18.0.13), and [prefix-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._prefix-in%2529%2529&version=8.18.0.13) forms can be nested to implement more complex manipulations of imported bindings. For example,\n\n> ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) ([prefix-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._prefix-in%2529%2529&version=8.18.0.13) m: ([except-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-in%2529%2529&version=8.18.0.13) 'm ghost)))\n\nimports all bindings that m exports, except for the ghost binding, and with local names that are prefixed with m:.\n\nEquivalently, the [prefix-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._prefix-in%2529%2529&version=8.18.0.13) could be applied before [except-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-in%2529%2529&version=8.18.0.13), as long as the omission with [except-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-in%2529%2529&version=8.18.0.13) is specified using the m: prefix:\n\n> ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) ([except-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-in%2529%2529&version=8.18.0.13) ([prefix-in](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._prefix-in%2529%2529&version=8.18.0.13) m: 'm) m:ghost))\n\n------------------------------------------------------------------------\n\n# 6.5 Exports: provide\n\n### 6.5 Exports: [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13)\n\nBy default, all of a module’s definitions are private to the module. The [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) form specifies definitions to be made available where the module is [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13)d.\n\n> > | |\n> > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) provide-spec ...) |\n\nA [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) form can only appear at module level (i.e., in the immediate body of a [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13)). Specifying multiple provide-specs in a single [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) is exactly the same as using multiple [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13)s each with a single provide-spec.\n\nEach identifier can be exported at most once from a module across all [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13)s within the module. More precisely, the external name for each export must be distinct; the same internal binding can be exported multiple times with different external names.\n\nThe allowed shape of a provide-spec is defined recursively:\n\n> > > | |\n> > > |------------|\n> > > | identifier |\n> >\n> > In its simplest form, a provide-spec indicates a binding within its module to be exported. The binding can be from either a local definition, or from an import.\n\n> > > | |\n> > > |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > > | ([rename-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._rename-out%2529%2529&version=8.18.0.13) \\[orig-id export-id\\] ...) |\n> >\n> > A [rename-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._rename-out%2529%2529&version=8.18.0.13) form is similar to just specifying an identifier, but the exported binding orig-id is given a different name, export-id, to importing modules.\n\n> > > | |\n> > > |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > > | ([struct-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct-out%2529%2529&version=8.18.0.13) struct-id) |\n> >\n> > A [struct-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct-out%2529%2529&version=8.18.0.13) form exports the bindings created by ([struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13) struct-id ....).\n> >\n> > > > > \"+\"See [Programmer-Defined Datatypes](define-struct.html) for information on [define-struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define-struct%2529%2529&version=8.18.0.13).\n\n> > > | |\n> > > |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > > | ([all-defined-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-defined-out%2529%2529&version=8.18.0.13)) |\n> >\n> > The [all-defined-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-defined-out%2529%2529&version=8.18.0.13) shorthand exports all bindings that are defined within the exporting module (as opposed to imported).\n> >\n> > Use of the [all-defined-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-defined-out%2529%2529&version=8.18.0.13) shorthand is generally discouraged, because it makes less clear the actual exports for a module, and because Racket programmers get into the habit of thinking that definitions can be added freely to a module without affecting its public interface (which is not the case when [all-defined-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-defined-out%2529%2529&version=8.18.0.13) is used).\n\n> > > | |\n> > > |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > > | ([all-from-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-from-out%2529%2529&version=8.18.0.13) module-path) |\n> >\n> > The [all-from-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-from-out%2529%2529&version=8.18.0.13) shorthand exports all bindings in the module that were imported using a require-spec that is based on module-path.\n> >\n> > Although different module-paths could refer to the same file-based module, re-exporting with [all-from-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._all-from-out%2529%2529&version=8.18.0.13) is based specifically on the module-path reference, and not the module that is actually referenced.\n\n> > > | |\n> > > |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > > | ([except-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._except-out%2529%2529&version=8.18.0.13) provide-spec id ...) |\n> >\n> > Like provide-spec, but omitting the export of each id, where id is the external name of the binding to omit.\n\n> > > | |\n> > > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > > | ([prefix-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._prefix-out%2529%2529&version=8.18.0.13) prefix-id provide-spec) |\n> >\n> > Like provide-spec, but adding prefix-id to the beginning of the external name for each exported binding.\n\n------------------------------------------------------------------------\n\n# 6.6 Assignment and Redefinition\n\n### 6.6 Assignment and Redefinition\n\nThe use of [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) on variables defined within a module is limited to the body of the defining module. That is, a module is allowed to change the value of its own definitions, and such changes are visible to importing modules. However, an importing context is not allowed to change the value of an imported binding.\n\nExamples:\n\n> ```racket\n> > ( module m racket ( provide counter increment! ) ( define counter 0 ) ( define ( increment! ) ( set! counter ( add1 counter ) ) ) )\n> > ( require ' m )\n> > counter\n> 0\n> > ( increment! )\n> > counter\n> 1\n> > ( set! counter -1 )\n> set!: cannot mutate module-required identifier\n> at: counter\n> in: (set! counter -1)\n> ```\n\nAs the above example illustrates, a module can always grant others the ability to change its exports by providing a mutator function, such as increment!.\n\nThe prohibition on assignment of imported variables helps support modular reasoning about programs. For example, in the module,\n\n> ```racket\n> ( module m racket\n> ( provide rx:fish fishy-string? )\n> ( define rx:fish #rx\"fish\" )\n> ( define ( fishy-string? s )\n> ( regexp-match? rx:fish s ) ) )\n> ```\n\nthe function fishy-string? will always match strings that contain “fish”, no matter how other modules use the rx:fish binding. For essentially the same reason that it helps programmers, the prohibition on assignment to imports also allows many programs to be executed more efficiently.\n\nAlong the same lines, when a module contains no [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) of a particular identifier that is defined within the module, then the identifier is considered a constant that cannot be changed—not even by re-declaring the module.\n\nConsequently, re-declaration of a module is not generally allowed. For file-based modules, simply changing the file does not lead to a re-declaration in any case, because file-based modules are loaded on demand, and the previously loaded declarations satisfy future requests. It is possible to use Racket’s reflection support to re-declare a module, however, and non-file modules can be re-declared in the [REPL](intro.html#%28tech._repl%29); in such cases, the re-declaration may fail if it involves the re-definition of a previously constant binding.\n\n> ```racket\n> > ( module m racket ( define pie 3.141597 ) )\n> > ( require ' m )\n> > ( module m racket ( define pie 3 ) )\n> define-values: assignment disallowed;\n> cannot re-define a constant\n> constant: pie\n> in module:'m\n> ```\n\nFor exploration and debugging purposes, the Racket reflective layer provides a [compile-enforce-module-constants](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=eval.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._compile-enforce-module-constants%2529%2529&version=8.18.0.13) parameter to disable the enforcement of constants.\n\n> ```racket\n> > ( compile-enforce-module-constants #f )\n> > ( module m2 racket ( provide pie ) ( define pie 3.141597 ) )\n> > ( require ' m2 )\n> > ( module m2 racket ( provide pie ) ( define pie 3 ) )\n> > ( compile-enforce-module-constants #t )\n> > pie\n> 3\n> ```\n\n------------------------------------------------------------------------\n\n# 6.7 Modules and Macros\n\n### 6.7 Modules and Macros\n\nRacket’s module system cooperates closely with Racket’s [macro](macros.html#%28tech._macro%29) system for adding new syntactic forms to Racket. For example, in the same way that importing [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) introduces syntax for [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) and [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13), importing other modules can introduce new syntactic forms (in addition to more traditional kinds of imports, such as functions or constants).\n\nWe introduce macros in more detail later, in [Macros](macros.html), but here’s a simple example of a module that defines a pattern-based macro:\n\n> ```racket\n> ( module noisy racket\n> ( provide define-noisy )\n> ( define-syntax-rule ( define-noisy ( id arg ... ) body )\n> ( define ( id arg ... )\n> ( show-arguments ' id ( list arg ... ) )\n> body ) )\n> ( define ( show-arguments name args )\n> ( printf \"calling ~s with arguments ~e\" name args ) ) )\n> ```\n\nThe define-noisy binding provided by this module is a [macro](macros.html#%28tech._macro%29) that acts like [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) for a function, but it causes each call to the function to print the arguments that are provided to the function:\n\n> ```racket\n> > ( require ' noisy )\n> > ( define-noisy ( f x y ) ( + x y ) )\n> > ( f 1 2 )\n> calling f with arguments '(1 2)\n> 3\n> ```\n\nRoughly, the define-noisy form works by replacing\n\n> ```racket\n> ( define-noisy ( f x y )\n> ( + x y ) )\n> ```\n\nwith\n\n> ```racket\n> ( define ( f x y )\n> ( show-arguments ' f ( list x y ) )\n> ( + x y ) )\n> ```\n\nSince show-arguments isn’t provided by the noisy module, however, this literal textual replacement is not quite right. The actual replacement correctly tracks the origin of identifiers like show-arguments, so they can refer to other definitions in the place where the macro is defined—even if those identifiers are not available at the place where the macro is used.\n\nThere’s more to the macro and module interaction than identifier binding. The [define-syntax-rule](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmisc..rkt%2529._define-syntax-rule%2529%2529&version=8.18.0.13) form is itself a macro, and it expands to compile-time code that implements the transformation from define-noisy into [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13). The module system keeps track of which code needs to run at compile and which needs to run normally, as explained more in [Compile and Run-Time Phases](stx-phases.html) and [Module Instantiations and Visits](macro-module.html).\n\n------------------------------------------------------------------------\n\n# 6.8 Protected Exports\n\n### 6.8 Protected Exports\n\nSometimes, a module needs to export bindings to other modules that are at the same trust level as the exporting module, while at the same time preventing access from untrusted modules. Such exports should use the [protect-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._protect-out%2529%2529&version=8.18.0.13) form in [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13). For example, [ffi/unsafe](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=foreign&rel=index.html&version=8.18.0.13) exports all of its unsafe bindings as protected in this sense.\n\nLevels of trust are implemented with [code inspectors](code-inspectors_protect.html#%28tech._code._inspector%29) (see [Code Inspectors for Trusted and Untrusted Code](code-inspectors_protect.html)). Only modules loaded with an equally strong code inspector as an exporting module can use protected bindings from the exporting module. Operations like [dynamic-require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Module_Names_and_Loading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._dynamic-require%2529%2529&version=8.18.0.13) are granted access depending on the current code inspector as determined by [current-code-inspector](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=modprotect.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-code-inspector%2529%2529&version=8.18.0.13).\n\nWhen a module re-exports a protected binding, it does not need to use [protect-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._protect-out%2529%2529&version=8.18.0.13) again. Access is always determined by the code inspector of the module that originally defines a protected binding. When using a protected binding within a module, take care to either provide new bindings from the module with [protect-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._protect-out%2529%2529&version=8.18.0.13) or ensure that no provided bindings expose functionality that was meant to be protected in the first place.\n\n------------------------------------------------------------------------\n\n# 7 Contracts\n\n## 7 Contracts\n\nThis chapter provides a gentle introduction to Racket’s contract system.\n\n> > > \"+\"[Contracts](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=contracts.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on contracts.\n\n| |\n|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n|     [7.1 Contracts and Boundaries](contract-boundaries.html) |\n|       [7.1.1 Contract Violations](contract-boundaries.html#%28part._contracts-amount0%29) |\n|       [7.1.2 Experimenting with Contracts and Modules](contract-boundaries.html#%28part._.Experimenting_with_.Contracts_and_.Modules%29) |\n|       [7.1.3 Experimenting with Nested Contract Boundaries](contract-boundaries.html#%28part._contracts-intro-nested%29) |\n|     [7.2 Simple Contracts on Functions](contract-func.html) |\n|       [7.2.1 Styles of ->](contract-func.html#%28part._.Styles_of_-_%29) |\n|       [7.2.2 Using define/contract and ->](contract-func.html#%28part._simple-nested%29) |\n|       [7.2.3 any and any/c](contract-func.html#%28part._any_and_any_c%29) |\n|       [7.2.4 Rolling Your Own Contracts](contract-func.html#%28part._contracts-own%29) |\n|       [7.2.5 Contracts on Higher-order Functions](contract-func.html#%28part._.Contracts_on_.Higher-order_.Functions%29) |\n|       [7.2.6 Contract Messages with “???”](contract-func.html#%28part._contracts-flat-named-contracts%29) |\n|       [7.2.7 Dissecting a contract error message](contract-func.html#%28part._contracts-dissecting-contract-errors%29) |\n|     [7.3 Contracts on Functions in General](contracts-general-functions.html) |\n|       [7.3.1 Optional Arguments](contracts-general-functions.html#%28part._contracts-optional%29) |\n|       [7.3.2 Rest Arguments](contracts-general-functions.html#%28part._contracts-rest-args%29) |\n|       [7.3.3 Keyword Arguments](contracts-general-functions.html#%28part._contracts-keywords%29) |\n|       [7.3.4 Optional Keyword Arguments](contracts-general-functions.html#%28part._contracts-optional-keywords%29) |\n|       [7.3.5 Contracts for case-lambda](contracts-general-functions.html#%28part._contracts-case-lambda%29) |\n|       [7.3.6 Argument and Result Dependencies](contracts-general-functions.html#%28part._contracts-arrow-d%29) |\n|       [7.3.7 Checking State Changes](contracts-general-functions.html#%28part._contracts-arrow-d-eval-order%29) |\n|       [7.3.8 Multiple Result Values](contracts-general-functions.html#%28part._contracts-multiple%29) |\n|       [7.3.9 Fixed but Statically Unknown Arities](contracts-general-functions.html#%28part._contracts-no-domain%29) |\n|     [7.4 Contracts: A Thorough Example](contracts-first.html) |\n|     [7.5 Contracts on Structures](contracts-struct.html) |\n|       [7.5.1 Guarantees for a Specific Value](contracts-struct.html#%28part._contracts-single-struct%29) |\n|       [7.5.2 Guarantees for All Values](contracts-struct.html#%28part._contracts-define-struct%29) |\n|       [7.5.3 Checking Properties of Data Structures](contracts-struct.html#%28part._contracts-lazy-contracts%29) |\n|     [7.6 Abstract Contracts using #:exists and #:∃](contracts-exists.html) |\n|     [7.7 Additional Examples](contracts-examples.html) |\n|       [7.7.1 A Customer-Manager Component](contracts-examples.html#%28part._.A_.Customer-.Manager_.Component%29) |\n|       [7.7.2 A Parameteric (Simple) Stack](contracts-examples.html#%28part._.A_.Parameteric__.Simple__.Stack%29) |\n|       [7.7.3 A Dictionary](contracts-examples.html#%28part._.A_.Dictionary%29) |\n|       [7.7.4 A Queue](contracts-examples.html#%28part._.A_.Queue%29) |\n|     [7.8 Building New Contracts](Building_New_Contracts.html) |\n|       [7.8.1 Contract Struct Properties](Building_New_Contracts.html#%28part._.Contract_.Struct_.Properties%29) |\n|       [7.8.2 With all the Bells and Whistles](Building_New_Contracts.html#%28part._.With_all_the_.Bells_and_.Whistles%29) |\n|     [7.9 Gotchas](contracts-gotchas.html) |\n|       [7.9.1 Contracts and eq?](contracts-gotchas.html#%28part._.Contracts_and_eq_%29) |\n|       [7.9.2 Contract boundaries and define/contract](contracts-gotchas.html#%28part._contracts-gotcha-nested%29) |\n|       [7.9.3 Exists Contracts and Predicates](contracts-gotchas.html#%28part._contracts-exists-gotcha%29) |\n|       [7.9.4 Defining Recursive Contracts](contracts-gotchas.html#%28part._.Defining_.Recursive_.Contracts%29) |\n|       [7.9.5 Mixing set! and contract-out](contracts-gotchas.html#%28part._.Mixing_set__and_contract-out%29) |\n\n------------------------------------------------------------------------\n\n# 7.1 Contracts and Boundaries\n\n### 7.1 Contracts and Boundaries\n\nLike a contract between two business partners, a software contract is an agreement between two parties. The agreement specifies obligations and guarantees for each “product” (or value) that is handed from one party to the other.\n\nA contract thus establishes a boundary between the two parties. Whenever a value crosses this boundary, the contract monitoring system performs contract checks, making sure the partners abide by the established contract.\n\nIn this spirit, Racket encourages contracts mainly at module boundaries. Specifically, programmers may attach contracts to [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) clauses and thus impose constraints and promises on the use of exported values. For example, the export specification\n\n> ```racket\n> #lang racket\n> ( provide ( contract-out [ amount positive? ] ) )\n> ( define amount ... )\n> ```\n\npromises to all clients of the above module that the value of amount will always be a positive number. The contract system monitors the module’s obligation carefully. Every time a client refers to amount, the monitor checks that the value of amount is indeed a positive number.\n\nThe contracts library is built into the Racket language, but if you wish to use racket/base, you can explicitly require the contracts library like this:\n\n> ```racket\n> #lang racket/base\n> ( require racket/contract ) ; now we can write contracts\n> ( provide ( contract-out [ amount positive? ] ) )\n> ( define amount ... )\n> ```\n\n#### 7.1.1 Contract Violations\n\nIf we bind amount to a number that is not positive,\n\n> ```racket\n> #lang racket\n> ( provide ( contract-out [ amount positive? ] ) )\n> ( define amount 0 )\n> ```\n\nthen, when the module is required, the monitoring system signals a violation of the contract and blames the module for breaking its promises.\n\nAn even bigger mistake would be to bind amount to a non-number value:\n\n> ```racket\n> #lang racket\n> ( provide ( contract-out [ amount positive? ] ) )\n> ( define amount ' amount )\n> ```\n\nIn this case, the monitoring system will apply [positive?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._positive%7E3f%2529%2529&version=8.18.0.13) to a symbol, but [positive?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._positive%7E3f%2529%2529&version=8.18.0.13) reports an error, because its domain is only numbers. To make the contract capture our intentions for all Racket values, we can ensure that the value is both a number and is positive, combining the two contracts with [and/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._and%252Fc%2529%2529&version=8.18.0.13):\n\n> ([provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13) ([contract-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._contract-out%2529%2529&version=8.18.0.13) \\[amount ([and/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._and%252Fc%2529%2529&version=8.18.0.13) [number?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._number%7E3f%2529%2529&version=8.18.0.13) [positive?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._positive%7E3f%2529%2529&version=8.18.0.13))\\]))\n\n#### 7.1.2 Experimenting with Contracts and Modules\n\nAll of the contracts and modules in this chapter (excluding those just following) are written using the standard #lang syntax for describing modules. Since modules serve as the boundary between parties in a contract, examples involve multiple modules.\n\nTo experiment with multiple modules within a single module or within DrRacket’s [definitions area](intro.html#%28tech._definitions._area%29), use Racket’s submodules. For example, try the example earlier in this section like this:\n\n> ```racket\n> #lang racket\n> ( module+ server\n> ( provide ( contract-out [ amount ( and/c number? positive? ) ] ) )\n> ( define amount 150 ) )\n> ( module+ main\n> ( require ( submod \"..\" server ) )\n> ( + amount 10 ) )\n> ```\n\nEach of the modules and their contracts are wrapped in parentheses with the [module+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._module%252B%2529%2529&version=8.18.0.13) keyword at the front. The first form after [module](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=module.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._module%2529%2529&version=8.18.0.13) is the name of the module to be used in a subsequent [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) statement (where each reference through a [require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) prefixes the name with \"..\").\n\n#### 7.1.3 Experimenting with Nested Contract Boundaries\n\nIn many cases, it makes sense to attach contracts at module boundaries. It is often convenient, however, to be able to use contracts at a finer granularity than modules. The [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13) form enables this kind of use:\n\n> ```racket\n> #lang racket\n> ( define/contract amount\n> ( and/c number? positive? )\n> 150 )\n> ( + amount 10 )\n> ```\n\nIn this example, the [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13) form establishes a contract boundary between the definition of amount and its surrounding context. In other words, the two parties here are the definition and the module that contains it.\n\nForms that create these nested contract boundaries can sometimes be subtle to use because they may have unexpected performance implications or blame a party that may seem unintuitive. These subtleties are explained in [Using define/contract and ->](contract-func.html#%28part._simple-nested%29) and [Contract boundaries and define/contract](contracts-gotchas.html#%28part._contracts-gotcha-nested%29).\n\n------------------------------------------------------------------------\n\n# 7.2 Simple Contracts on Functions\n\n### 7.2 Simple Contracts on Functions\n\nA mathematical function has a domain and a range. The domain indicates the kind of values that the function can accept as arguments, and the range indicates the kind of values that it produces. The conventional notation for describing a function with its domain and range is\n\n> f : A [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) B\n\nwhere A is the domain of the function and B is the range.\n\nFunctions in a programming language have domains and ranges, too, and a contract can ensure that a function receives only values in its domain and produces only values in its range. A [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) creates such a contract for a function. The forms after a [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) specify contracts for the domains and finally a contract for the range.\n\nHere is a module that might represent a bank account:\n\n> ```racket\n> #lang racket\n> ( provide ( contract-out\n> [ deposit ( -> number? any ) ]\n> [ balance ( -> number? ) ] ) )\n> ( define amount 0 )\n> ( define ( deposit a ) ( set! amount ( + amount a ) ) )\n> ( define ( balance ) amount )\n> ```\n\nThe module exports two functions:\n\n- deposit, which accepts a number and returns some value that is not specified in the contract, and\n\n- balance, which returns a number indicating the current balance of the account.\n\nWhen a module exports a function, it establishes two channels of communication between itself as a “server” and the “client” module that imports the function. If the client module calls the function, it sends a value into the server module. Conversely, if such a function call ends and the function returns a value, the server module sends a value back to the client module. This client–server distinction is important, because when something goes wrong, one or the other of the parties is to blame.\n\nIf a client module were to apply deposit to 'millions, it would violate the contract. The contract-monitoring system would catch this violation and blame the client for breaking the contract with the above module. In contrast, if the balance function were to return 'broke, the contract-monitoring system would blame the server module.\n\nA [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) by itself is not a contract; it is a contract combinator, which combines other contracts to form a contract.\n\n#### 7.2.1 Styles of [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13)\n\nIf you are used to mathematical functions, you may prefer a contract arrow to appear between the domain and the range of a function, not at the beginning. If you have read [How to Design Programs](https://htdp.org), you have seen this many times. Indeed, you may have seen contracts such as these in other people’s code:\n\n> ```racket\n> ( provide ( contract-out\n> [ deposit ( number? . -> . any ) ] ) )\n> ```\n\nIf a Racket S-expression contains two dots with a symbol in the middle, the reader re-arranges the S-expression and place the symbol at the front, as described in [Lists and Racket Syntax](Pairs__Lists__and_Racket_Syntax.html#%28part._lists-and-syntax%29). Thus,\n\n> ([number?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._number%7E3f%2529%2529&version=8.18.0.13) . [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) . [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13))\n\nis just another way of writing\n\n> ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [number?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._number%7E3f%2529%2529&version=8.18.0.13) [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13))\n\n#### 7.2.2 Using [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13) and [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13)\n\nThe [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13) form introduced in [Experimenting with Nested Contract Boundaries](contract-boundaries.html#%28part._contracts-intro-nested%29) can also be used to define functions that come with a contract. For example,\n\n> ```racket\n> ( define/contract ( deposit amount )\n> ( -> number? any )\n> ; implementation goes here\n> .... )\n> ```\n\nwhich defines the deposit function with the contract from earlier. Note that this has two potentially important impacts on the use of deposit:\n\n1. The contract will be checked on any call to deposit that is outside of the definition of deposit – even those inside the module in which it is defined. Because there may be many calls inside the module, this checking may cause the contract to be checked too often, which could lead to a performance degradation. This is especially true if the function is called repeatedly from a loop.\n\n2. In some situations, a function may be written to accept a more lax set of inputs when called by other code in the same module. For such use cases, the contract boundary established by [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13) is too strict.\n\n#### 7.2.3 [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13) and [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13)\n\nThe [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13) contract used for deposit matches any kind of result, and it can only be used in the range position of a function contract. Instead of [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13) above, we could use the more specific contract [void?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=void.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._void%7E3f%2529%2529&version=8.18.0.13), which says that the function will always return the ([void](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=void.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._void%2529%2529&version=8.18.0.13)) value. The [void?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=void.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._void%7E3f%2529%2529&version=8.18.0.13) contract, however, would require the contract monitoring system to check the return value every time the function is called, even though the “client” module can’t do much with the value. In contrast, [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13) tells the monitoring system not to check the return value, it tells a potential client that the “server” module makes no promises at all about the function’s return value, even whether it is a single value or multiple values.\n\nThe [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) contract is similar to [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13), in that it makes no demands on a value. Unlike [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13), [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) indicates a single value, and it is suitable for use as an argument contract. Using [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) as a range contract imposes a check that the function produces a single value. That is,\n\n> ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13))\n\ndescribes a function that accepts an integer and returns any number of values, while\n\n> ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13))\n\ndescribes a function that accepts an integer and produces a single result (but does not say anything more about the result). The function\n\n> ([define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) (f x) ([values](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=values.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._values%2529%2529&version=8.18.0.13) ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) x 1) ([-](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._-%2529%2529&version=8.18.0.13) x 1)))\n\nmatches ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13)), but not ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13)).\n\nUse [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) as a result contract when it is particularly important to promise a single result from a function. Use [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13) when you want to promise as little as possible (and incur as little checking as possible) for a function’s result.\n\n#### 7.2.4 Rolling Your Own Contracts\n\nThe deposit function adds the given number to the value of amount. While the function’s contract prevents clients from applying it to non-numbers, the contract still allows them to apply the function to complex numbers, negative numbers, or inexact numbers, none of which sensibly represent amounts of money.\n\nThe contract system allows programmers to define their own contracts as functions:\n\n> ```racket\n> #lang racket\n> ( define ( amount? a )\n> ( and ( number? a ) ( integer? a ) ( exact? a ) ( >= a 0 ) ) )\n> ( provide ( contract-out\n> ; an amount is a natural number of cents\n> ; is the given number an amount?\n> [ deposit ( -> amount? any ) ]\n> [ amount? ( -> any/c boolean? ) ]\n> [ balance ( -> amount? ) ] ) )\n> ( define amount 0 )\n> ( define ( deposit a ) ( set! amount ( + amount a ) ) )\n> ( define ( balance ) amount )\n> ```\n\nThis module defines an amount? function and uses it as a contract within [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) contracts. When a client calls the deposit function as exported with the contract ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) amount? [any](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%2529%2529&version=8.18.0.13)), it must supply an exact, nonnegative integer, otherwise the amount? function applied to the argument will return #f, which will cause the contract-monitoring system to blame the client. Similarly, the server module must provide an exact, nonnegative integer as the result of balance to remain blameless.\n\nOf course, it makes no sense to restrict a channel of communication to values that the client doesn’t understand. Therefore the module also exports the amount? predicate itself, with a contract saying that it accepts an arbitrary value and returns a boolean.\n\nIn this case, we could also have used [natural-number/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._natural-number%252Fc%2529%2529&version=8.18.0.13) in place of amount?, since it implies exactly the same check:\n\n> ```racket\n> ( provide ( contract-out\n> [ deposit ( -> natural-number/c any ) ]\n> [ balance ( -> natural-number/c ) ] ) )\n> ```\n\nEvery function that accepts one argument can be treated as a predicate and thus used as a contract. For combining existing checks into a new one, however, contract combinators such as [and/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._and%252Fc%2529%2529&version=8.18.0.13) and [or/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._or%252Fc%2529%2529&version=8.18.0.13) are often useful. For example, here is yet another way to write the contracts above:\n\n> ```racket\n> ( define amount/c\n> ( and/c number? integer? exact? ( or/c positive? zero? ) ) )\n> ( provide ( contract-out\n> [ deposit ( -> amount/c any ) ]\n> [ balance ( -> amount/c ) ] ) )\n> ```\n\nOther values also serve double duty as contracts. For example, if a function accepts a number or #f, ([or/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._or%252Fc%2529%2529&version=8.18.0.13) [number?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._number%7E3f%2529%2529&version=8.18.0.13) #f) suffices. Similarly, the amount/c contract could have been written with a 0 in place of [zero?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._zero%7E3f%2529%2529&version=8.18.0.13). If you use a regular expression as a contract, the contract accepts strings and byte strings that match the regular expression.\n\nNaturally, you can mix your own contract-implementing functions with combinators like [and/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._and%252Fc%2529%2529&version=8.18.0.13). Here is a module for creating strings from banking records:\n\n> ```racket\n> #lang racket\n> ( define ( has-decimal? str )\n> ( define L ( string-length str ) )\n> ( and ( >= L 3 )\n> ( char=? #\\. ( string-ref str ( - L 3 ) ) ) ) )\n> ( provide ( contract-out\n> ; convert a random number to a string\n> [ format-number ( -> number? string? ) ]\n> ; convert an amount into a string with a decimal\n> ; point, as in an amount of US currency\n> [ format-nat ( -> natural-number/c\n> ( and/c string? has-decimal? ) ) ] ) )\n> ```\n\nThe contract of the exported function format-number specifies that the function consumes a number and produces a string. The contract of the exported function format-nat is more interesting than the one of format-number. It consumes only natural numbers. Its range contract promises a string that has a . in the third position from the right.\n\nIf we want to strengthen the promise of the range contract for format-nat so that it admits only strings with digits and a single dot, we could write it like this:\n\n> ```racket\n> #lang racket\n> ( define ( digit-char? x )\n> ( member x ' ( #\\1 #\\2 #\\3 #\\4 #\\5 #\\6 #\\7 #\\8 #\\9 #\\0 ) ) )\n> ( define ( has-decimal? str )\n> ( define L ( string-length str ) )\n> ( and ( >= L 3 )\n> ( char=? #\\. ( string-ref str ( - L 3 ) ) ) ) )\n> ( define ( is-decimal-string? str )\n> ( define L ( string-length str ) )\n> ( and ( has-decimal? str )\n> ( andmap digit-char?\n> ( string->list ( substring str 0 ( - L 3 ) ) ) )\n> ( andmap digit-char?\n> ( string->list ( substring str ( - L 2 ) L ) ) ) ) )\n> ....\n> ( provide ( contract-out\n> ....\n> ; convert an amount (natural number) of cents\n> ; into a dollar-based string\n> [ format-nat ( -> natural-number/c\n> ( and/c string?\n> is-decimal-string? ) ) ] ) )\n> ```\n\nAlternately, in this case, we could use a regular expression as a contract:\n\n> ```racket\n> #lang racket\n> ( provide\n> ( contract-out\n> ....\n> ; convert an amount (natural number) of cents\n> ; into a dollar-based string\n> [ format-nat ( -> natural-number/c\n> ( and/c string? #rx\"[0-9]*\\\\.[0-9][0-9]\" ) ) ] ) )\n> ```\n\n#### 7.2.5 Contracts on Higher-order Functions\n\nFunction contracts are not just restricted to having simple predicates on their domains or ranges. Any of the contract combinators discussed here, including function contracts themselves, can be used as contracts on the arguments and results of a function.\n\nFor example,\n\n> ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13)))\n\nis a contract that describes a curried function. It matches functions that accept one argument and then return another function accepting a second argument before finally returning an integer. If a server exports a function make-adder with this contract, and if make-adder returns a value other than a function, then the server is to blame. If make-adder does return a function, but the resulting function is applied to a value other than an integer, then the client is to blame.\n\nSimilarly, the contract\n\n> ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13)) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13))\n\ndescribes functions that accept other functions as its input. If a server exports a function twice with this contract and the twice is applied to a value other than a function of one argument, then the client is to blame. If twice is applied to a function of one argument and twice calls the given function on a value other than an integer, then the server is to blame.\n\n#### 7.2.6 Contract Messages with “???”\n\nYou wrote your module. You added contracts. You put them into the interface so that client programmers have all the information from interfaces. It’s a piece of art:\n\n> ```racket\n> > ( module bank-server racket ( provide ( contract-out [ deposit ( -> ( λ ( x ) ( and ( number? x ) ( integer? x ) ( >= x 0 ) ) ) any ) ] ) ) ( define total 0 ) ( define ( deposit a ) ( set! total ( + a total ) ) ) )\n> ```\n\nSeveral clients used your module. Others used their modules in turn. And all of a sudden one of them sees this error message:\n\n> ```racket\n> > ( require ' bank-server )\n> > ( deposit -1 0 )\n> deposit: contract violation\n> expected: ???\n> given: -10\n> in: the 1st argument of\n> (-> ??? any)\n> contract from: bank-server\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\n\nWhat is the ??? doing there? Wouldn’t it be nice if we had a name for this class of data much like we have string, number, and so on?\n\nFor this situation, Racket provides flat named contracts. The use of “contract” in this term shows that contracts are first-class values. The “flat” means that the collection of data is a subset of the built-in atomic classes of data; they are described by a predicate that consumes all Racket values and produces a boolean. The “named” part says what we want to do, which is to name the contract so that error messages become intelligible:\n\n> ```racket\n> > ( module improved-bank-server racket ( provide ( contract-out [ deposit ( -> ( flat-named-contract ' amount ( λ ( x ) ( and ( number? x ) ( integer? x ) ( >= x 0 ) ) ) ) any ) ] ) ) ( define total 0 ) ( define ( deposit a ) ( set! total ( + a total ) ) ) )\n> ```\n\nWith this little change, the error message becomes quite readable:\n\n> ```racket\n> > ( require ' improved-bank-server )\n> > ( deposit -1 0 )\n> deposit: contract violation\n> expected: amount\n> given: -10\n> in: the 1st argument of\n> (-> amount any)\n> contract from: improved-bank-server\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:5:0\n> ```\n\n#### 7.2.7 Dissecting a contract error message\n\nIn general, each contract error message consists of six sections:\n\n- \n\n a name for the function or method associated with the contract and either the phrase “contract violation” or “broke its contract” depending on whether the contract was violated by the client or the server; e.g. in the previous example:\n\n \n\n \n\n | |\n |-----------------------------|\n | deposit: contract violation |\n\n \n\n- \n\n a description of the precise aspect of the contract that was violated,\n\n \n\n \n\n | |\n |------------------|\n | expected: amount |\n | given: -10 |\n\n \n\n- \n\n the complete contract plus a path into it showing which aspect was violated,\n\n \n\n \n\n | |\n |-------------------------|\n | in: the 1st argument of |\n | (-> amount any) |\n\n \n\n- \n\n the module where the contract was put (or, more generally, the boundary that the contract mediates),\n\n \n\n \n\n | |\n |-------------------------------------|\n | contract from: improved-bank-server |\n\n \n\n- \n\n who was blamed,\n\n \n\n \n\n | |\n |------------------------------------|\n | blaming: top-level |\n | (assuming the contract is correct) |\n\n \n\n- \n\n and the source location where the contract appears.\n\n \n\n \n\n | |\n |--------------|\n | at: eval:5:0 |\n\n \n\n------------------------------------------------------------------------\n\n# 7.3 Contracts on Functions in General\n\n### 7.3 Contracts on Functions in General\n\nThe [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) contract constructor works for functions that take a fixed number of arguments and where the result contract is independent of the input arguments. To support other kinds of functions, Racket supplies additional contract constructors, notably [->*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%252A%2529%2529&version=8.18.0.13) and [->i](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3ei%2529%2529&version=8.18.0.13).\n\n#### 7.3.1 Optional Arguments\n\nTake a look at this excerpt from a string-processing module:\n\n> ```racket\n> #lang racket\n> ( provide\n> ( contract-out\n> ; pad the given str left and right with\n> ; the (optional) char so that it is centered\n> [ string-pad-center ( -> * ( string? natural-number/c )\n> ( char? )\n> string? ) ] ) )\n> ( define ( string-pad-center str width [ pad #\\space ] )\n> ( define field-width ( min width ( string-length str ) ) )\n> ( define rmargin ( ceiling ( / ( - width field-width ) 2 ) ) )\n> ( define lmargin ( floor ( / ( - width field-width ) 2 ) ) )\n> ( string-append ( build-string lmargin ( λ ( x ) pad ) )\n> str\n> ( build-string rmargin ( λ ( x ) pad ) ) ) )\n> ```\n\nThe module exports string-pad-center, a function that creates a string of a given width with the given string in the center. The default fill character is #\\\\space; if the client module wishes to use a different character, it may call string-pad-center with a third argument, a char, overwriting the default.\n\nThe function definition uses optional arguments, which is appropriate for this kind of functionality. The interesting point here is the formulation of the contract for the string-pad-center.\n\nThe contract combinator [->*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%252A%2529%2529&version=8.18.0.13), demands several groups of contracts:\n\n- The first one is a parenthesized group of contracts for all required arguments. In this example, we see two: [string?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._string%7E3f%2529%2529&version=8.18.0.13) and [natural-number/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._natural-number%252Fc%2529%2529&version=8.18.0.13).\n\n- The second one is a parenthesized group of contracts for all optional arguments: [char?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=characters.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._char%7E3f%2529%2529&version=8.18.0.13).\n\n- The last one is a single contract: the result of the function.\n\nNote that if a default value does not satisfy a contract, you won’t get a contract error for this interface. If you can’t trust yourself to get the initial value right, you need to communicate the initial value across a boundary.\n\n#### 7.3.2 Rest Arguments\n\nThe [max](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._max%2529%2529&version=8.18.0.13) operator consumes at least one real number, but it accepts any number of additional arguments. You can write other such functions using a [rest argument](lambda.html#%28tech._rest._argument%29), such as in max-abs:\n\n> > > See [Declaring a Rest Argument](lambda.html#%28part._rest-args%29) for an introduction to rest arguments.\n\n> ```racket\n> ( define ( max-abs n . rst )\n> ( foldr ( lambda ( n m ) ( max ( abs n ) m ) ) ( abs n ) rst ) )\n> ```\n\nTo describe this function through a contract, you can use the [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13) feature of [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13).\n\n> ```racket\n> ( provide\n> ( contract-out\n> [ max-abs ( -> real? real? ... real? ) ] ) )\n> ```\n\nAlternatively, you can use [->*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%252A%2529%2529&version=8.18.0.13) with a #:rest keyword, which specifies a contract on a list of arguments after the required and optional arguments:\n\n> ```racket\n> ( provide\n> ( contract-out\n> [ max-abs ( -> * ( real? ) ( ) #:rest ( listof real? ) real? ) ] ) )\n> ```\n\nAs always for [->*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%252A%2529%2529&version=8.18.0.13), the contracts for the required arguments are enclosed in the first pair of parentheses, which in this case is a single real number. The empty pair of parenthesis indicates that there are no optional arguments (not counting the rest arguments). The contract for the rest argument follows #:rest; since all additional arguments must be real numbers, the list of rest arguments must satisfy the contract ([listof](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._listof%2529%2529&version=8.18.0.13) [real?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._real%7E3f%2529%2529&version=8.18.0.13)).\n\n#### 7.3.3 Keyword Arguments\n\nIt turns out that the [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) contract constructor also contains support for keyword arguments. For example, consider this function, which creates a simple GUI and asks the user a yes-or-no question:\n\n> > > See [Declaring Keyword Arguments](lambda.html#%28part._lambda-keywords%29) for an introduction to keyword arguments.\n\n> ```racket\n> #lang racket/gui\n> ( define ( ask-yes-or-no-question question\n> #:default answer\n> #:title title\n> #:width w\n> #:height h )\n> ( define d ( new dialog% [ label title ] [ width w ] [ height h ] ) )\n> ( define msg ( new message% [ label question ] [ parent d ] ) )\n> ( define ( yes ) ( set! answer #t ) ( send d show #f ) )\n> ( define ( no ) ( set! answer #f ) ( send d show #f ) )\n> ( define yes-b ( new button%\n> [ label \"Yes\" ] [ parent d ]\n> [ callback ( λ ( x y ) ( yes ) ) ]\n> [ style ( if answer ' ( border ) ' ( ) ) ] ) )\n> ( define no-b ( new button%\n> [ label \"No\" ] [ parent d ]\n> [ callback ( λ ( x y ) ( no ) ) ]\n> [ style ( if answer ' ( ) ' ( border ) ) ] ) )\n> ( send d show #t )\n> answer )\n> ( provide ( contract-out\n> [ ask-yes-or-no-question\n> ( -> string?\n> #:default boolean?\n> #:title string?\n> #:width exact-integer?\n> #:height exact-integer?\n> boolean? ) ] ) )\n> ```\n\n> > > If you really want to ask a yes-or-no question via a GUI, you should use [message-box/custom](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=gui&rel=Windowing_Functions.html%23%2528def._%2528%2528lib._mred%252Fmain..rkt%2529._message-box%252Fcustom%2529%2529&version=8.18.0.13). For that matter, it’s usually better to provide buttons with more specific answers than “yes” and “no.”\n\nThe contract for ask-yes-or-no-question uses [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13), and in the same way that [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) (or [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13)-based functions) allows a keyword to precede a functions formal argument, [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) allows a keyword to precede a function contract’s argument contract. In this case, the contract says that ask-yes-or-no-question must receive four keyword arguments, one for each of the keywords #:default, #:title, #:width, and #:height. As in a function definition, the order of the keywords in [->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) relative to each other does not matter for clients of the function; only the relative order of argument contracts without keywords matters.\n\n#### 7.3.4 Optional Keyword Arguments\n\nOf course, many of the parameters in ask-yes-or-no-question (from the previous question) have reasonable defaults and should be made optional:\n\n> ```racket\n> ( define ( ask-yes-or-no-question question\n> #:default answer\n> #:title [ title \"Yes or No?\" ]\n> #:width [ w 400 ]\n> #:height [ h 200 ] )\n> ... )\n> ```\n\nTo specify this function’s contract, we need to use [->*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%252A%2529%2529&version=8.18.0.13) again. It supports keywords just as you might expect in both the optional and mandatory argument sections. In this case, we have the mandatory keyword #:default and optional keywords #:title, #:width, and #:height. So, we write the contract like this:\n\n> ```racket\n> ( provide ( contract-out\n> [ ask-yes-or-no-question\n> ( -> * ( string?\n> #:default boolean? )\n> ( #:title string?\n> #:width exact-integer?\n> #:height exact-integer? )\n> boolean? ) ] ) )\n> ```\n\nThat is, we put the mandatory keywords in the first section, and we put the optional ones in the second section.\n\n#### 7.3.5 Contracts for [case-lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._case-lambda%2529%2529&version=8.18.0.13)\n\nA function defined with [case-lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._case-lambda%2529%2529&version=8.18.0.13) might impose different constraints on its arguments depending on how many are provided. For example, a report-cost function might convert either a pair of numbers or a string into a new string:\n\n> > > See [Arity-Sensitive Functions: case-lambda](lambda.html#%28part._case-lambda%29) for an introduction to [case-lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._case-lambda%2529%2529&version=8.18.0.13).\n\n> ```\n(define report-cost\n> ( case-lambda\n> [ ( lo hi ) ( format \"between $~a and $~a\" lo hi ) ]\n> [ ( desc ) ( format \"~a of dollars\" desc ) ] ) )\n \n> ( report-cost 5 8 )\n> \"between $5 and $8\"\n> > ( report-cost \"millions\" )\n> \"millions of dollars\"\n```"} {"text": "### 5.5 Structure Comparisons\n(x)\t→\t\n(-> provide (contract-out\n [ report-cost\n (case →\n (integer? integer? . → . string?)\n (string? . → . string?)) ]))```\n------------------------------------------------------------------------"} {"text": "# 7.9 Gotchas"} {"text": "### 7.9 Gotchas"} {"text": "#### 7.9.1 Contracts and [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13)\nAs a general rule, adding a contract to a program should either leave the behavior of the program unchanged, or should signal a contract violation. And this is almost true for Racket contracts, with one exception: [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13).\nThe [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) procedure is designed to be fast and does not provide much in the way of guarantees, except that if it returns true, it means that the two values behave identically in all respects. Internally, this is implemented as pointer equality at a low-level so it exposes information about how Racket is implemented (and how contracts are implemented)."} {"text": "# 7.9 Gotchas\nContracts interact poorly with [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) because function contract checking is implemented internally as wrapper functions. For example, consider this module:\n> ```racket\n> #lang racket\n> ( define ( make-adder x )\n> ( if ( = 1 x )\n> add1\n> ( lambda ( y ) ( + x y ) ) ) )\n> ( provide ( contract-out\n> [ make-adder ( -> number? ( -> number? number? ) ) ] ) )\n> ```\nIt exports the make-adder function that is the usual curried addition function, except that it returns Racket’s [add1](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._add1%2529%2529&version=8.18.0.13) when its input is 1.\nYou might expect that\n> ```racket\n> ( eq? ( make-adder 1 )\n> ( make-adder 1 ) )\n> ```"} {"text": "# 7.9 Gotchas\nwould return #t, but it does not. If the contract were changed to [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) (or even ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [number?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._number%7E3f%2529%2529&version=8.18.0.13) [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13))), then the [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) call would return #t."} {"text": "# 7.9 Gotchas\nMoral: Do not use [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) on values that have contracts."} {"text": "#### 7.9.2 Contract boundaries and [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13)\nThe contract boundaries established by [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13), which creates a nested contract boundary, are sometimes unintuitive. This is especially true when multiple functions or other values with contracts interact. For example, consider these two interacting functions:\n> ```racket\n> > ( define/contract ( f x ) ( -> integer? integer? ) x )\n> > ( define/contract ( g ) ( -> string? ) ( f \"not an integer\" ) )\n> > ( g )\n> f: contract violation\n> expected: integer?\n> given: \"not an integer\"\n> in: the 1st argument of\n> (-> integer? integer?)\n> contract from: (function f)\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\nOne might expect that the function g will be blamed for breaking the terms of its contract with f. Blaming g would be right if f and g were directly establishing contracts with each other. They aren’t, however. Instead, the access between f and g is mediated through the top-level of the enclosing module."} {"text": "# 7.9 Gotchas\nMore precisely, f and the top-level of the module have the ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13) [integer?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=number-types.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._integer%7E3f%2529%2529&version=8.18.0.13)) contract mediating their interaction; g and the top-level have ([->](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=function-contracts.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._-%7E3e%2529%2529&version=8.18.0.13) [string?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._string%7E3f%2529%2529&version=8.18.0.13)) mediating their interaction, but there is no contract directly between f and g. This means that the reference to f in the body of g is really the top-level of the module’s responsibility, not g’s. In other words, the function f has been given to g with no contract between g and the top-level and thus the top-level is blamed."} {"text": "# 7.9 Gotchas\nIf we wanted to add a contract between g and the top-level, we can use [define/contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fregion..rkt%2529._define%252Fcontract%2529%2529&version=8.18.0.13)’s #:freevar declaration and see the expected blame:\n> ```racket\n> > ( define/contract ( f x ) ( -> integer? integer? ) x )\n> > ( define/contract ( g ) ( -> string? ) #:freevar f ( -> integer? integer? ) ( f \"not an integer\" ) )\n> > ( g )\n> f: contract violation\n> expected: integer?\n> given: \"not an integer\"\n> in: the 1st argument of\n> (-> integer? integer?)\n> contract from: top-level\n> blaming: (function g)\n> (assuming the contract is correct)\n> at: eval:6:0\n> ```\nMoral: if two values with contracts should interact, put them in separate modules with contracts at the module boundary or use #:freevar."} {"text": "#### 7.9.3 Exists Contracts and Predicates\nMuch like the [eq?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Equality.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._eq%7E3f%2529%2529&version=8.18.0.13) example above, #:∃ contracts can change the behavior of a program.\nSpecifically, the [null?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._null%7E3f%2529%2529&version=8.18.0.13) predicate (and many other predicates) return #f for #:∃ contracts, and changing one of those contracts to [any/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=data-structure-contracts.html%23%2528def._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fmisc..rkt%2529._any%252Fc%2529%2529&version=8.18.0.13) means that [null?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._null%7E3f%2529%2529&version=8.18.0.13) might now return #t instead, resulting in arbitrarily different behavior depending on how this boolean might flow around in the program.\nMoral: Do not use predicates on #:∃ contracts."} {"text": "#### 7.9.4 Defining Recursive Contracts\nWhen defining a self-referential contract, it is natural to use [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13). For example, one might try to write a contract on streams like this:\n> ```racket\n> > ( define stream/c ( promise/c ( or/c null? ( cons/c number? stream/c ) ) ) )\n> stream/c: undefined;\n> cannot reference an identifier before its definition\n> in module: top-level\n> ```\nUnfortunately, this does not work because the value of stream/c is needed before it is defined. Put another way, all of the combinators evaluate their arguments eagerly, even though the values that they accept do not.\nInstead, use\n> ```racket\n> ( define stream/c\n> ( promise/c\n> ( or/c\n> null?\n> ( cons/c number? ( recursive-contract stream/c ) ) ) ) )\n> ```\nThe use of [recursive-contract](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=contract-utilities.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fprivate%252Fbase..rkt%2529._recursive-contract%2529%2529&version=8.18.0.13) delays the evaluation of the identifier stream/c until after the contract is first checked, long enough to ensure that stream/c is defined.\nSee also [Checking Properties of Data Structures](contracts-struct.html#%28part._contracts-lazy-contracts%29)."} {"text": "#### 7.9.5 Mixing [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) and [contract-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._contract-out%2529%2529&version=8.18.0.13)\nThe contract library assumes that variables exported via [contract-out](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=attaching-contracts-to-values.html%23%2528form._%2528%2528lib._racket%252Fcontract%252Fbase..rkt%2529._contract-out%2529%2529&version=8.18.0.13) are not assigned to, but does not enforce it. Accordingly, if you try to [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) those variables, you may be surprised. Consider the following example:\n> ```racket\n> > ( module server racket ( define ( inc-x! ) ( set! x ( + x 1 ) ) ) ( define x 0 ) ( provide ( contract-out [ inc-x! ( -> void? ) ] [ x integer? ] ) ) )\n> > ( module client racket ( require ' server ) ( define ( print-latest ) ( printf \"x is ~s\\n\" x ) ) ( print-latest ) ( inc-x! ) ( print-latest ) )\n> > ( require ' client )\n> x is 0 x is 0\n> ```"} {"text": "# 7.9 Gotchas\nBoth calls to print-latest print 0, even though the value of x has been incremented (and the change is visible inside the module x).\nTo work around this, export accessor functions, rather than exporting the variable directly, like this:\n> ```racket\n> #lang racket\n> ( define ( get-x ) x )\n> ( define ( inc-x! ) ( set! x ( + x 1 ) ) )\n> ( define x 0 )\n> ( provide ( contract-out [ inc-x! ( -> void? ) ]\n> [ get-x ( -> integer? ) ] ) )\n> ```\nMoral: This is a bug that we will address in a future release.\n------------------------------------------------------------------------"} {"text": "# 8 Input and Output"} {"text": "## 8 Input and Output\n> > > A Racket port corresponds to the Unix notion of a stream (not to be confused with [racket/stream](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=streams.html&version=8.18.0.13)’s streams).\nA Racket port represents a source or sink of data, such as a file, a terminal, a TCP connection, or an in-memory string. Ports provide sequential access in which data can be read or written a piece at a time, without requiring the data to be consumed or produced all at once. More specifically, an input port represents a source from which a program can read data, and an output port represents a sink to which a program can write data.\n| |\n|---------------------------------------------------------------------------------------|\n|     [8.1 Varieties of Ports](ports.html) |\n|     [8.2 Default Ports](default-ports.html) |\n|     [8.3 Reading and Writing Racket Data](read-write.html) |\n|     [8.4 Datatypes and Serialization](serialization.html) |\n|     [8.5 Bytes, Characters, and Encodings](encodings.html) |\n|     [8.6 I/O Patterns](io-patterns.html) |\n------------------------------------------------------------------------"} {"text": "# 8.1 Varieties of Ports"} {"text": "### 8.1 Varieties of Ports\nVarious functions create various kinds of ports. Here are a few examples:\n- Files: The [open-output-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._open-output-file%2529%2529&version=8.18.0.13) function opens a file for writing, and [open-input-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._open-input-file%2529%2529&version=8.18.0.13) opens a file for reading.\n Examples:\n > ```racket\n > > ( define out ( open-output-file \"data\" ) )\n > > ( display \"hello\" out )\n > > ( close-output-port out )\n > > ( define in ( open-input-file \"data\" ) )\n > > ( read-line in )\n > \"hello\"\n > > ( close-input-port in )\n > ```\n If a file exists already, then [open-output-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._open-output-file%2529%2529&version=8.18.0.13) raises an exception by default. Supply an option like #:exists 'truncate or #:exists 'update to re-write or update the file:\n Examples:\n > ```racket\n > > ( define out ( open-output-file \"data\" #:exists ' truncate ) )\n > > ( display \"howdy\" out )\n > > ( close-output-port out )\n > ```"} {"text": "# 8.1 Varieties of Ports\n Instead of having to match the open calls with close calls, most Racket programmers will use the [call-with-input-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._call-with-input-file%2529%2529&version=8.18.0.13) and [call-with-output-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._call-with-output-file%2529%2529&version=8.18.0.13) functions which take a function to call to carry out the desired operation. This function gets as its only argument the port, which is automatically opened and closed for the operation.\n Examples:\n > ```racket\n > > ( call-with-output-file \"data\" #:exists ' truncate ( lambda ( out ) ( display \"hello\" out ) ) )\n > > ( call-with-input-file \"data\" ( lambda ( in ) ( read-line in ) ) )\n > \"hello\"\n > ```"} {"text": "# 8.1 Varieties of Ports\n- Strings: The [open-output-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stringport.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._open-output-string%2529%2529&version=8.18.0.13) function creates a port that accumulates data into a string, and [get-output-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stringport.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._get-output-string%2529%2529&version=8.18.0.13) extracts the accumulated string. The [open-input-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stringport.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._open-input-string%2529%2529&version=8.18.0.13) function creates a port to read from a string.\n Examples:\n > ```racket\n > > ( define p ( open-output-string ) )\n > > ( display \"hello\" p )\n > > ( get-output-string p )\n > \"hello\"\n > > ( read-line ( open-input-string \"goodbye\\nfarewell\" ) )\n > \"goodbye\"\n > ```"} {"text": "# 8.1 Varieties of Ports\n- TCP Connections: The [tcp-connect](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=tcp.html%23%2528def._%2528%2528lib._racket%252Ftcp..rkt%2529._tcp-connect%2529%2529&version=8.18.0.13) function creates both an input port and an output port for the client side of a TCP communication. The [tcp-listen](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=tcp.html%23%2528def._%2528%2528lib._racket%252Ftcp..rkt%2529._tcp-listen%2529%2529&version=8.18.0.13) function creates a server, which accepts connections via [tcp-accept](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=tcp.html%23%2528def._%2528%2528lib._racket%252Ftcp..rkt%2529._tcp-accept%2529%2529&version=8.18.0.13).\n Examples:\n > ```racket\n > > ( define server ( tcp-listen 12345 ) )\n > > ( define-values ( c-in c-out ) ( tcp-connect \"localhost\" 12345 ) )\n > > ( define-values ( s-in s-out ) ( tcp-accept server ) )\n > > ( display \"hello\\n\" c-out )\n > > ( close-output-port c-out )\n > > ( read-line s-in )\n > \"hello\"\n > > ( read-line s-in )\n > #\n > ```"} {"text": "# 8.1 Varieties of Ports\n- Process Pipes: The [subprocess](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=subprocess.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._subprocess%2529%2529&version=8.18.0.13) function runs a new process at the OS level and returns ports that correspond to the subprocess’s stdin, stdout, and stderr. (The first three arguments can be certain kinds of existing ports to connect directly to the subprocess, instead of creating new ports.)\n Examples:\n > ```racket\n > > ( define-values ( p stdout stdin stderr ) ( subprocess #f #f #f \"/usr/bin/wc\" \"-w\" ) )\n > > ( display \"a b c\\n\" stdin )\n > > ( close-output-port stdin )\n > > ( read-line stdout )\n > \" 3\"\n > > ( close-input-port stdout )\n > > ( close-input-port stderr )\n > ```\n- Internal Pipes: The [make-pipe](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pipeports.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._make-pipe%2529%2529&version=8.18.0.13) function returns two ports that are ends of a pipe. This kind of pipe is internal to Racket, and not related to OS-level pipes for communicating between different processes.\n Examples:\n > ```racket\n > > ( define-values ( in out ) ( make-pipe ) )\n > > ( display \"garbage\" out )\n > > ( close-output-port out )\n > > ( read-line in )\n > \"garbage\"\n > ```\n------------------------------------------------------------------------"} {"text": "# 8.2 Default Ports"} {"text": "### 8.2 Default Ports\nFor most simple I/O functions, the target port is an optional argument, and the default is the current input port or current output port. Furthermore, error messages are written to the current error port, which is an output port. The [current-input-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-ops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-input-port%2529%2529&version=8.18.0.13), [current-output-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-ops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-output-port%2529%2529&version=8.18.0.13), and [current-error-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-ops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._current-error-port%2529%2529&version=8.18.0.13) functions return the corresponding current ports.\nExamples:\n> ```racket\n> > ( display \"Hi\" )\n> Hi\n> > ( display \"Hi\" ( current-output-port ) ) ; the same\n> Hi\n> ```\nIf you start the racket program in a terminal, then the current input, output, and error ports are all connected to the terminal. More generally, they are connected to the OS-level stdin, stdout, and stderr. In this guide, the examples show output written to stdout in purple, and output written to stderr in red italics.\nExamples:"} {"text": "# 8.2 Default Ports\n> ```racket\n> ( define ( swing-hammer ) ( display \"Ouch!\" ( current-error-port ) ) )\n> > ( swing-hammer )\n> Ouch!\n> ```\nThe current-port functions are actually [parameters](parameterize.html#%28tech._parameter%29), which means that their values can be set with [parameterize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=parameters.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._parameterize%2529%2529&version=8.18.0.13).\n> > > See [Dynamic Binding: parameterize](parameterize.html) for an introduction to parameters.\nExample:\n> ```racket\n> > ( let ( [ s ( open-output-string ) ] ) ( parameterize ( [ current-error-port s ] ) ( swing-hammer ) ( swing-hammer ) ( swing-hammer ) ) ( get-output-string s ) )\n> \"Ouch!Ouch!Ouch!\"\n> ```\n------------------------------------------------------------------------"} {"text": "# 8.3 Reading and Writing Racket Data"} {"text": "### 8.3 Reading and Writing Racket Data\nAs noted throughout [Built-In Datatypes](datatypes.html), Racket provides three ways to print an instance of a built-in value:\n- [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13), which prints a value in the same way that is it printed for a [REPL](intro.html#%28tech._repl%29) result; and\n- [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13), which prints a value in such a way that [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13) on the output produces the value back; and"} {"text": "# 8.3 Reading and Writing Racket Data\n- [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13), which tends to reduce a value to just its character or byte content—at least for those datatypes that are primarily about characters or bytes, otherwise it falls back to the same output as [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13).\nHere are some examples using each:"} {"text": "# 8.3 Reading and Writing Racket Data\n```\n> ( print 1/2 )\n1/2\n> ( print #\\x )\n#\\x\n> ( print \"hello\" )\n\"hello\"\n> ( print #\"goodbye\" )\n#\"goodbye\"\n> ( print ' |pea pod| )\n'|pea pod|\n> ( print ' ( \"i\" pod ) )\n'(\"i\" pod)\n> ( print write )\n#   > ( write 1/2 )\n1/2\n> ( write #\\x )\n#\\x\n> ( write \"hello\" )\n\"hello\"\n> ( write #\"goodbye\" )\n#\"goodbye\"\n> ( write ' |pea pod| )\n|pea pod|\n> ( write ' ( \"i\" pod ) )\n(\"i\" pod)\n> ( write write )\n#   > ( display 1/2 )\n1/2\n> ( display #\\x )\nx\n> ( display \"hello\" )\nhello\n> ( display #\"goodbye\" )\ngoodbye\n> ( display ' |pea pod| )\npea pod\n> ( display ' ( \"i\" pod ) )\n(i pod)\n> ( display write )\n#```\n\n\nOverall, [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13) corresponds to the expression layer of Racket syntax, [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13) corresponds to the reader layer, and [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13) roughly corresponds to the character layer.\n\nThe [printf](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._printf%2529%2529&version=8.18.0.13) function supports simple formatting of data and text. In the format string supplied to [printf](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._printf%2529%2529&version=8.18.0.13), \\~a [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13)s the next argument, \\~s [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13)s the next argument, and \\~v [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13)s the next argument.\n\nExamples:\n\n> ```racket\n> ( define ( deliver who when what ) ( printf \"Items ~a for shopper ~s: ~v\" who when what ) )\n> > ( deliver ' ( \"list\" ) ' ( \"John\" ) ' ( \"milk\" ) )\n> Items (list) for shopper (\"John\"): '(\"milk\")\n> ```\n\nAfter using [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13), as opposed to [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13) or [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13), many forms of data can be read back in using [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13). The same values [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13)ed can also be parsed by [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13), but the result may have extra quote forms, since a [print](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._print%2529%2529&version=8.18.0.13)ed form is meant to be read like an expression.\n\nExamples:\n\n> ```racket\n> > ( define-values ( in out ) ( make-pipe ) )\n> > ( write \"hello\" out )\n> > ( read in )\n> \"hello\"\n> > ( write ' ( \"alphabet\" soup ) out )\n> > ( read in )\n> '(\"alphabet\" soup)\n> > ( write #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) out )\n> > ( read in )\n> '#hash((a . \"apple\") (b . \"banana\"))\n> > ( print ' ( \"alphabet\" soup ) out )\n> > ( read in )\n> ''(\"alphabet\" soup)\n> > ( display ' ( \"alphabet\" soup ) out )\n> > ( read in )\n> '(alphabet soup)\n> ```\n\n------------------------------------------------------------------------\n\n# 8.4 Datatypes and Serialization\n\n### 8.4 Datatypes and Serialization\n\n[Prefab](define-struct.html#%28tech._prefab%29) structure types (see [Prefab Structure Types](define-struct.html#%28part._prefab-struct%29)) automatically support serialization: they can be written to an output stream, and a copy can be read back in from an input stream:\n\n> ```racket\n> > ( define-values ( in out ) ( make-pipe ) )\n> > ( write #s ( sprout bean ) out )\n> > ( read in )\n> '#s(sprout bean)\n> ```\n\nOther structure types created by [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13), which offer more abstraction than [prefab](define-struct.html#%28tech._prefab%29) structure types, normally [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13) either using #\\<....> notation (for opaque structure types) or using #(....) vector notation (for transparent structure types). In neither case can the result be read back in as an instance of the structure type:\n\n> ```racket\n> > ( struct posn ( x y ) )\n> > ( write ( posn 1 2 ) )\n> #\n> > ( define-values ( in out ) ( make-pipe ) )\n> > ( write ( posn 1 2 ) out )\n> > ( read in )\n> pipe::1: read: bad syntax `#<`> ```\n\n> ```racket\n> > ( struct posn ( x y ) #:transparent )\n> > ( write ( posn 1 2 ) )\n> #(struct:posn 1 2)\n> > ( define-values ( in out ) ( make-pipe ) )\n> > ( write ( posn 1 2 ) out )\n> > ( define v ( read in ) )\n> > v\n> '#(struct:posn 1 2)\n> > ( posn? v )\n> #f\n> > ( vector? v )\n> #t\n> ```\n\nThe [serializable-struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528form._%2528%2528lib._racket%252Fserialize..rkt%2529._serializable-struct%2529%2529&version=8.18.0.13) form defines a structure type that can be [serialize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fserialize..rkt%2529._serialize%2529%2529&version=8.18.0.13)d to a value that can be printed using [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13) and restored via [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13). The [serialize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fserialize..rkt%2529._serialize%2529%2529&version=8.18.0.13)d result can be [deserialize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fserialize..rkt%2529._deserialize%2529%2529&version=8.18.0.13)d to get back an instance of the original structure type. The serialization form and functions are provided by the [racket/serialize](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html&version=8.18.0.13) library.\n\nExamples:\n\n> ```racket\n> > ( require racket/serialize )\n> > ( serializable-struct posn ( x y ) #:transparent )\n> > ( deserialize ( serialize ( posn 1 2 ) ) )\n> (posn 1 2)\n> > ( write ( serialize ( posn 1 2 ) ) )\n> ((3) 1 ((#f . deserialize-info:posn-v0)) 0 () () (0 1 2))\n> > ( define-values ( in out ) ( make-pipe ) )\n> > ( write ( serialize ( posn 1 2 ) ) out )\n> > ( deserialize ( read in ) )\n> (posn 1 2)\n> ```\n\nIn addition to the names bound by [struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define-struct.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._struct%2529%2529&version=8.18.0.13), [serializable-struct](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=serialization.html%23%2528form._%2528%2528lib._racket%252Fserialize..rkt%2529._serializable-struct%2529%2529&version=8.18.0.13) binds an identifier with deserialization information, and it automatically [provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._provide%2529%2529&version=8.18.0.13)s the deserialization identifier from a module context. This deserialization identifier is accessed reflectively when a value is deserialized.\n\n------------------------------------------------------------------------\n\n# 8.5 Bytes, Characters, and Encodings\n\n### 8.5 Bytes, Characters, and Encodings\n\nFunctions like [read-line](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-line%2529%2529&version=8.18.0.13), [read](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Reading.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read%2529%2529&version=8.18.0.13), [display](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._display%2529%2529&version=8.18.0.13), and [write](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Writing.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write%2529%2529&version=8.18.0.13) all work in terms of [characters](characters.html#%28tech._character%29) (which correspond to Unicode scalar values). Conceptually, they are implemented in terms of [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) and [write-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-char%2529%2529&version=8.18.0.13).\n\nMore primitively, ports read and write [bytes](bytestrings.html#%28tech._byte%29), instead of [characters](characters.html#%28tech._character%29). The functions [read-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-byte%2529%2529&version=8.18.0.13) and [write-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-byte%2529%2529&version=8.18.0.13) read and write raw bytes. Other functions, such as [read-bytes-line](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-bytes-line%2529%2529&version=8.18.0.13), build on top of byte operations instead of character operations.\n\nIn fact, the [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) and [write-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-char%2529%2529&version=8.18.0.13) functions are conceptually implemented in terms of [read-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-byte%2529%2529&version=8.18.0.13) and [write-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-byte%2529%2529&version=8.18.0.13). When a single byte’s value is less than 128, then it corresponds to an ASCII character. Any other byte is treated as part of a UTF-8 sequence, where UTF-8 is a particular standard way of encoding Unicode scalar values in bytes (which has the nice property that ASCII characters are encoded as themselves). Thus, a single [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) may call [read-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-byte%2529%2529&version=8.18.0.13) multiple times, and a single [write-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-char%2529%2529&version=8.18.0.13) may generate multiple output bytes.\n\nThe [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) and [write-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Output.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._write-char%2529%2529&version=8.18.0.13) operations always use a UTF-8 encoding. If you have a text stream that uses a different encoding, or if you want to generate a text stream in a different encoding, use [reencode-input-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._reencode-input-port%2529%2529&version=8.18.0.13) or [reencode-output-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._reencode-output-port%2529%2529&version=8.18.0.13). The [reencode-input-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._reencode-input-port%2529%2529&version=8.18.0.13) function converts an input stream from an encoding that you specify into a UTF-8 stream; that way, [read-char](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-char%2529%2529&version=8.18.0.13) sees UTF-8 encodings, even though the original used a different encoding. Beware, however, that [read-byte](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-byte%2529%2529&version=8.18.0.13) also sees the re-encoded data, instead of the original byte stream.\n\n------------------------------------------------------------------------\n\n# 8.6 I/O Patterns\n\n### 8.6 I/O Patterns\n\n> > > ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) racket/port) is needed for [#lang](Module_Syntax.html#%28part._hash-lang%29) [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13).\n\nFor these examples, say you have two files in the same directory as your program, \"oneline.txt\" and \"manylines.txt\".\n\n> \"oneline.txt\"\n>\n> > | |\n> > |------------------------------------------------------------|\n> > |  I am one line, but there is an empty line after this one. |\n> > |   |\n\n> \"manylines.txt\"\n>\n> > | |\n> > |--------------------------|\n> > |  I am |\n> > |  a message |\n> > |  split over a few lines. |\n> > |   |\n\nIf you have a file that is quite small, you can get away with reading in the file as a string:\n\nExamples:\n\n> ```racket\n> > ( define file-contents ( port->string ( open-input-file \"oneline.txt\" ) #:close? #t ) )\n> > ( string-suffix? file-contents \"after this one.\" )\n> #f\n> > ( string-suffix? file-contents \"after this one.\\n\" )\n> #t\n> > ( string-suffix? ( string-trim file-contents ) \"after this one.\" )\n> #t\n> ```\n\nWe use [port->string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._port-%7E3estring%2529%2529&version=8.18.0.13) from [racket/port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html&version=8.18.0.13) to do the reading to a string: the #:close? #t keyword argument ensures that our file is closed after the read.\n\nWe use [string-trim](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528def._%2528%2528lib._racket%252Fstring..rkt%2529._string-trim%2529%2529&version=8.18.0.13) from [racket/string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=strings.html%23%2528mod-path._racket%252Fstring%2529&version=8.18.0.13) to remove any extraneous whitespace at the very beginning and very end of our file. (Lots of formatters out there insist that text files end with a single blank line).\n\nSee also [read-line](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Byte_and_String_Input.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._read-line%2529%2529&version=8.18.0.13) if your file has one line of text.\n\nIf, instead, you want to process individual lines of a file, then you can use [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) with [in-lines](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-lines%2529%2529&version=8.18.0.13):\n\n> ```racket\n> > ( define ( upcase-all in ) ( for ( [ l ( in-lines in ) ] ) ( display ( string-upcase l ) ) ( newline ) ) )\n> > ( upcase-all ( open-input-string ( string-append \"Hello, World!\\n\" \"Can you hear me, now?\" ) ) )\n> HELLO, WORLD! CAN YOU HEAR ME, NOW?\n> ```\n\nYou could also combine computations over each line. So if you want to know how many lines contain “m”, you could do:\n\nExample:\n\n> ```racket\n> > ( with-input-from-file \"manylines.txt\" ( lambda ( ) ( for/sum ( [ l ( in-lines ) ] #:when ( string-contains? l \"m\" ) ) 1 ) ) )\n> 2\n> ```\n\nHere, [with-input-from-file](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=file-ports.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._with-input-from-file%2529%2529&version=8.18.0.13) from [racket/port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html&version=8.18.0.13) sets the default input port to be the file \"manylines.txt\" inside the thunk. It also closes the file after the computation has been completed (and in a few other cases).\n\nHowever, if you want to determine whether “hello” appears in a file, then you could search separate lines, but it’s even easier to simply apply a regular expression (see [Regular Expressions](regexp.html)) to the stream:\n\n> ```racket\n> > ( define ( has-hello? in ) ( regexp-match? #rx\"hello\" in ) )\n> > ( has-hello? ( open-input-string \"hello\" ) )\n> #t\n> > ( has-hello? ( open-input-string \"goodbye\" ) )\n> #f\n> ```\n\nIf you want to copy one port into another, use [copy-port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html%23%2528def._%2528%2528lib._racket%252Fport..rkt%2529._copy-port%2529%2529&version=8.18.0.13) from [racket/port](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=port-lib.html&version=8.18.0.13), which efficiently transfers large blocks when lots of data is available, but also transfers small blocks immediately if that’s all that is available:\n\n> ```racket\n> > ( define o ( open-output-string ) )\n> > ( copy-port ( open-input-string \"broom\" ) o )\n> > ( get-output-string o )\n> \"broom\"\n> ```\n\n------------------------------------------------------------------------\n\n# 9 Regular Expressions\n\n## 9 Regular Expressions\n\n> > > This chapter is a modified version of \\[[Sitaram05](doc-bibliography.html#%28cite._.Sitaram05%29)\\].\n\nA regexp value encapsulates a pattern that is described by a string or [byte string](bytestrings.html#%28tech._byte._string%29). The regexp matcher tries to match this pattern against (a portion of) another string or byte string, which we will call the text string, when you call functions like [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13). The text string is treated as raw text, and not as a pattern.\n\n| |\n|------------------------------------------------------------------------------------------------------------------------------------------------------------|\n|     [9.1 Writing Regexp Patterns](regexp-intro.html) |\n|     [9.2 Matching Regexp Patterns](regexp-match.html) |\n|     [9.3 Basic Assertions](regexp-assert.html) |\n|     [9.4 Characters and Character Classes](regexp-chars.html) |\n|       [9.4.1 Some Frequently Used Character Classes](regexp-chars.html#%28part._.Some_.Frequently_.Used_.Character_.Classes%29) |\n|       [9.4.2 POSIX character classes](regexp-chars.html#%28part._.P.O.S.I.X_character_classes%29) |\n|     [9.5 Quantifiers](regexp-quant.html) |\n|     [9.6 Clusters](regexp-clusters.html) |\n|       [9.6.1 Backreferences](regexp-clusters.html#%28part._.Backreferences%29) |\n|       [9.6.2 Non-capturing Clusters](regexp-clusters.html#%28part._.Non-capturing_.Clusters%29) |\n|       [9.6.3 Cloisters](regexp-clusters.html#%28part._regexp-cloister%29) |\n|     [9.7 Alternation](regexp-alternation.html) |\n|     [9.8 Backtracking](Backtracking.html) |\n|     [9.9 Looking Ahead and Behind](Looking_Ahead_and_Behind.html) |\n|       [9.9.1 Lookahead](Looking_Ahead_and_Behind.html#%28part._.Lookahead%29) |\n|       [9.9.2 Lookbehind](Looking_Ahead_and_Behind.html#%28part._.Lookbehind%29) |\n|     [9.10 An Extended Example](An_Extended_Example.html) |\n\n> > > \"+\"[Regular Expressions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on regexps.\n\n------------------------------------------------------------------------\n\n# 9.1 Writing Regexp Patterns\n\n### 9.1 Writing Regexp Patterns\n\nA string or [byte string](bytestrings.html#%28tech._byte._string%29) can be used directly as a [regexp](regexp.html#%28tech._regexp%29) pattern, or it can be prefixed with #rx to form a literal [regexp](regexp.html#%28tech._regexp%29) value. For example, #rx\"abc\" is a string-based [regexp](regexp.html#%28tech._regexp%29) value, and #rx#\"abc\" is a [byte string](bytestrings.html#%28tech._byte._string%29)-based [regexp](regexp.html#%28tech._regexp%29) value. Alternately, a string or byte string can be prefixed with #px, as in #px\"abc\", for a slightly extended syntax of patterns within the string.\n\nMost of the characters in a [regexp](regexp.html#%28tech._regexp%29) pattern are meant to match occurrences of themselves in the [text string](regexp.html#%28tech._text._string%29). Thus, the pattern #rx\"abc\" matches a string that contains the characters a, b, and c in succession. Other characters act as metacharacters, and some character sequences act as metasequences. That is, they specify something other than their literal selves. For example, in the pattern #rx\"a.c\", the characters a and c stand for themselves, but the [metacharacter](#%28tech._metacharacter%29) . can match any character. Therefore, the pattern #rx\"a.c\" matches an a, any character, and c in succession.\n\n> > > When we want a literal \\\\ inside a Racket string or regexp literal, we must escape it so that it shows up in the string at all. Racket strings use \\\\ as the escape character, so we end up with two \\\\s: one Racket-string \\\\ to escape the regexp \\\\, which then escapes the .. Another character that would need escaping inside a Racket string is \".\n\nIf we needed to match the character . itself, we can escape it by preceding it with a \\\\. The character sequence \\\\. is thus a [metasequence](#%28tech._metasequence%29), since it doesn’t match itself but rather just .. So, to match a, ., and c in succession, we use the regexp pattern #rx\"a\\\\\\\\.c\"; the double \\\\ is an artifact of Racket strings, not the [regexp](regexp.html#%28tech._regexp%29) pattern itself.\n\nThe [regexp](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp%2529%2529&version=8.18.0.13) function takes a string or byte string and produces a [regexp](regexp.html#%28tech._regexp%29) value. Use [regexp](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp%2529%2529&version=8.18.0.13) when you construct a pattern to be matched against multiple strings, since a pattern is compiled to a [regexp](regexp.html#%28tech._regexp%29) value before it can be used in a match. The [pregexp](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._pregexp%2529%2529&version=8.18.0.13) function is like [regexp](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp%2529%2529&version=8.18.0.13), but using the extended syntax. Regexp values as literals with #rx or #px are compiled once and for all when they are read.\n\nThe [regexp-quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-quote%2529%2529&version=8.18.0.13) function takes an arbitrary string and returns a string for a pattern that matches exactly the original string. In particular, characters in the input string that could serve as regexp metacharacters are escaped with a backslash, so that they safely match only themselves.\n\n> ```racket\n> > ( regexp-quote \"cons\" )\n> \"cons\"\n> > ( regexp-quote \"list?\" )\n> \"list\\\\?\"\n> ```\n\nThe [regexp-quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-quote%2529%2529&version=8.18.0.13) function is useful when building a composite [regexp](regexp.html#%28tech._regexp%29) from a mix of [regexp](regexp.html#%28tech._regexp%29) strings and verbatim strings.\n\n------------------------------------------------------------------------\n\n# 9.2 Matching Regexp Patterns\n\n### 9.2 Matching Regexp Patterns\n\nThe [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13) function takes a [regexp](regexp.html#%28tech._regexp%29) pattern and a [text string](regexp.html#%28tech._text._string%29), and it returns a match if the regexp matches (some part of) the [text string](regexp.html#%28tech._text._string%29), or #f if the regexp did not match the string. A successful match produces a list of index pairs.\n\nExamples:\n\n> ```racket\n> > ( regexp-match-positions #rx\"brain\" \"bird\" )\n> #f\n> > ( regexp-match-positions #rx\"needle\" \"hay needle stack\" )\n> '((4 . 10))\n> ```\n\nIn the second example, the integers 4 and 10 identify the substring that was matched. The 4 is the starting (inclusive) index, and 10 the ending (exclusive) index of the matching substring:\n\n> ```racket\n> > ( substring \"hay needle stack\" 4 10 )\n> \"needle\"\n> ```\n\nIn this first example, [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13)’s return list contains only one index pair, and that pair represents the entire substring matched by the regexp. When we discuss [subpatterns](regexp-clusters.html#%28tech._subpattern%29) later, we will see how a single match operation can yield a list of [submatch](regexp-clusters.html#%28tech._submatch%29)es.\n\nThe [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13) function takes optional third and fourth arguments that specify the indices of the [text string](regexp.html#%28tech._text._string%29) within which the matching should take place.\n\n> ```racket\n> > ( regexp-match-positions #rx\"needle\" \"his needle stack -- my needle stack -- her needle stack\" 20 39 )\n> '((23 . 29))\n> ```\n\nNote that the returned indices are still reckoned relative to the full [text string](regexp.html#%28tech._text._string%29).\n\nThe [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13) function is like [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13), but instead of returning index pairs, it returns the matching substrings:\n\n> ```racket\n> > ( regexp-match #rx\"brain\" \"bird\" )\n> #f\n> > ( regexp-match #rx\"needle\" \"hay needle stack\" )\n> '(\"needle\")\n> ```\n\nWhen [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13) is used with byte-string regexp, the result is a matching byte substring:\n\n> ```racket\n> > ( regexp-match #rx#\"needle\" #\"hay needle stack\" )\n> '(#\"needle\")\n> ```\n\n> > > A byte-string regexp can be applied to a string, and a string regexp can be applied to a byte string. In both cases, the result is a byte string. Internally, all regexp matching is in terms of bytes, and a string regexp is expanded to a regexp that matches UTF-8 encodings of characters. For maximum efficiency, use byte-string matching instead of string, since matching bytes directly avoids UTF-8 encodings.\n\nIf you have data that is in a port, there’s no need to first read it into a string. Functions like [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13) can match on the port directly:\n\n> ```racket\n> > ( define-values ( i o ) ( make-pipe ) )\n> > ( write \"hay needle stack\" o )\n> > ( close-output-port o )\n> > ( regexp-match #rx#\"needle\" i )\n> '(#\"needle\")\n> ```\n\nThe [regexp-match?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%7E3f%2529%2529&version=8.18.0.13) function is like [regexp-match-positions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match-positions%2529%2529&version=8.18.0.13), but simply returns a boolean indicating whether the match succeeded:\n\n> ```racket\n> > ( regexp-match? #rx\"brain\" \"bird\" )\n> #f\n> > ( regexp-match? #rx\"needle\" \"hay needle stack\" )\n> #t\n> ```\n\nThe [regexp-split](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-split%2529%2529&version=8.18.0.13) function takes two arguments, a [regexp](regexp.html#%28tech._regexp%29) pattern and a text string, and it returns a list of substrings of the text string; the pattern identifies the delimiter separating the substrings.\n\n> ```racket\n> > ( regexp-split #rx\":\" \"/bin:/usr/bin:/usr/bin/X11:/usr/local/bin\" )\n> '(\"/bin\" \"/usr/bin\" \"/usr/bin/X11\" \"/usr/local/bin\")\n> > ( regexp-split #rx\" \" \"pea soup\" )\n> '(\"pea\" \"soup\")\n> ```\n\nIf the first argument matches empty strings, then the list of all the single-character substrings is returned.\n\n> ```racket\n> > ( regexp-split #rx\"\" \"smithereens\" )\n> '(\"\" \"s\" \"m\" \"i\" \"t\" \"h\" \"e\" \"r\" \"e\" \"e\" \"n\" \"s\" \"\")\n> ```\n\nThus, to identify one-or-more spaces as the delimiter, take care to use the regexp #rx\" +\", not #rx\" \\*\".\n\n> ```racket\n> > ( regexp-split #rx\" +\" \"split pea soup\" )\n> '(\"split\" \"pea\" \"soup\")\n> > ( regexp-split #rx\" *\" \"split pea soup\" )\n> '(\"\" \"s\" \"p\" \"l\" \"i\" \"t\" \"\" \"p\" \"e\" \"a\" \"\" \"s\" \"o\" \"u\" \"p\" \"\")\n> ```\n\nThe [regexp-replace](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-replace%2529%2529&version=8.18.0.13) function replaces the matched portion of the text string by another string. The first argument is the pattern, the second the text string, and the third is either the string to be inserted or a procedure to convert matches to the insert string.\n\n> ```racket\n> > ( regexp-replace #rx\"te\" \"liberte\" \"ty\" )\n> \"liberty\"\n> > ( regexp-replace #rx\".\" \"racket\" string-upcase )\n> \"Racket\"\n> ```\n\nIf the pattern doesn’t occur in the text string, the returned string is identical to the text string.\n\nThe [regexp-replace*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-replace%252A%2529%2529&version=8.18.0.13) function replaces all matches in the text string by the insert string:\n\n> ```racket\n> > ( regexp-replace* #rx\"te\" \"liberte egalite fraternite\" \"ty\" )\n> \"liberty egality fratyrnity\"\n> > ( regexp-replace* #rx\"[ds]\" \"drracket\" string-upcase )\n> \"Drracket\"\n> ```\n\n------------------------------------------------------------------------\n\n# 9.3 Basic Assertions\n\n### 9.3 Basic Assertions\n\nThe assertions ^ and $ identify the beginning and the end of the text string, respectively. They ensure that their adjoining regexps match at one or other end of the text string:\n\n> ```racket\n> > ( regexp-match-positions #rx\"^contact\" \"first contact\" )\n> #f\n> ```\n\nThe [regexp](regexp.html#%28tech._regexp%29) above fails to match because contact does not occur at the beginning of the text string. In\n\n> ```racket\n> > ( regexp-match-positions #rx\"laugh$\" \"laugh laugh laugh laugh\" )\n> '((18 . 23))\n> ```\n\nthe regexp matches the last laugh.\n\nThe metasequence \\\\b asserts that a word boundary exists, but this metasequence works only with #px syntax. In\n\n> ```racket\n> > ( regexp-match-positions #px\"yack\\\\b\" \"yackety yack\" )\n> '((8 . 12))\n> ```\n\nthe yack in yackety doesn’t end at a word boundary so it isn’t matched. The second yack does and is.\n\nThe metasequence \\\\B (also #px only) has the opposite effect to \\\\b; it asserts that a word boundary does not exist. In\n\n> ```racket\n> > ( regexp-match-positions #px\"an\\\\B\" \"an analysis\" )\n> '((3 . 5))\n> ```\n\nthe an that doesn’t end in a word boundary is matched.\n\n------------------------------------------------------------------------\n\n# 9.4 Characters and Character Classes\n\n### 9.4 Characters and Character Classes\n\nTypically, a character in the regexp matches the same character in the text string. Sometimes it is necessary or convenient to use a regexp [metasequence](regexp-intro.html#%28tech._metasequence%29) to refer to a single character. For example, the metasequence \\\\. matches the period character.\n\nThe [metacharacter](regexp-intro.html#%28tech._metacharacter%29) . matches any character (other than newline in [multi-line mode](regexp-clusters.html#%28tech._multi._line._mode%29); see [Cloisters](regexp-clusters.html#%28part._regexp-cloister%29)):\n\n> ```racket\n> > ( regexp-match #rx\"p.t\" \"pet\" )\n> '(\"pet\")\n> ```\n\nThe above pattern also matches pat, pit, pot, put, and p8t, but not peat or pfffft.\n\nA character class matches any one character from a set of characters. A typical format for this is the bracketed character class \\[...\\], which matches any one character from the non-empty sequence of characters enclosed within the brackets. Thus, #rx\"p\\[aeiou\\]t\" matches pat, pet, pit, pot, put, and nothing else.\n\nInside the brackets, a - between two characters specifies the Unicode range between the characters. For example, #rx\"ta\\[b-dgn-p\\]\" matches tab, tac, tad, tag, tan, tao, and tap.\n\nAn initial ^ after the left bracket inverts the set specified by the rest of the contents; i.e., it specifies the set of characters other than those identified in the brackets. For example, #rx\"do\\[^g\\]\" matches all three-character sequences starting with do except dog.\n\nNote that the [metacharacter](regexp-intro.html#%28tech._metacharacter%29) ^ inside brackets means something quite different from what it means outside. Most other [metacharacters](regexp-intro.html#%28tech._metacharacter%29) (., \\*, +, ?, etc.) cease to be [metacharacters](regexp-intro.html#%28tech._metacharacter%29) when inside brackets, although you may still escape them for peace of mind. A - is a [metacharacter](regexp-intro.html#%28tech._metacharacter%29) only when it’s inside brackets, and when it is neither the first nor the last character between the brackets.\n\nBracketed character classes cannot contain other bracketed character classes (although they contain certain other types of character classes; see below). Thus, a \\[ inside a bracketed character class doesn’t have to be a metacharacter; it can stand for itself. For example, #rx\"\\[a\\[b\\]\" matches a, \\[, and b.\n\nFurthermore, since empty bracketed character classes are disallowed, a \\] immediately occurring after the opening left bracket also doesn’t need to be a metacharacter. For example, #rx\"\\[\\]ab\\]\" matches \\], a, and b.\n\n#### 9.4.1 Some Frequently Used Character Classes\n\nIn #px syntax, some standard character classes can be conveniently represented as metasequences instead of as explicit bracketed expressions: \\\\d matches a digit (the same as \\[0-9\\]); \\\\s matches an ASCII whitespace character; and \\\\w matches a character that could be part of a “word”.\n\n> > > Following regexp custom, we identify “word” characters as \\[A-Za-z0-9\\_\\], although these are too restrictive for what a Racketeer might consider a “word.”\n\nThe upper-case versions of these metasequences stand for the inversions of the corresponding character classes: \\\\D matches a non-digit, \\\\S a non-whitespace character, and \\\\W a non-“word” character.\n\nRemember to include a double backslash when putting these metasequences in a Racket string:\n\n> ```racket\n> > ( regexp-match #px\"\\\\d\\\\d\" \"0 dear, 1 have 2 read catch 22 before 9\" )\n> '(\"22\")\n> ```\n\nThese character classes can be used inside a bracketed expression. For example, #px\"\\[a-z\\\\\\\\d\\]\" matches a lower-case letter or a digit.\n\n#### 9.4.2 POSIX character classes\n\nA POSIX character class is a special [metasequence](regexp-intro.html#%28tech._metasequence%29) of the form \\[:...:\\] that can be used only inside a bracketed expression in #px syntax. The POSIX classes supported are\n\n- \\[:alnum:\\] — ASCII letters and digits\n\n- \\[:alpha:\\] — ASCII letters\n\n- \\[:ascii:\\] — ASCII characters\n\n- \\[:blank:\\] — ASCII widthful whitespace: space and tab\n\n- \\[:cntrl:\\] — “control” characters: ASCII 0 to 31\n\n- \\[:digit:\\] — ASCII digits, same as \\\\d\n\n- \\[:graph:\\] — ASCII characters that use ink\n\n- \\[:lower:\\] — ASCII lower-case letters\n\n- \\[:print:\\] — ASCII ink-users plus widthful whitespace\n\n- \\[:space:\\] — ASCII whitespace, same as \\\\s\n\n- \\[:upper:\\] — ASCII upper-case letters\n\n- \\[:word:\\] — ASCII letters and \\_, same as \\\\w\n\n- \\[:xdigit:\\] — ASCII hex digits\n\nFor example, the #px\"\\[\\[:alpha:\\]\\_\\]\" matches a letter or underscore.\n\n> ```racket\n> > ( regexp-match #px\"[[:alpha:]_]\" \"--x--\" )\n> '(\"x\")\n> > ( regexp-match #px\"[[:alpha:]_]\" \"--_--\" )\n> '(\"_\")\n> > ( regexp-match #px\"[[:alpha:]_]\" \"--:--\" )\n> #f\n> ```\n\nThe POSIX class notation is valid only inside a bracketed expression. For instance, \\[:alpha:\\], when not inside a bracketed expression, will not be read as the letter class. Rather, it is (from previous principles) the character class containing the characters :, a, l, p, h.\n\n> ```racket\n> > ( regexp-match #px\"[:alpha:]\" \"--a--\" )\n> '(\"a\")\n> > ( regexp-match #px\"[:alpha:]\" \"--x--\" )\n> #f\n> ```\n\n------------------------------------------------------------------------\n\n# 9.5 Quantifiers\n\n### 9.5 Quantifiers\n\nThe quantifiers \\*, +, and ? match respectively: zero or more, one or more, and zero or one instances of the preceding subpattern.\n\n> ```racket\n> > ( regexp-match-positions #rx\"c[ad]*r\" \"cadaddadddr\" )\n> '((0 . 11))\n> > ( regexp-match-positions #rx\"c[ad]*r\" \"cr\" )\n> '((0 . 2))\n> > ( regexp-match-positions #rx\"c[ad]+r\" \"cadaddadddr\" )\n> '((0 . 11))\n> > ( regexp-match-positions #rx\"c[ad]+r\" \"cr\" )\n> #f\n> > ( regexp-match-positions #rx\"c[ad]?r\" \"cadaddadddr\" )\n> #f\n> > ( regexp-match-positions #rx\"c[ad]?r\" \"cr\" )\n> '((0 . 2))\n> > ( regexp-match-positions #rx\"c[ad]?r\" \"car\" )\n> '((0 . 3))\n> ```\n\nIn #px syntax, you can use braces to specify much finer-tuned quantification than is possible with \\*, +, ?:\n\n- The quantifier {m} matches exactly m instances of the preceding [subpattern](regexp-clusters.html#%28tech._subpattern%29); m must be a nonnegative integer.\n\n- The quantifier {m,n} matches at least m and at most n instances. m and n are nonnegative integers with m less or equal to n. You may omit either or both numbers, in which case m defaults to 0 and n to infinity.\n\nIt is evident that + and ? are abbreviations for {1,} and {0,1} respectively, and \\* abbreviates {,}, which is the same as {0,}.\n\n> ```racket\n> > ( regexp-match #px\"[aeiou]{3}\" \"vacuous\" )\n> '(\"uou\")\n> > ( regexp-match #px\"[aeiou]{3}\" \"evolve\" )\n> #f\n> > ( regexp-match #px\"[aeiou]{2,3}\" \"evolve\" )\n> #f\n> > ( regexp-match #px\"[aeiou]{2,3}\" \"zeugma\" )\n> '(\"eu\")\n> ```\n\nThe quantifiers described so far are all greedy: they match the maximal number of instances that would still lead to an overall match for the full pattern.\n\n> ```racket\n> > ( regexp-match #rx\"<.*>\" \" \" )\n> '(\" \")\n> ```\n\nTo make these quantifiers non-greedy, append a ? to them. Non-greedy quantifiers match the minimal number of instances needed to ensure an overall match.\n\n> ```racket\n> > ( regexp-match #rx\"<.*?>\" \" \" )\n> '(\"\")\n> ```\n\nThe non-greedy quantifiers are \\*?, +?, ??, {m}?, and {m,n}?, although {m}? is always the same as {m}. Note that the metacharacter ? has two different uses, and both uses are represented in ??.\n\n------------------------------------------------------------------------\n\n# 9.6 Clusters\n\n### 9.6 Clusters\n\nClustering—enclosure within parens (...)—identifies the enclosed subpattern as a single entity. It causes the matcher to capture the submatch, or the portion of the string matching the subpattern, in addition to the overall match:\n\n> ```racket\n> > ( regexp-match #rx\"([a-z]+) ([0-9]+), ([0-9]+)\" \"jan 1, 1970\" )\n> '(\"jan 1, 1970\" \"jan\" \"1\" \"1970\")\n> ```\n\nClustering also causes a following quantifier to treat the entire enclosed subpattern as an entity:\n\n> ```racket\n> > ( regexp-match #rx\"(pu )*\" \"pu pu platter\" )\n> '(\"pu pu \" \"pu \")\n> ```\n\nThe number of submatches returned is always equal to the number of subpatterns specified in the regexp, even if a particular subpattern happens to match more than one substring or no substring at all.\n\n> ```racket\n> > ( regexp-match #rx\"([a-z ]+;)*\" \"lather; rinse; repeat;\" )\n> '(\"lather; rinse; repeat;\" \" repeat;\")\n> ```\n\nHere, the \\*-quantified subpattern matches three times, but it is the last submatch that is returned.\n\nIt is also possible for a quantified subpattern to fail to match, even if the overall pattern matches. In such cases, the failing submatch is represented by #f\n\n> ```racket\n> > ( define date-re ; match ‘ month year ' or ‘ month day, year ' ; ; subpattern matches day, if present #rx\"([a-z]+) +([0-9]+,)? *([0-9]+)\" )\n> > ( regexp-match date-re \"jan 1, 1970\" )\n> '(\"jan 1, 1970\" \"jan\" \"1,\" \"1970\")\n> > ( regexp-match date-re \"jan 1970\" )\n> '(\"jan 1970\" \"jan\" #f \"1970\")\n> ```\n\n#### 9.6.1 Backreferences\n\n[Submatch](#%28tech._submatch%29)es can be used in the insert string argument of the procedures [regexp-replace](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-replace%2529%2529&version=8.18.0.13) and [regexp-replace*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._regexp-replace%252A%2529%2529&version=8.18.0.13). The insert string can use \\\\n as a backreference to refer back to the nth submatch, which is the substring that matched the nth subpattern. A \\\\0 refers to the entire match, and it can also be specified as \\\\&.\n\n> ```racket\n> > ( regexp-replace #rx\"_(.+?)_\" \"the _nina_, the _pinta_, and the _santa maria_\" \"*\\\\1*\" )\n> \"the *nina*, the _pinta_, and the _santa maria_\"\n> > ( regexp-replace* #rx\"_(.+?)_\" \"the _nina_, the _pinta_, and the _santa maria_\" \"*\\\\1*\" )\n> \"the *nina*, the *pinta*, and the *santa maria*\"\n> > ( regexp-replace #px\"(\\\\S+) (\\\\S+) (\\\\S+)\" \"eat to live\" \"\\\\3 \\\\2 \\\\1\" )\n> \"live to eat\"\n> ```\n\nUse \\\\\\\\ in the insert string to specify a literal backslash. Also, \\\\$ stands for an empty string, and is useful for separating a backreference \\\\n from an immediately following number.\n\nBackreferences can also be used within a #px pattern to refer back to an already matched subpattern in the pattern. \\\\n stands for an exact repeat of the nth submatch. Note that \\\\0, which is useful in an insert string, makes no sense within the regexp pattern, because the entire regexp has not matched yet so you cannot refer back to it.}\n\n> ```racket\n> > ( regexp-match #px\"([a-z]+) and \\\\1\" \"billions and billions\" )\n> '(\"billions and billions\" \"billions\")\n> ```\n\nNote that the [backreference](#%28tech._backreference%29) is not simply a repeat of the previous subpattern. Rather it is a repeat of the particular substring already matched by the subpattern.\n\nIn the above example, the [backreference](#%28tech._backreference%29) can only match billions. It will not match millions, even though the subpattern it harks back to—(\\[a-z\\]+)—would have had no problem doing so:\n\n> ```racket\n> > ( regexp-match #px\"([a-z]+) and \\\\1\" \"billions and millions\" )\n> #f\n> ```\n\nThe following example marks all immediately repeating patterns in a number string:\n\n> ```racket\n> > ( regexp-replace* #px\"(\\\\d+)\\\\1\" \"123340983242432420980980234\" \"{\\\\1,\\\\1}\" )\n> \"12{3,3}40983{24,24}3242{098,098}0234\"\n> ```\n\nThe following example corrects doubled words:\n\n> ```racket\n> > ( regexp-replace* #px\"\\\\b(\\\\S+) \\\\1\\\\b\" ( string-append \"now is the the time for all good men to \" \"to come to the aid of of the party\" ) \"\\\\1\" )\n> \"now is the time for all good men to come to the aid of the party\"\n> ```\n\n#### 9.6.2 Non-capturing Clusters\n\nIt is often required to specify a cluster (typically for quantification) but without triggering the capture of [submatch](#%28tech._submatch%29) information. Such clusters are called non-capturing. To create a non-capturing cluster, use (?: instead of ( as the cluster opener.\n\nIn the following example, a non-capturing cluster eliminates the “directory” portion of a given Unix pathname, and a capturing cluster identifies the basename.\n\n> > > But don’t parse paths with regexps. Use functions like [split-path](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Manipulating_Paths.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._split-path%2529%2529&version=8.18.0.13), instead.\n\n> ```racket\n> > ( regexp-match #rx\"^(?:[a-z]*/)*([a-z]+)$\" \"/usr/local/bin/racket\" )\n> '(\"/usr/local/bin/racket\" \"racket\")\n> ```\n\n#### 9.6.3 Cloisters\n\nThe location between the ? and the : of a non-capturing cluster is called a cloister. You can put modifiers there that will cause the enclustered [subpattern](#%28tech._subpattern%29) to be treated specially. The modifier i causes the subpattern to match case-insensitively:\n\n> > > The term cloister is a useful, if terminally cute, coinage from the abbots of Perl.\n\n> ```racket\n> > ( regexp-match #rx\"(?i:hearth)\" \"HeartH\" )\n> '(\"HeartH\")\n> ```\n\nThe modifier m causes the [subpattern](#%28tech._subpattern%29) to match in multi-line mode, where . does not match a newline character, ^ can match just after a newline, and $ can match just before a newline.\n\n> ```racket\n> > ( regexp-match #rx\".\" \"\\na\\n\" )\n> '(\"\\n\")\n> > ( regexp-match #rx\"(?m:.)\" \"\\na\\n\" )\n> '(\"a\")\n> > ( regexp-match #rx\"^A plan$\" \"A man\\nA plan\\nA canal\" )\n> #f\n> > ( regexp-match #rx\"(?m:^A plan$)\" \"A man\\nA plan\\nA canal\" )\n> '(\"A plan\")\n> ```\n\nYou can put more than one modifier in the cloister:\n\n> ```racket\n> > ( regexp-match #rx\"(?mi:^A Plan$)\" \"a man\\na plan\\na canal\" )\n> '(\"a plan\")\n> ```\n\nA minus sign before a modifier inverts its meaning. Thus, you can use -i in a subcluster to overturn the case-insensitivities caused by an enclosing cluster.\n\n> ```racket\n> > ( regexp-match #rx\"(?i:the (?-i:TeX)book)\" \"The TeXbook\" )\n> '(\"The TeXbook\")\n> ```\n\nThe above regexp will allow any casing for the and book, but it insists that TeX not be differently cased.\n\n------------------------------------------------------------------------\n\n# 9.7 Alternation\n\n### 9.7 Alternation\n\nYou can specify a list of alternate [subpatterns](regexp-clusters.html#%28tech._subpattern%29) by separating them by \\|. The \\| separates [subpatterns](regexp-clusters.html#%28tech._subpattern%29) in the nearest enclosing cluster (or in the entire pattern string if there are no enclosing parens).\n\n> ```racket\n> > ( regexp-match #rx\"f(ee|i|o|um)\" \"a small, final fee\" )\n> '(\"fi\" \"i\")\n> > ( regexp-replace* #rx\"([yi])s(e[sdr]?|ing|ation)\" ( string-append \"analyse an energising organisation\" \" pulsing with noisy organisms\" ) \"\\\\1z\\\\2\" )\n> \"analyze an energizing organization pulsing with noisy organisms\"\n> ```\n\nNote again that if you wish to use clustering merely to specify a list of alternate subpatterns but do not want the submatch, use (?: instead of (.\n\n> ```racket\n> > ( regexp-match #rx\"f(?:ee|i|o|um)\" \"fun for all\" )\n> '(\"fo\")\n> ```\n\nAn important thing to note about alternation is that the leftmost matching alternate is picked regardless of its length. Thus, if one of the alternates is a prefix of a later alternate, the latter may not have a chance to match.\n\n> ```racket\n> > ( regexp-match #rx\"call|call-with-current-continuation\" \"call-with-current-continuation\" )\n> '(\"call\")\n> ```\n\nTo allow the longer alternate to have a shot at matching, place it before the shorter one:\n\n> ```racket\n> > ( regexp-match #rx\"call-with-current-continuation|call\" \"call-with-current-continuation\" )\n> '(\"call-with-current-continuation\")\n> ```\n\nIn any case, an overall match for the entire regexp is always preferred to an overall non-match. In the following, the longer alternate still wins, because its preferred shorter prefix fails to yield an overall match.\n\n> ```racket\n> > ( regexp-match #rx\"(?:call|call-with-current-continuation) constrained\" \"call-with-current-continuation constrained\" )\n> '(\"call-with-current-continuation constrained\")\n> ```\n\n------------------------------------------------------------------------\n\n# 9.8 Backtracking\n\n### 9.8 Backtracking\n\nWe’ve already seen that greedy quantifiers match the maximal number of times, but the overriding priority is that the overall match succeed. Consider\n\n> ```racket\n> > ( regexp-match #rx\"a*a\" \"aaaa\" )\n> '(\"aaaa\")\n> ```\n\nThe regexp consists of two subregexps: a\\* followed by a. The subregexp a\\* cannot be allowed to match all four a’s in the text string aaaa, even though \\* is a greedy quantifier. It may match only the first three, leaving the last one for the second subregexp. This ensures that the full regexp matches successfully.\n\nThe regexp matcher accomplishes this via a process called backtracking. The matcher tentatively allows the greedy quantifier to match all four a’s, but then when it becomes clear that the overall match is in jeopardy, it backtracks to a less greedy match of three a’s. If even this fails, as in the call\n\n> ```racket\n> > ( regexp-match #rx\"a*aa\" \"aaaa\" )\n> '(\"aaaa\")\n> ```\n\nthe matcher backtracks even further. Overall failure is conceded only when all possible backtracking has been tried with no success.\n\nBacktracking is not restricted to greedy quantifiers. Nongreedy quantifiers match as few instances as possible, and progressively backtrack to more and more instances in order to attain an overall match. There is backtracking in alternation too, as the more rightward alternates are tried when locally successful leftward ones fail to yield an overall match.\n\nSometimes it is efficient to disable backtracking. For example, we may wish to commit to a choice, or we know that trying alternatives is fruitless. A nonbacktracking regexp is enclosed in (?>...).\n\n> ```racket\n> > ( regexp-match #rx\"(?>a+).\" \"aaaa\" )\n> #f\n> ```\n\nIn this call, the subregexp ?>a+ greedily matches all four a’s, and is denied the opportunity to backtrack. So, the overall match is denied. The effect of the regexp is therefore to match one or more a’s followed by something that is definitely non-a.\n\n------------------------------------------------------------------------\n\n# 9.9 Looking Ahead and Behind\n\n### 9.9 Looking Ahead and Behind\n\nYou can have assertions in your pattern that look ahead or behind to ensure that a subpattern does or does not occur. These “look around” assertions are specified by putting the subpattern checked for in a cluster whose leading characters are: ?= (for positive lookahead), ?! (negative lookahead), ?\\<= (positive lookbehind), ?\\ ```racket\n> > ( regexp-match-positions #rx\"grey(?=hound)\" \"i left my grey socks at the greyhound\" )\n> '((28 . 32))\n> ```\n\nThe regexp #rx\"grey(?=hound)\" matches grey, but only if it is followed by hound. Thus, the first grey in the text string is not matched.\n\nNegative lookahead with ?! peeks ahead to ensure that its subpattern could not possibly match.\n\n> ```racket\n> > ( regexp-match-positions #rx\"grey(?!hound)\" \"the gray greyhound ate the grey socks\" )\n> '((27 . 31))\n> ```\n\nThe regexp #rx\"grey(?!hound)\" matches grey, but only if it is not followed by hound. Thus the grey just before socks is matched.\n\n#### 9.9.2 Lookbehind\n\nPositive lookbehind with ?\\<= checks that its subpattern could match immediately to the left of the current position in the text string.> ```racket\n> > ( regexp-match-positions #rx\"(?<=grey)hound\" \"the hound in the picture is not a greyhound\" )> '((38 . 43))\n> ```\n\nThe regexp #rx\"(?\\<=grey)hound\" matches hound, but only if it is preceded by grey.\n\nNegative lookbehind with ?\\ ```racket\n> > ( regexp-match-positions #rx\"(? '((38 . 43))\n> ```\n\nThe regexp #rx\"(?\\ ```racket\n> > ( define n0-255 ( string-append \"(?:\" \"\\\\d|\" ; 0 through 9 \"\\\\d\\\\d|\" ; 00 through 99 \"[01]\\\\d\\\\d|\" ; 000 through 199 \"2[0-4]\\\\d|\" ; 200 through 249 \"25[0-5]\" ; 250 through 255 \")\" ) )\n> ```\n\n> > > Note that n0-255 lists prefixes as preferred alternates, which is something we cautioned against in [Alternation](regexp-alternation.html). However, since we intend to anchor this subregexp explicitly to force an overall match, the order of the alternates does not matter.\n\nThe first two alternates simply get all single- and double-digit numbers. Since 0-padding is allowed, we need to match both 1 and 01. We need to be careful when getting 3-digit numbers, since numbers above 255 must be excluded. So we fashion alternates to get 000 through 199, then 200 through 249, and finally 250 through 255.\n\nAn IP-address is a string that consists of four n0-255s with three dots separating them.\n\n> ```racket\n> > ( define ip-re1 ( string-append \"^\" ; nothing before n0-255 ; the first n0-255 , \"(?:\" ; then the subpattern of \"\\\\.\" ; a dot followed by n0-255 ; an n0-255 , \")\" ; which is \"{3}\" ; repeated exactly 3 times \"$\" ) )\n> ; with nothing following\n> ```\n\nLet’s try it out:\n\n> ```racket\n> > ( regexp-match ( pregexp ip-re1 ) \"1.2.3.4\" )\n> '(\"1.2.3.4\")\n> > ( regexp-match ( pregexp ip-re1 ) \"55.155.255.265\" )\n> #f\n> ```\n\nwhich is fine, except that we also have\n\n> ```racket\n> > ( regexp-match ( pregexp ip-re1 ) \"0.00.000.00\" )\n> '(\"0.00.000.00\")\n> ```\n\nAll-zero sequences are not valid IP addresses! Lookahead to the rescue. Before starting to match ip-re1, we look ahead to ensure we don’t have all zeros. We could use positive lookahead to ensure there is a digit other than zero.\n\n> ```racket\n> > ( define ip-re ( pregexp ( string-append \"(?=.*[1-9])\" ; ensure there ' s a non-0 digit ip-re1 ) ) )\n> ```\n\nOr we could use negative lookahead to ensure that what’s ahead isn’t composed of only zeros and dots.\n\n> ```racket\n> > ( define ip-re ( pregexp ( string-append \"(?![0.]*$)\" ; not just zeros and dots ; (note: . is not metachar inside [ ... ] ) ip-re1 ) ) )\n> ```\n\nThe regexp ip-re will match all and only valid IP addresses.\n\n> ```racket\n> > ( regexp-match ip-re \"1.2.3.4\" )\n> '(\"1.2.3.4\")\n> > ( regexp-match ip-re \"0.0.0.0\" )\n> #f\n> ```\n\n------------------------------------------------------------------------\n\n# 10 Exceptions and Control\n\n## 10 Exceptions and Control\n\nRacket provides an especially rich set of control operations—not only operations for raising and catching exceptions, but also operations for grabbing and restoring portions of a computation.\n\n| |\n|-----------------------------------------------------------------------|\n|     [10.1 Exceptions](exns.html) |\n|     [10.2 Prompts and Aborts](prompt.html) |\n|     [10.3 Continuations](conts.html) |\n\n------------------------------------------------------------------------\n\n# 10.1 Exceptions\n\n### 10.1 Exceptions\n\nWhenever a run-time error occurs, an exception is raised. Unless the exception is caught, then it is handled by printing a message associated with the exception, and then escaping from the computation.\n\n> ```racket\n> > ( / 1 0 )\n> /: division by zero\n> > ( car 17 )\n> car: contract violation\n> expected: pair?\n> given: 17\n> ```\n\nTo catch an exception, use the [with-handlers](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=exns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmore-scheme..rkt%2529._with-handlers%2529%2529&version=8.18.0.13) form:\n\n> > ```\n(with-handlers ([predicate-expr handler-expr] ...)\n> > body ...+ )\n```"} {"text": "# 8.3 Reading and Writing Racket Data\n(v)\t→\t\n(-> with-handlers ([ exn:fail? (lambda (v) ((error-display-handler) (exn-message v) v)) ]) (car 17))```\nA [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) loop iterates through the sequence produced by the sequence-expr. For each element of the sequence, [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) binds the element to id, and then it evaluates the bodys for side effects.\nExamples:\n> ```racket\n> > ( for ( [ i ' ( 1 2 3 ) ] ) ( display i ) )\n> 123\n> > ( for ( [ i \"abc\" ] ) ( printf \"~a...\" i ) )\n> a...b...c...\n> > ( for ( [ i 4 ] ) ( display i ) )\n> 0123\n> ```"} {"text": "# 8.3 Reading and Writing Racket Data\nThe [for/list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252Flist%2529%2529&version=8.18.0.13) variant of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) is more Racket-like. It accumulates body results into a list, instead of evaluating body only for side effects. In more technical terms, [for/list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252Flist%2529%2529&version=8.18.0.13) implements a list comprehension.\nExamples:\n> ```racket\n> > ( for/list ( [ i ' ( 1 2 3 ) ] ) ( * i i ) )\n> '(1 4 9)\n> > ( for/list ( [ i \"abc\" ] ) i )\n> '(#\\a #\\b #\\c)\n> > ( for/list ( [ i 4 ] ) i )\n> '(0 1 2 3)\n> ```"} {"text": "# 8.3 Reading and Writing Racket Data\nThe full syntax of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) accommodates multiple sequences to iterate in parallel, and the [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13) variant nests the iterations instead of running them in parallel. More variants of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) and [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13) accumulate body results in different ways. In all of these variants, predicates that prune iterations can be included along with bindings."} {"text": "# 8.3 Reading and Writing Racket Data\nBefore details on the variations of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13), though, it’s best to see the kinds of sequence generators that make interesting examples."} {"text": "### 11.1 Sequence Constructors\nThe [in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13) function generates a sequence of numbers, given an optional starting number (which defaults to 0), a number before which the sequence ends, and an optional step (which defaults to 1). Using a non-negative integer k directly as a sequence is a shorthand for ([in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13) k).\nExamples:\n> ```racket\n> > ( for ( [ i 3 ] ) ( display i ) )\n> 012\n> > ( for ( [ i ( in-range 3 ) ] ) ( display i ) )\n> 012\n> > ( for ( [ i ( in-range 1 4 ) ] ) ( display i ) )\n> 123\n> > ( for ( [ i ( in-range 1 4 2 ) ] ) ( display i ) )\n> 13\n> > ( for ( [ i ( in-range 4 1 -1 ) ] ) ( display i ) )\n> 432\n> > ( for ( [ i ( in-range 1 4 1/2 ) ] ) ( printf \" ~a \" i ) )\n> 1 3/2 2 5/2 3 7/2\n> ```"} {"text": "### 11.1 Sequence Constructors\nThe [in-naturals](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-naturals%2529%2529&version=8.18.0.13) function is similar, except that the starting number must be an exact non-negative integer (which defaults to 0), the step is always 1, and there is no upper limit. A [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) loop using just [in-naturals](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-naturals%2529%2529&version=8.18.0.13) will never terminate unless a body expression raises an exception or otherwise escapes.\nExample:\n> ```racket\n> > ( for ( [ i ( in-naturals ) ] ) ( if ( = i 10 ) ( error \"too much!\" ) ( display i ) ) )\n> 0123456789\n> too much!\n> ```"} {"text": "### 11.1 Sequence Constructors\nThe [stop-before](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-before%2529%2529&version=8.18.0.13) and [stop-after](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-after%2529%2529&version=8.18.0.13) functions construct a new sequence given a sequence and a predicate. The new sequence is like the given sequence, but truncated either immediately before or immediately after the first element for which the predicate returns true.\nExample:\n> ```racket\n> > ( for ( [ i ( stop-before \"abc def\" char-whitespace? ) ] ) ( display i ) )\n> abc\n> ```"} {"text": "### 11.1 Sequence Constructors\nSequence constructors like [in-list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-list%2529%2529&version=8.18.0.13), [in-vector](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-vector%2529%2529&version=8.18.0.13) and [in-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-string%2529%2529&version=8.18.0.13) simply make explicit the use of a list, vector, or string as a sequence. Along with [in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13), these constructors raise an exception when given the wrong kind of value, and since they otherwise avoid a run-time dispatch to determine the sequence type, they enable more efficient code generation; see [Iteration Performance](#%28part._for-performance%29) for more information.\nExamples:"} {"text": "### 11.1 Sequence Constructors\n> ```racket\n> > ( for ( [ i ( in-string \"abc\" ) ] ) ( display i ) )\n> abc\n> > ( for ( [ i ( in-string ' ( 1 2 3 ) ) ] ) ( display i ) )\n> in-string: contract violation\n> expected: string?\n> given: '(1 2 3)\n> ```\n> > > \"+\"[Sequences](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on sequences."} {"text": "### 11.2 [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) and [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13)\nA more complete syntax of [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) is\n> > ```\n(for (clause ...)\n> > body ...+ )\nclause   =   [id sequence-expr]\n    |   #:when boolean-expr\n    |   #:unless boolean-expr"} {"text": "### 11.2 [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) and [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13)\n```\nWhen multiple \\[id sequence-expr\\] clauses are provided in a for form, the corresponding sequences are traversed in parallel:\n\n> ```racket\n> > ( for ( [ i ( in-range 1 4 ) ] [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) ( printf \"Chapter ~a. ~a\\n\" i chapter ) )\n> Chapter 1. Intro Chapter 2. Details Chapter 3. Conclusion\n> ```\n\nWith parallel sequences, the for expression stops iterating when any sequence ends. This behavior allows in-naturals, which creates an infinite sequence of numbers, to be used for indexing:\n\n> ```racket\n> > ( for ( [ i ( in-naturals 1 ) ] [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) ( printf \"Chapter ~a. ~a\\n\" i chapter ) )\n> Chapter 1. Intro Chapter 2. Details Chapter 3. Conclusion\n> ```\n\nThe for* form, which has the same syntax as for, nests multiple sequences instead of running them in parallel:\n\n> ```racket\n> > ( for* ( [ book ' ( \"Guide\" \"Reference\" ) ] [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) ( printf \"~a ~a\\n\" book chapter ) )\n> Guide Intro Guide Details Guide Conclusion Reference Intro Reference Details Reference Conclusion\n> ```\n\nThus, for* is a shorthand for nested fors in the same way that let* is a shorthand for nested lets.\n\nThe #:when boolean-expr form of a clause is another shorthand. It allows the bodys to evaluate only when the boolean-expr produces a true value:\n\n> ```racket\n> > ( for* ( [ book ' ( \"Guide\" \"Reference\" ) ] [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] #:when ( not ( equal? chapter \"Details\" ) ) ) ( printf \"~a ~a\\n\" book chapter ) )\n> Guide Intro Guide Conclusion Reference Intro Reference Conclusion\n> ```\n\nA boolean-expr with #:when can refer to any of the preceding iteration bindings. In a for form, this scoping makes sense only if the test is nested in the iteration of the preceding bindings; thus, bindings separated by #:when are mutually nested, instead of in parallel, even with for.\n\n> ```racket\n> > ( for ( [ book ' ( \"Guide\" \"Reference\" \"Notes\" ) ] #:when ( not ( equal? book \"Notes\" ) ) [ i ( in-naturals 1 ) ] [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" \"Index\" ) ] #:when ( not ( equal? chapter \"Index\" ) ) ) ( printf \"~a Chapter ~a. ~a\\n\" book i chapter ) )\n> Guide Chapter 1. Intro Guide Chapter 2. Details Guide Chapter 3. Conclusion Reference Chapter 1. Intro Reference Chapter 2. Details Reference Chapter 3. Conclusion\n> ```\n\nAn #:unless clause is analogous to a #:when clause, but the bodys evaluate only when the boolean-expr produces a false value.\n\n### 11.3 for/list and for*/list\n\nThe for/list form, which has the same syntax as for, evaluates the bodys to obtain values that go into a newly constructed list:\n\n> ```racket\n> > ( for/list ( [ i ( in-naturals 1 ) ] [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) ( string-append ( number → string i ) \". \" chapter ) )\n> '(\"1. Intro\" \"2. Details\" \"3. Conclusion\")\n> ```\n\nA #:when clause in a for-list form prunes the result list along with evaluations of the bodys:\n\n> ```racket\n> > ( for/list ( [ i ( in-naturals 1 ) ] [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] #:when ( odd? i ) ) chapter )\n> '(\"Intro\" \"Conclusion\")\n> ```\n\nThis pruning behavior of #:when is more useful with for/list than for. Whereas a plain when form normally suffices with for, a when expression form in a for/list would cause the result list to contain #s instead of omitting list elements.\n\nThe for*/list form is like for*, nesting multiple iterations:\n\n> ```racket\n> > ( for*/list ( [ book ' ( \"Guide\" \"Ref.\" ) ] [ chapter ' ( \"Intro\" \"Details\" ) ] ) ( string-append book \" \" chapter ) )\n> '(\"Guide Intro\" \"Guide Details\" \"Ref. Intro\" \"Ref. Details\")\n> ```\n\nA for*/list form is not quite the same thing as nested for/list forms. Nested for/lists would produce a list of lists, instead of one flattened list. Much like #:when, then, the nesting of for*/list is more useful than the nesting of for*.\n\n### 11.4 for/vector and for*/vector\n\nThe for/vector form can be used with the same syntax as the for/list form, but the evaluated bodys go into a newly-constructed vector instead of a list:\n\n> ```racket\n> > ( for/vector ( [ i ( in-naturals 1 ) ] [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) ( string-append ( number → string i ) \". \" chapter ) )\n> '#(\"1. Intro\" \"2. Details\" \"3. Conclusion\")\n> ```\n\nThe for*/vector form behaves similarly, but the iterations are nested as in for*.\n\nThe for/vector and for*/vector forms also allow the length of the vector to be constructed to be supplied in advance. The resulting iteration can be performed more efficiently than plain for/vector or for*/vector:\n\n> ```racket\n> > ( let ( [ chapters ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) ( for/vector #:length ( length chapters ) ( [ i ( in-naturals 1 ) ] [ chapter chapters ] ) ( string-append ( number → string i ) \". \" chapter ) ) )\n> '#(\"1. Intro\" \"2. Details\" \"3. Conclusion\")\n> ```\n\nIf a length is provided, the iteration stops when the vector is filled or the requested iterations are complete, whichever comes first. If the provided length exceeds the requested number of iterations, then the remaining slots in the vector are initialized to the default argument of make-vector.\n\n### 11.5 for/and and for/or\n\nThe for/and form combines iteration results with and, stopping as soon as it encounters #f:\n\n> ```racket\n> > ( for/and ( [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) ( equal? chapter \"Intro\" ) )\n> #f\n> ```\n\nThe for/or form combines iteration results with or, stopping as soon as it encounters a true value:\n\n> ```racket\n> > ( for/or ( [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) ( equal? chapter \"Intro\" ) )\n> #t\n> ```\n\nAs usual, the for*/and and for*/or forms provide the same facility with nested iterations.\n\n### 11.6 for/first and for/last\n\nThe for/first form returns the result of the first time that the bodys are evaluated, skipping further iterations. This form is most useful with a #:when clause.\n\n> ```racket\n> > ( for/first ( [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" \"Index\" ) ] #:when ( not ( equal? chapter \"Intro\" ) ) ) chapter )\n> \"Details\"\n> ```\n\nIf the bodys are evaluated zero times, then the result is #f.\n\nThe for/last form runs all iterations, returning the value of the last iteration (or #f if no iterations are run):\n\n> ```racket\n> > ( for/last ( [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" \"Index\" ) ] #:when ( not ( equal? chapter \"Index\" ) ) ) chapter )\n> \"Conclusion\"\n> ```\n\nAs usual, the for*/first and for*/last forms provide the same facility with nested iterations:\n\n> ```racket\n> > ( for*/first ( [ book ' ( \"Guide\" \"Reference\" ) ] [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" \"Index\" ) ] #:when ( not ( equal? chapter \"Intro\" ) ) ) ( list book chapter ) )\n> '(\"Guide\" \"Details\")\n> > ( for*/last ( [ book ' ( \"Guide\" \"Reference\" ) ] [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" \"Index\" ) ] #:when ( not ( equal? chapter \"Index\" ) ) ) ( list book chapter ) )\n> '(\"Reference\" \"Conclusion\")\n> ```\n\n### 11.7 for/fold and for*/fold\n\nThe for/fold form is a very general way to combine iteration results. Its syntax is slightly different than the syntax of for, because accumulation variables must be declared at the beginning:\n\n> ```racket\n> ( for/fold ( [ accum-id init-expr ] ... )\n> ( clause ... )\n> body ...+ )\n> ```\n\nIn the simple case, only one \\[accum-id init-expr\\] is provided, and the result of the for/fold is the final value for accum-id, which starts out with the value of init-expr. In the clauses and bodys, accum-id can be referenced to get its current value, and the last body provides the value of accum-id for the next iteration.\n\nExamples:\n\n> ```racket\n> > ( for/fold ( [ len 0 ] ) ( [ chapter ' ( \"Intro\" \"Conclusion\" ) ] ) ( + len ( string-length chapter ) ) )\n> 15\n> > ( for/fold ( [ prev #f ] ) ( [ i ( in-naturals 1 ) ] [ chapter ' ( \"Intro\" \"Details\" \"Details\" \"Conclusion\" ) ] #:when ( not ( equal? chapter prev ) ) ) ( printf \"~a. ~a\\n\" i chapter ) chapter )\n> 1. Intro 2. Details 4. Conclusion\n> \"Conclusion\"\n> ```\n\nWhen multiple accum-ids are specified, then the last body must produce multiple values, one for each accum-id. The for/fold expression itself produces multiple values for the results.\n\nExample:\n\n> ```racket\n> > ( for/fold ( [ prev #f ] [ counter 1 ] ) ( [ chapter ' ( \"Intro\" \"Details\" \"Details\" \"Conclusion\" ) ] #:when ( not ( equal? chapter prev ) ) ) ( printf \"~a. ~a\\n\" counter chapter ) ( values chapter ( add1 counter ) ) )\n> 1. Intro 2. Details 3. Conclusion\n> \"Conclusion\" 4\n> ```\n\n### 11.8 Multiple-Valued Sequences\n\nIn the same way that a function or expression can produce multiple values, individual iterations of a sequence can produce multiple elements. For example, a hash table as a sequence generates two values for each iteration: a key and a value.\n\nIn the same way that let-values binds multiple results to multiple identifiers, for can bind multiple sequence elements to multiple iteration identifiers:\n\n> > > While let must be changed to let-values to bind multiple identifiers, for simply allows a parenthesized list of identifiers instead of a single identifier in any clause.\n\n> ```racket\n> > ( for ( [ ( k v ) #hash ( ( \"apple\" . 1 ) ( \"banana\" . 3 ) ) ] ) ( printf \"~a count: ~a\\n\" k v ) )\n> apple count: 1 banana count: 3\n> ```\n\nThis extension to multiple-value bindings works for all for variants. For example, for*/list nests iterations, builds a list, and also works with multiple-valued sequences:\n\n> ```racket\n> > ( for*/list ( [ ( k v ) #hash ( ( \"apple\" . 1 ) ( \"banana\" . 3 ) ) ] [ ( i ) ( in-range v ) ] ) k )\n> '(\"apple\" \"banana\" \"banana\" \"banana\")\n> ```\n\n### 11.9 Breaking an Iteration\n\nAn even more complete syntax of for is\n\n> > ```\n(for (clause ...)\n> > body-or-break ... body )\n \nclause   =   [id sequence-expr]\n    |   #:when boolean-expr\n    |   #:unless boolean-expr\n    |   break\n         \nbody-or-break   =   body\n    |   break\n         \nbreak   =   #:break boolean-expr\n    |   #:final boolean-expr```\n\n\nThat is, a #:break or #:final clause can be included among the binding clauses and body of the iteration. Among the binding clauses, #:break is like #:unless but when its boolean-expr is true, all sequences within the [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) are stopped. Among the bodys, #:break has the same effect on sequences when its boolean-expr is true, and it also prevents later bodys from evaluation in the current iteration.\n\nFor example, while using #:unless between clauses effectively skips later sequences as well as the body,\n\n> ```racket\n> > ( for ( [ book ' ( \"Guide\" \"Story\" \"Reference\" ) ] #:unless ( equal? book \"Story\" ) [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) ( printf \"~a ~a\\n\" book chapter ) )\n> Guide Intro Guide Details Guide Conclusion Reference Intro Reference Details Reference Conclusion\n> ```\n\nusing #:break causes the entire [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) iteration to terminate:\n\n> ```racket\n> > ( for ( [ book ' ( \"Guide\" \"Story\" \"Reference\" ) ] #:break ( equal? book \"Story\" ) [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) ( printf \"~a ~a\\n\" book chapter ) )\n> Guide Intro Guide Details Guide Conclusion\n> > ( for* ( [ book ' ( \"Guide\" \"Story\" \"Reference\" ) ] [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) #:break ( and ( equal? book \"Story\" ) ( equal? chapter \"Conclusion\" ) ) ( printf \"~a ~a\\n\" book chapter ) )\n> Guide Intro Guide Details Guide Conclusion Story Intro Story Details\n> ```\n\nA #:final clause is similar to #:break, but it does not immediately terminate the iteration. Instead, it allows at most one more element to be drawn for each sequence and at most one more evaluation of the bodys.\n\n> ```racket\n> > ( for* ( [ book ' ( \"Guide\" \"Story\" \"Reference\" ) ] [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) #:final ( and ( equal? book \"Story\" ) ( equal? chapter \"Conclusion\" ) ) ( printf \"~a ~a\\n\" book chapter ) )\n> Guide Intro Guide Details Guide Conclusion Story Intro Story Details Story Conclusion\n> > ( for ( [ book ' ( \"Guide\" \"Story\" \"Reference\" ) ] #:final ( equal? book \"Story\" ) [ chapter ' ( \"Intro\" \"Details\" \"Conclusion\" ) ] ) ( printf \"~a ~a\\n\" book chapter ) )\n> Guide Intro Guide Details Guide Conclusion Story Intro\n> ```\n\n### 11.10 Iteration Performance\n\nIdeally, a [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) iteration should run as fast as a loop that you write by hand as a recursive-function invocation. A hand-written loop, however, is normally specific to a particular kind of data, such as lists. In that case, the hand-written loop uses selectors like [car](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._car%2529%2529&version=8.18.0.13) and [cdr](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cdr%2529%2529&version=8.18.0.13) directly, instead of handling all forms of sequences and dispatching to an appropriate iterator.\n\nThe [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) forms can provide the performance of hand-written loops when enough information is apparent about the sequences to iterate, specifically when the clause has one of the following fast-clause forms:\n\n| | | | | |\n|--------------:|:----|:---:|:----|:-------------------------------|\n|   fast-clause |   | = |   | \\[id fast-seq\\] |\n|   |   | \\| |   | \\[(id) fast-seq\\] |\n|   |   | \\| |   | \\[(id id) fast-indexed-seq\\] |\n|   |   | \\| |   | \\[(id ...) fast-parallel-seq\\] |\n\n| | | | | |\n|-----------:|:----|:---:|:----|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n|   fast-seq |   | = |   | literal |\n|   |   | \\| |   | ([in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13) expr) |\n|   |   | \\| |   | ([in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13) expr expr) |\n|   |   | \\| |   | ([in-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-range%2529%2529&version=8.18.0.13) expr expr expr) |\n|   |   | \\| |   | ([in-inclusive-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-inclusive-range%2529%2529&version=8.18.0.13) expr expr) |\n|   |   | \\| |   | ([in-inclusive-range](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-inclusive-range%2529%2529&version=8.18.0.13) expr expr expr) |\n|   |   | \\| |   | ([in-naturals](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-naturals%2529%2529&version=8.18.0.13)) |\n|   |   | \\| |   | ([in-naturals](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-naturals%2529%2529&version=8.18.0.13) expr) |\n|   |   | \\| |   | ([in-list](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-list%2529%2529&version=8.18.0.13) expr) |\n|   |   | \\| |   | ([in-mlist](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-mlist%2529%2529&version=8.18.0.13) expr) |\n|   |   | \\| |   | ([in-vector](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-vector%2529%2529&version=8.18.0.13) expr) |\n|   |   | \\| |   | ([in-string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-string%2529%2529&version=8.18.0.13) expr) |\n|   |   | \\| |   | ([in-bytes](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-bytes%2529%2529&version=8.18.0.13) expr) |\n|   |   | \\| |   | ([in-value](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-value%2529%2529&version=8.18.0.13) expr) |\n|   |   | \\| |   | ([stop-before](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-before%2529%2529&version=8.18.0.13) fast-seq predicate-expr) |\n|   |   | \\| |   | ([stop-after](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-after%2529%2529&version=8.18.0.13) fast-seq predicate-expr) |\n\n| | | | | |\n|-------------------:|:----|:---:|:----|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n|   fast-indexed-seq |   | = |   | ([in-indexed](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-indexed%2529%2529&version=8.18.0.13) fast-seq) |\n|   |   | \\| |   | ([stop-before](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-before%2529%2529&version=8.18.0.13) fast-indexed-seq predicate-expr) |\n|   |   | \\| |   | ([stop-after](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-after%2529%2529&version=8.18.0.13) fast-indexed-seq predicate-expr) |\n\n| | | | | |\n|--------------------:|:----|:---:|:----|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n|   fast-parallel-seq |   | = |   | ([in-parallel](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._in-parallel%2529%2529&version=8.18.0.13) fast-seq ...) |\n|   |   | \\| |   | ([stop-before](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-before%2529%2529&version=8.18.0.13) fast-parallel-seq predicate-expr) |\n|   |   | \\| |   | ([stop-after](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=sequences.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._stop-after%2529%2529&version=8.18.0.13) fast-parallel-seq predicate-expr) |\n\nExamples:\n\n> ```racket\n> > ( define lst ' ( a b c d e f g h ) )\n> > ( time ( for ( [ i ( in-range 100000 ) ] ) ( for ( [ elem ( in-list lst ) ] ) ; fast ( void ) ) ) )\n> cpu time: 7 real time: 1 gc time: 0\n> > ( time ( for ( [ i ( in-range 100000 ) ] ) ( for ( [ elem ' ( a b c d e f g h ) ] ) ; also fast ( void ) ) ) )\n> cpu time: 7 real time: 1 gc time: 0\n> > ( time ( for ( [ i ( in-range 100000 ) ] ) ( for ( [ elem lst ] ) ; slower ( void ) ) ) )\n> cpu time: 27 real time: 4 gc time: 0\n> > ( time ( let ( [ seq ( in-list lst ) ] ) ( for ( [ i ( in-range 100000 ) ] ) ( for ( [ elem seq ] ) ; also slower ( void ) ) ) ) )\n> cpu time: 53 real time: 13 gc time: 9\n> ```\n\nThe grammars above are not complete, because the set of syntactic patterns that provide good performance is extensible, just like the set of sequence values. The documentation for a sequence constructor should indicate the performance benefits of using it directly in a [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) clause.\n\n> > > \"+\"[Iterations and Comprehensions: for, for/list, ...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html&version=8.18.0.13) in [The Racket Reference](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13) provides more on iterations and comprehensions.\n\n------------------------------------------------------------------------\n\n# 12 Pattern Matching\n\n## 12 Pattern Matching\n\n> > > ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) racket/match) is needed for [#lang](Module_Syntax.html#%28part._hash-lang%29) [racket/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=index.html&version=8.18.0.13).\n\nThe [match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=match.html%23%2528form._%2528%2528lib._racket%252Fmatch..rkt%2529._match%2529%2529&version=8.18.0.13) form supports pattern matching on arbitrary Racket values, as opposed to functions like [regexp-match](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=regexp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._regexp-match%2529%2529&version=8.18.0.13) that compare regular expressions to byte and character sequences (see [Regular Expressions](regexp.html)).\n\n> > ```\n(match target-expr\n> > [ pattern expr ...+ ] ... )\n```"} {"text": "### 11.2 [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) and [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13)\n(1)\t→```\nThe grow method in picky-fish% is declared with [define/override](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._define%252Foverride%2529%2529&version=8.18.0.13) instead of [define/public](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._define%252Fpublic%2529%2529&version=8.18.0.13), because grow is meant as an overriding declaration. If grow had been declared with [define/public](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._define%252Fpublic%2529%2529&version=8.18.0.13), an error would have been signaled when evaluating the [class](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._class%2529%2529&version=8.18.0.13) expression, because fish% already supplies grow."} {"text": "### 11.2 [for](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%2529%2529&version=8.18.0.13) and [for*](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=for.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._for%252A%2529%2529&version=8.18.0.13)\nUsing [define/override](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._define%252Foverride%2529%2529&version=8.18.0.13) also allows the invocation of the overridden method via a [super](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._super%2529%2529&version=8.18.0.13) call. For example, the grow implementation in picky-fish% uses [super](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._super%2529%2529&version=8.18.0.13) to delegate to the superclass implementation."} {"text": "### 13.2 Initialization Arguments\nSince picky-fish% declares no initialization arguments, any initialization values supplied in ([new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._new%2529%2529&version=8.18.0.13) picky-fish% ....) are propagated to the superclass initialization, i.e., to fish%. A subclass can supply additional initialization arguments for its superclass in a [super-new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._super-new%2529%2529&version=8.18.0.13) call, and such initialization arguments take precedence over arguments supplied to [new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._new%2529%2529&version=8.18.0.13). For example, the following size-10-fish% class always generates fish of size 10:"} {"text": "### 13.2 Initialization Arguments\n>
([define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) size-10-fish% ([class](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._class%2529%2529&version=8.18.0.13) fish% ([super-new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._super-new%2529%2529&version=8.18.0.13) [size 10])))

 

> ( send ( new size-10-fish% ) get-size )\n> 10
"} {"text": "### 13.2 Initialization Arguments\nIn the case of size-10-fish%, supplying a size initialization argument with [new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._new%2529%2529&version=8.18.0.13) would result in an initialization error; because the size in [super-new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._super-new%2529%2529&version=8.18.0.13) takes precedence, a size supplied to [new](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=objcreation.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._new%2529%2529&version=8.18.0.13) would have no target declaration.\nAn initialization argument is optional if the [class](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._class%2529%2529&version=8.18.0.13) form declares a default value. For example, the following default-10-fish% class accepts a size initialization argument, but its value defaults to 10 if no value is supplied on instantiation:\n> ```\n(define default-10-fish% (class fish%\n> ( init [ size 10 ] )\n> ( super-new [ size size ] ) ) )"} {"text": "### 13.2 Initialization Arguments\n> ( new default-10-fish% )\n> (object:default-10-fish% ...)\n> > ( new default-10-fish% [ size 20 ] )\n> (object:default-10-fish% ...)\n```\n(implied)\t→```\n\n\nThe first set of interface-exprs determines the domain of the mixin, and the second set determines the range. That is, the expansion is a function that tests whether a given base class implements the first sequence of interface-exprs and produces a class that implements the second sequence of interface-exprs. Other requirements, such as the presence of [inherit](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._inherit%2529%2529&version=8.18.0.13)ed methods in the superclass, are then checked for the [class](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._class%2529%2529&version=8.18.0.13) expansion of the [mixin](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=mixins.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._mixin%2529%2529&version=8.18.0.13) form. For example:\n\n> ```racket\n> > ( define choosy-interface ( interface ( ) choose? ) )\n> > ( define hungry-interface ( interface ( ) eat ) )\n> > ( define choosy-eater-mixin ( mixin ( choosy-interface ) ( hungry-interface ) ( inherit choose? ) ( super-new ) ( define/public ( eat x ) ( cond [ ( choose? x ) ( printf \"chomp chomp chomp on ~a.\\n\" x ) ] [ else ( printf \"I'm not crazy about ~a.\\n\" x ) ] ) ) ) )\n> > ( define herring-lover% ( class* object% ( choosy-interface ) ( super-new ) ( define/public ( choose? x ) ( regexp-match #px\"^herring\" x ) ) ) )\n> > ( define herring-eater% ( choosy-eater-mixin herring-lover% ) )\n> > ( define eater ( new herring-eater% ) )\n> > ( send eater eat \"elderberry\" )\n> I'm not crazy about elderberry.\n> > ( send eater eat \"herring\" )\n> chomp chomp chomp on herring.\n> > ( send eater eat \"herring ice cream\" )\n> chomp chomp chomp on herring ice cream.\n> ```\n\nMixins not only override methods and introduce public methods, they can also augment methods, introduce augment-only methods, add an overrideable augmentation, and add an augmentable override — all of the things that a class can do (see [Final, Augment, and Inner](#%28part._inner%29)).\n\n#### 13.7.3 Parameterized Mixins\n\nAs noted in [Controlling the Scope of External Names](#%28part._extnames%29), external names can be bound with [define-member-name](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._define-member-name%2529%2529&version=8.18.0.13). This facility allows a mixin to be generalized with respect to the methods that it defines and uses. For example, we can parameterize hungry-mixin with respect to the external member key for eat:\n\n> ```racket\n> ( define ( make-hungry-mixin eat-method-key )\n> ( define-member-name eat eat-method-key )\n> ( mixin ( ) ( ) ( super-new )\n> ( inherit eat )\n> ( define/public ( eat-more x y ) ( eat x ) ( eat y ) ) ) )\n> ```\n\nTo obtain a particular hungry-mixin, we must apply this function to a member key that refers to a suitable eat method, which we can obtain using [member-name-key](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._member-name-key%2529%2529&version=8.18.0.13):\n\n> ```racket\n> ( ( make-hungry-mixin ( member-name-key eat ) )\n> ( class object% .... ( define/public ( eat x ) ' yum ) ) )\n> ```\n\nAbove, we apply hungry-mixin to an anonymous class that provides eat, but we can also combine it with a class that provides chomp, instead:\n\n> ```racket\n> ( ( make-hungry-mixin ( member-name-key chomp ) )\n> ( class object% .... ( define/public ( chomp x ) ' yum ) ) )\n> ```\n\n### 13.8 Traits\n\nA trait is similar to a mixin, in that it encapsulates a set of methods to be added to a class. A trait is different from a mixin in that its individual methods can be manipulated with trait operators such as [trait-sum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528def._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-sum%2529%2529&version=8.18.0.13) (merge the methods of two traits), [trait-exclude](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-exclude%2529%2529&version=8.18.0.13) (remove a method from a trait), and [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13) (add a copy of a method with a new name; do not redirect any calls to the old name).\n\nThe practical difference between mixins and traits is that two traits can be combined, even if they include a common method and even if neither method can sensibly override the other. In that case, the programmer must explicitly resolve the collision, usually by aliasing methods, excluding methods, and merging a new trait that uses the aliases.\n\nSuppose our fish% programmer wants to define two class extensions, spots and stripes, each of which includes a get-color method. The fish’s spot color should not override the stripe color nor vice versa; instead, a spots+stripes-fish% should combine the two colors, which is not possible if spots and stripes are implemented as plain mixins. If, however, spots and stripes are implemented as traits, they can be combined. First, we alias get-color in each trait to a non-conflicting name. Second, the get-color methods are removed from both and the traits with only aliases are merged. Finally, the new trait is used to create a class that introduces its own get-color method based on the two aliases, producing the desired spots+stripes extension.\n\n#### 13.8.1 Traits as Sets of Mixins\n\nOne natural approach to implementing traits in Racket is as a set of mixins, with one mixin per trait method. For example, we might attempt to define the spots and stripes traits as follows, using association lists to represent sets:\n\n> ```racket\n> ( define spots-trait\n> ( list ( cons ' get-color\n> ( lambda ( % ) ( class % ( super-new )\n> ( define/public ( get-color )\n> ' black ) ) ) ) ) )\n> ( define stripes-trait\n> ( list ( cons ' get-color\n> ( lambda ( % ) ( class % ( super-new )\n> ( define/public ( get-color )\n> ' red ) ) ) ) ) )\n> ```\n\nA set representation, such as the above, allows [trait-sum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528def._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-sum%2529%2529&version=8.18.0.13) and [trait-exclude](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-exclude%2529%2529&version=8.18.0.13) as simple manipulations; unfortunately, it does not support the [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13) operator. Although a mixin can be duplicated in the association list, the mixin has a fixed method name, e.g., get-color, and mixins do not support a method-rename operation. To support [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13), we must parameterize the mixins over the external method name in the same way that eat was parameterized in [Parameterized Mixins](#%28part._parammixins%29).\n\nTo support the [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13) operation, spots-trait should be represented as:\n\n> ```racket\n> ( define spots-trait\n> ( list ( cons ( member-name-key get-color )\n> ( lambda ( get-color-key % )\n> ( define-member-name get-color get-color-key )\n> ( class % ( super-new )\n> ( define/public ( get-color ) ' black ) ) ) ) ) )\n> ```\n\nWhen the get-color method in spots-trait is aliased to get-trait-color and the get-color method is removed, the resulting trait is the same as\n\n> ```racket\n> ( list ( cons ( member-name-key get-trait-color )\n> ( lambda ( get-color-key % )\n> ( define-member-name get-color get-color-key )\n> ( class % ( super-new )\n> ( define/public ( get-color ) ' black ) ) ) ) )\n> ```\n\nTo apply a trait T to a class C and obtain a derived class, we use (([trait->mixin](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528def._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-%7E3emixin%2529%2529&version=8.18.0.13) T) C). The [trait->mixin](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528def._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-%7E3emixin%2529%2529&version=8.18.0.13) function supplies each mixin of T with the key for the mixin’s method and a partial extension of C:\n\n> ```racket\n> ( define ( ( trait->mixin T ) C )\n> ( foldr ( lambda ( m % ) ( ( cdr m ) ( car m ) % ) ) C T ) )\n> ```\n\nThus, when the trait above is combined with other traits and then applied to a class, the use of get-color becomes a reference to the external name get-trait-color.\n\n#### 13.8.2 Inherit and Super in Traits\n\nThis first implementation of traits supports [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13), and it supports a trait method that calls itself, but it does not support trait methods that call each other. In particular, suppose that a spot-fish’s market value depends on the color of its spots:\n\n> ```racket\n> ( define spots-trait\n> ( list ( cons ( member-name-key get-color ) .... )\n> ( cons ( member-name-key get-price )\n> ( lambda ( get-price % ) ....\n> ( class % ....\n> ( define/public ( get-price )\n> .... ( get-color ) .... ) ) ) ) ) )\n> ```\n\nIn this case, the definition of spots-trait fails, because get-color is not in scope for the get-price mixin. Indeed, depending on the order of mixin application when the trait is applied to a class, the get-color method may not be available when get-price mixin is applied to the class. Therefore adding an ([inherit](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._inherit%2529%2529&version=8.18.0.13) get-color) declaration to the get-price mixin does not solve the problem.\n\nOne solution is to require the use of ([send](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=ivaraccess.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._send%2529%2529&version=8.18.0.13) [this](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._this%2529%2529&version=8.18.0.13) get-color) in methods such as get-price. This change works because [send](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=ivaraccess.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._send%2529%2529&version=8.18.0.13) always delays the method lookup until the method call is evaluated. The delayed lookup is more expensive than a direct call, however. Worse, it also delays checking whether a get-color method even exists.\n\nA second, effective, and efficient solution is to change the encoding of traits. Specifically, we represent each method as a pair of mixins: one that introduces the method and one that implements it. When a trait is applied to a class, all of the method-introducing mixins are applied first. Then the method-implementing mixins can use [inherit](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._inherit%2529%2529&version=8.18.0.13) to directly access any introduced method.\n\n> ```racket\n> ( define spots-trait\n> ( list ( list ( local-member-name-key get-color )\n> ( lambda ( get-color get-price % ) ....\n> ( class % ....\n> ( define/public ( get-color ) ( void ) ) ) )\n> ( lambda ( get-color get-price % ) ....\n> ( class % ....\n> ( define/override ( get-color ) ' black ) ) ) )\n> ( list ( local-member-name-key get-price )\n> ( lambda ( get-color get-price % ) ....\n> ( class % ....\n> ( define/public ( get-price ) ( void ) ) ) )\n> ( lambda ( get-color get-price % ) ....\n> ( class % ....\n> ( inherit get-color )\n> ( define/override ( get-price )\n> .... ( get-color ) .... ) ) ) ) ) )\n> ```\n\nWith this trait encoding, [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13) adds a new method with a new name, but it does not change any references to the old method.\n\n#### 13.8.3 The [trait](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait%2529%2529&version=8.18.0.13) Form\n\n> > > ([require](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=require.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._require%2529%2529&version=8.18.0.13) racket/trait) is needed.\n\nThe general-purpose trait pattern is clearly too complex for a programmer to use directly, but it is easily codified in a [trait](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait%2529%2529&version=8.18.0.13) macro:\n\n> > | |\n> > |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([trait](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait%2529%2529&version=8.18.0.13) trait-clause ...) |\n\nThe ids in the optional [inherit](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._inherit%2529%2529&version=8.18.0.13) clause are available for direct reference in the method exprs, and they must be supplied either by other traits or the base class to which the trait is ultimately applied.\n\nUsing this form in conjunction with trait operators such as [trait-sum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528def._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-sum%2529%2529&version=8.18.0.13), [trait-exclude](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-exclude%2529%2529&version=8.18.0.13), [trait-alias](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528form._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-alias%2529%2529&version=8.18.0.13), and [trait->mixin](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=trait.html%23%2528def._%2528%2528lib._racket%252Ftrait..rkt%2529._trait-%7E3emixin%2529%2529&version=8.18.0.13), we can implement spots-trait and stripes-trait as desired.\n\n> ```racket\n> ( define spots-trait\n> ( trait\n> ( define/public ( get-color ) ' black )\n> ( define/public ( get-price ) ... ( get-color ) ... ) ) )\n> ( define stripes-trait\n> ( trait\n> ( define/public ( get-color ) ' red ) ) )\n> ( define spots+stripes-trait\n> ( trait-sum\n> ( trait-exclude ( trait-alias spots-trait\n> get-color get-spots-color )\n> get-color )\n> ( trait-exclude ( trait-alias stripes-trait\n> get-color get-stripes-color )\n> get-color )\n> ( trait\n> ( inherit get-spots-color get-stripes-color )\n> ( define/public ( get-color )\n> .... ( get-spots-color ) .... ( get-stripes-color ) .... ) ) ) )\n> ```\n\n### 13.9 Class Contracts\n\nAs classes are values, they can flow across contract boundaries, and we may wish to protect parts of a given class with contracts. For this, the [class/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Object_and_Class_Contracts.html%23%2528form._%2528%2528lib._racket%252Fclass..rkt%2529._class%252Fc%2529%2529&version=8.18.0.13) form is used. The [class/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Object_and_Class_Contracts.html%23%2528form._%2528%2528lib._racket%252Fclass..rkt%2529._class%252Fc%2529%2529&version=8.18.0.13) form has many subforms, which describe two types of contracts on fields and methods: those that affect uses via instantiated objects and those that affect subclasses.\n\n#### 13.9.1 External Class Contracts\n\nIn its simplest form, [class/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Object_and_Class_Contracts.html%23%2528form._%2528%2528lib._racket%252Fclass..rkt%2529._class%252Fc%2529%2529&version=8.18.0.13) protects the public fields and methods of objects instantiated from the contracted class. There is also an [object/c](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Object_and_Class_Contracts.html%23%2528form._%2528%2528lib._racket%252Fclass..rkt%2529._object%252Fc%2529%2529&version=8.18.0.13) form that can be used to similarly protect the public fields and methods of a particular object. Take the following definition of animal%, which uses a public field for its size attribute:\n\n> ```racket\n> ( define animal%\n> ( class object%\n> ( super-new )\n> ( field [ size 10 ] )\n> ( define/public ( eat food )\n> ( set! size ( + size ( get-field size food ) ) ) ) ) )\n> ```\n\nFor any instantiated animal%, accessing the size field should return a positive number. Also, if the size field is set, it should be assigned a positive number. Finally, the eat method should receive an argument which is an object with a size field that contains a positive number. To ensure these conditions, we will define the animal% class with an appropriate contract:\n\n> ```racket\n> ( define positive/c ( and/c number? positive? ) )\n> ( define edible/c ( object/c ( field [ size positive/c ] ) ) )\n> ( define/contract animal%\n> ( class/c ( field [ size positive/c ] )\n> [ eat ( -> m edible/c void? ) ] )\n> ( class object%\n> ( super-new )\n> ( field [ size 10 ] )\n> ( define/public ( eat food )\n> ( set! size ( + size ( get-field size food ) ) ) ) ) )\n> ```\n\nHere we use [->m](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=Object_and_Class_Contracts.html%23%2528form._%2528%2528lib._racket%252Fclass..rkt%2529._-%7E3em%2529%2529&version=8.18.0.13) to describe the behavior of eat since we do not need to describe any requirements for the [this](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._this%2529%2529&version=8.18.0.13) parameter. Now that we have our contracted class, we can see that the contracts on both size and eat are enforced:\n\n> ```racket\n> > ( define bob ( new animal% ) )\n> > ( set-field! size bob 3 )\n> > ( get-field size bob )\n> 3\n> > ( set-field! size bob ' large )\n> animal%: contract violation\n> expected: positive/c\n> given: 'large\n> in: the size field in\n> (class/c\n> (eat\n> (->m\n> (object/c (field (size positive/c)))\n> void?))\n> (field (size positive/c)))\n> contract from: (definition animal%)\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:31:0\n> > ( define richie ( new animal% ) )\n> > ( send bob eat richie )\n> > ( get-field size bob )\n> 13\n> > ( define rock ( new object% ) )\n> > ( send bob eat rock )\n> eat: contract violation;\n> no public field size\n> in: the 1st argument of\n> the eat method in\n> (class/c\n> (eat\n> (->m\n> (object/c (field (size positive/c)))\n> void?))\n> (field (size positive/c)))\n> contract from: (definition animal%)\n> contract on: animal%\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:31:0\n> > ( define giant ( new ( class object% ( super-new ) ( field [ size ' large ] ) ) ) )\n> > ( send bob eat giant )\n> eat: contract violation\n> expected: positive/c\n> given: 'large\n> in: the size field in\n> the 1st argument of\n> the eat method in\n> (class/c\n> (eat\n> (->m\n> (object/c (field (size positive/c)))\n> void?))\n> (field (size positive/c)))\n> contract from: (definition animal%)\n> contract on: animal%\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:31:0\n> ```\n\nThere are two important caveats for external class contracts. First, external method contracts are only enforced when the target of dynamic dispatch is the method implementation of the contracted class, which lies within the contract boundary. Overriding that implementation, and thus changing the target of dynamic dispatch, will mean that the contract is no longer enforced for clients, since accessing the method no longer crosses the contract boundary. Unlike external method contracts, external field contracts are always enforced for clients of subclasses, since fields cannot be overridden or shadowed.\n\nSecond, these contracts do not restrict subclasses of animal% in any way. Fields and methods that are inherited and used by subclasses are not checked by these contracts, and uses of the superclass’s methods via [super](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=createclass.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fclass-internal..rkt%2529._super%2529%2529&version=8.18.0.13) are also unchecked. The following example illustrates both caveats:\n\n> ```\n(parameter)\t→\t\n(-> object/c (field (size positive/c)))\n```"} {"text": "### 13.2 Initialization Arguments\n(Components)\t→\t\n(-> inherit [ eat (→ m edible/c void?) ])```\n> > > The [define-syntax-rule](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fmisc..rkt%2529._define-syntax-rule%2529%2529&version=8.18.0.13) form is itself a macro that expands into [define-syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define-syntax%2529%2529&version=8.18.0.13) with a [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13) form that contains only one pattern and template.\nFor example, suppose we would like a rotate macro that generalizes swap to work on either two or three identifiers, so that\n> ```racket\n> ( let ( [ red 1 ] [ green 2 ] [ blue 3 ] )\n> ( rotate red green ) ; swaps\n> ( rotate red green blue ) ; rotates left\n> ( list red green blue ) )\n> ```\nproduces (1 3 2). We can implement rotate using [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13):"} {"text": "### 13.2 Initialization Arguments\n> ```racket\n> ( define-syntax rotate\n> ( syntax-rules ( )\n> [ ( rotate a b ) ( swap a b ) ]\n> [ ( rotate a b c ) ( begin\n> ( swap a b )\n> ( swap b c ) ) ] ) )\n> ```\nThe expression (rotate red green) matches the first pattern in the [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13) form, so it expands to (swap red green). The expression (rotate red green blue) matches the second pattern, so it expands to ([begin](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=begin.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._begin%2529%2529&version=8.18.0.13) (swap red green) (swap green blue))."} {"text": "#### 16.1.4 Matching Sequences\nA better rotate macro would allow any number of identifiers, instead of just two or three. To match a use of rotate with any number of identifiers, we need a pattern form that has something like a Kleene star. In a Racket macro pattern, a star is written as [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13).\nTo implement rotate with [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13), we need a base case to handle a single identifier, and an inductive case to handle more than one identifier:\n> ```racket\n> ( define-syntax rotate\n> ( syntax-rules ( )\n> [ ( rotate a ) ( void ) ]\n> [ ( rotate a b c ... ) ( begin\n> ( swap a b )\n> ( rotate b c ... ) ) ] ) )\n> ```"} {"text": "### 13.2 Initialization Arguments\nWhen a pattern variable like c is followed by [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13) in a pattern, then it must be followed by [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13) in a template, too. The pattern variable effectively matches a sequence of zero or more forms, and it is replaced in the template by the same sequence.\nBoth versions of rotate so far are a bit inefficient, since pairwise swapping keeps moving the value from the first variable into every variable in the sequence until it arrives at the last one. A more efficient rotate would move the first value directly to the last variable. We can use [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13) patterns to implement the more efficient variant using a helper macro:"} {"text": "### 13.2 Initialization Arguments\n> ```racket\n> ( define-syntax rotate\n> ( syntax-rules ( )\n> [ ( rotate a c ... )\n> ( shift-to ( c ... a ) ( a c ... ) ) ] ) )\n> ( define-syntax shift-to\n> ( syntax-rules ( )\n> [ ( shift-to ( from0 from ... ) ( to0 to ... ) )\n> ( let ( [ tmp from0 ] )\n> ( set! to from ) ...\n> ( set! to0 tmp ) ) ] ) )\n> ```\nIn the shift-to macro, [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13) in the template follows ([set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) to from), which causes the ([set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) to from) expression to be duplicated as many times as necessary to use each identifier matched in the to and from sequences. (The number of to and from matches must be the same, otherwise the macro expansion fails with an error.)"} {"text": "#### 16.1.5 Identifier Macros\nGiven our macro definitions, the swap or rotate identifiers must be used after an open parenthesis, otherwise a syntax error is reported:\n> ```racket\n> > ( + swap 3 )\n> eval:2:0: swap: bad syntax\n> in: swap\n> ```\nAn identifier macro is a pattern-matching macro that works when used by itself without parentheses. For example, we can define val as an identifier macro that expands to (get-val), so ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) val 3) would expand to ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) (get-val) 3).\n> ```racket\n> > ( define-syntax val ( lambda ( stx ) ( syntax-case stx ( ) [ val ( identifier? ( syntax val ) ) ( syntax ( get-val ) ) ] ) ) )\n> > ( define-values ( get-val put-val! ) ( let ( [ private-val 0 ] ) ( values ( lambda ( ) private-val ) ( lambda ( v ) ( set! private-val v ) ) ) ) )\n> > val\n> 0\n> > ( + val 3 )\n> 3\n> ```"} {"text": "### 13.2 Initialization Arguments\nThe val macro uses [syntax-case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-case%2529%2529&version=8.18.0.13), which enables defining more powerful macros and will be explained in the [Mixing Patterns and Expressions: syntax-case](syntax-case.html) section. For now it is sufficient to know that to define a macro, [syntax-case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-case%2529%2529&version=8.18.0.13) is used in a [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13), and its templates must be wrapped with an explicit [syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax%2529%2529&version=8.18.0.13) constructor. Finally, [syntax-case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-case%2529%2529&version=8.18.0.13) clauses may specify additional guard conditions after the pattern."} {"text": "### 13.2 Initialization Arguments\nOur val macro uses an [identifier?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fstx..rkt%2529._identifier%7E3f%2529%2529&version=8.18.0.13) condition to ensure that val must not be used with parentheses. Instead, the macro raises a syntax error:\n> ```racket\n> > ( val )\n> eval:8:0: val: bad syntax\n> in: (val)\n> ```"} {"text": "#### 16.1.6 [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) Transformers\nWith the above val macro, we still must call put-val! to change the stored value. It would be more convenient, however, to use [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) directly on val. To invoke the macro when val is used with [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13), we create an [assignment transformer](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=syntax-model.html%23%2528tech._assignment._transformer%2529&version=8.18.0.13) with [make-set!-transformer](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxtrans.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._make-set%2521-transformer%2529%2529&version=8.18.0.13). We must also declare [set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=set_.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._set%2521%2529%2529&version=8.18.0.13) as a literal in the [syntax-case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-case%2529%2529&version=8.18.0.13) literal list."} {"text": "### 13.2 Initialization Arguments\n> ```racket\n> > ( define-syntax val2 ( make-set!-transformer ( lambda ( stx ) ( syntax-case stx ( set! ) [ val2 ( identifier? ( syntax val2 ) ) ( syntax ( get-val ) ) ] [ ( set! val2 e ) ( syntax ( put-val! e ) ) ] ) ) ) )\n> > val2\n> 0\n> > ( + val2 3 )\n> 3\n> > ( set! val2 10 )\n> > val2\n> 10\n> ```"} {"text": "#### 16.1.7 Macro-Generating Macros\nSuppose that we have many identifiers like val and val2 that we’d like to redirect to accessor and mutator functions like get-val and put-val!. We’d like to be able to just write:\n> (define-get/put-id val get-val put-val!)\nNaturally, we can implement define-get/put-id as a macro:\n> ```racket\n> > ( define-syntax-rule ( define-get/put-id id get put! ) ( define-syntax id ( make-set!-transformer ( lambda ( stx ) ( syntax-case stx ( set! ) [ id ( identifier? ( syntax id ) ) ( syntax ( get ) ) ] [ ( set! id e ) ( syntax ( put! e ) ) ] ) ) ) ) )\n> > ( define-get/put-id val3 get-val put-val! )\n> > ( set! val3 11 )\n> > val3\n> 11\n> ```\nThe define-get/put-id macro is a macro-generating macro."} {"text": "#### 16.1.8 Extended Example: Call-by-Reference Functions\nWe can use pattern-matching macros to add a form to Racket for defining first-order call-by-reference functions. When a call-by-reference function body mutates its formal argument, the mutation applies to variables that are supplied as actual arguments in a call to the function.\nFor example, if define-cbr is like [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13) except that it defines a call-by-reference function, then\n> ```racket\n> ( define-cbr ( f a b )\n> ( swap a b ) )\n> ( let ( [ x 1 ] [ y 2 ] )\n> ( f x y )\n> ( list x y ) )\n> ```\nproduces (2 1).\nWe will implement call-by-reference functions by having function calls supply accessor and mutators for the arguments, instead of supplying argument values directly. In particular, for the function f above, we’ll generate\n> ```racket\n> ( define ( do-f get-a get-b put-a! put-b! )\n> ( define-get/put-id a get-a put-a! )\n> ( define-get/put-id b get-b put-b! )\n> ( swap a b ) )\n> ```\nand redirect a function call (f x y) to\n> ```racket\n> ( do-f ( lambda ( ) x )\n> ( lambda ( ) y )\n> ( lambda ( v ) ( set! x v ) )\n> ( lambda ( v ) ( set! y v ) ) )\n> ```\nClearly, then define-cbr is a macro-generating macro, which binds f to a macro that expands to a call of do-f. That is, (define-cbr (f a b) (swap a b)) needs to generate the definition"} {"text": "### 13.2 Initialization Arguments\n> ```racket\n> ( define-syntax f\n> ( syntax-rules ( )\n> [ ( id actual ... )\n> ( do-f ( lambda ( ) actual )\n> ...\n> ( lambda ( v )\n> ( set! actual v ) )\n> ... ) ] ) )\n> ```\nAt the same time, define-cbr needs to define do-f using the body of f, this second part is slightly more complex, so we defer most of it to a define-for-cbr helper module, which lets us write define-cbr easily enough:\n> ```racket\n> ( define-syntax-rule ( define-cbr ( id arg ... ) body )\n> ( begin\n> ( define-syntax id\n> ( syntax-rules ( )\n> [ ( id actual ( ... ... ) )\n> ( do-f ( lambda ( ) actual )\n> ( ... ... )\n> ( lambda ( v )\n> ( set! actual v ) )\n> ( ... ... ) ) ] ) )\n> ( define-for-cbr do-f ( arg ... )\n> ( ) ; explained below...\n> body ) ) )\n> ```\nOur remaining task is to define define-for-cbr so that it converts\n> (define-for-cbr do-f (a b) () (swap a b))\nto the function definition do-f above. Most of the work is generating a define-get/put-id declaration for each argument, a and b, and putting them before the body. Normally, that’s an easy task for [...](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._......%2529%2529&version=8.18.0.13) in a pattern and template, but this time there’s a catch: we need to generate the names get-a and put-a! as well as get-b and put-b!, and the pattern language provides no way to synthesize identifiers based on existing identifiers."} {"text": "### 13.2 Initialization Arguments\nAs it turns out, lexical scope gives us a way around this problem. The trick is to iterate expansions of define-for-cbr once for each argument in the function, and that’s why define-for-cbr starts with an apparently useless () after the argument list. We need to keep track of all the arguments seen so far and the get and put names generated for each, in addition to the arguments left to process. After we’ve processed all the identifiers, then we have all the names we need.\nHere is the definition of define-for-cbr:\n> ```racket\n> ( define-syntax define-for-cbr\n> ( syntax-rules ( )\n> [ ( define-for-cbr do-f ( id0 id ... )\n> ( gens ... ) body )\n> ( define-for-cbr do-f ( id ... )\n> ( gens ... ( id0 get put ) ) body ) ]\n> [ ( define-for-cbr do-f ( )\n> ( ( id get put ) ... ) body )\n> ( define ( do-f get ... put ... )\n> ( define-get/put-id id get put ) ...\n> body ) ] ) )\n> ```\nStep-by-step, expansion proceeds as follows:\n> ```racket\n> ( define-for-cbr do-f ( a b )\n> ( ) ( swap a b ) )\n> => ( define-for-cbr do-f ( b )\n> ( [ a get_1 put_1 ] ) ( swap a b ) )\n> => ( define-for-cbr do-f ( )\n> ( [ a get_1 put_1 ] [ b get_2 put_2 ] ) ( swap a b ) )\n> => ( define ( do-f get_1 get_2 put_1 put_2 )\n> ( define-get/put-id a get_1 put_1 )\n> ( define-get/put-id b get_2 put_2 )\n> ( swap a b ) )\n> ```"} {"text": "### 13.2 Initialization Arguments\nThe “subscripts” on get_1, get_2, put_1, and put_2 are inserted by the macro expander to preserve lexical scope, since the get generated by each iteration of define-for-cbr should not bind the get generated by a different iteration. In other words, we are essentially tricking the macro expander into generating fresh names for us, but the technique illustrates some of the surprising power of pattern-based macros with automatic lexical scope.\nThe last expression eventually expands to just\n> ```racket\n> ( define ( do-f get_1 get_2 put_1 put_2 )\n> ( let ( [ tmp ( get_1 ) ] )\n> ( put_1 ( get_2 ) )\n> ( put_2 tmp ) ) )\n> ```\nwhich implements the call-by-name function f.\nTo summarize, then, we can add call-by-reference functions to Racket with just three small pattern-based macros: define-cbr, define-for-cbr, and define-get/put-id.\n------------------------------------------------------------------------"} {"text": "# 16.2 General Macro Transformers"} {"text": "### 16.2 General Macro Transformers\nThe [define-syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define-syntax%2529%2529&version=8.18.0.13) form creates a transformer binding for an identifier, which is a binding that can be used at compile time while expanding expressions to be evaluated at run time. The compile-time value associated with a transformer binding can be anything; if it is a procedure of one argument, then the binding is used as a macro, and the procedure is the macro transformer."} {"text": "# 16.2 General Macro Transformers\n| |\n|----------------------------------------------------------------------------------------------------------------|\n|     [16.2.1 Syntax Objects](stx-obj.html) |\n|     [16.2.2 Macro Transformer Procedures](macro-transformers.html) |\n|     [16.2.3 Mixing Patterns and Expressions: syntax-case](syntax-case.html) |\n|     [16.2.4 with-syntax and generate-temporaries](with-syntax.html) |\n|     [16.2.5 Compile and Run-Time Phases](stx-phases.html) |\n|     [16.2.6 General Phase Levels](phases.html) |\n|       [16.2.6.1 Phases and Bindings](phases.html#%28part._.Phases_and_.Bindings%29) |\n|       [16.2.6.2 Phases and Modules](phases.html#%28part._.Phases_and_.Modules%29) |\n|     [16.2.7 Tainted Syntax](stx-certs.html) |\n------------------------------------------------------------------------"} {"text": "# 16.2.1 Syntax Objects"} {"text": "#### 16.2.1 Syntax Objects\nThe input and output of a macro transformer (i.e., source and replacement forms) are represented as syntax objects. A syntax object contains symbols, lists, and constant values (such as numbers) that essentially correspond to the [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13)d form of the expression. For example, a representation of the expression ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) 1 2) contains the symbol '+ and the numbers 1 and 2, all in a list. In addition to this quoted content, a syntax object associates source-location and lexical-binding information with each part of the form. The source-location information is used when reporting syntax errors (for example), and the lexical-binding information allows the macro system to maintain lexical scope. To accommodate this extra information, the representation of the expression ([+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=generic-numbers.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._%252B%2529%2529&version=8.18.0.13) 1 2) is not merely '(+ 1 2), but a packaging of '(+ 1 2) into a syntax object."} {"text": "# 16.2.1 Syntax Objects\nTo create a literal syntax object, use the [syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax%2529%2529&version=8.18.0.13) form:\n> ```racket\n> > ( syntax ( + 1 2 ) )\n> #\n> ```\nIn the same way that ' abbreviates [quote](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=quote.html%23%2528form._%2528%2528quote._%7E23%7E25kernel%2529._quote%2529%2529&version=8.18.0.13), #' abbreviates [syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax%2529%2529&version=8.18.0.13):\n> ```racket\n> > #' ( + 1 2 )\n> #\n> ```"} {"text": "# 16.2.1 Syntax Objects\nA syntax object that contains just a symbol is an identifier syntax object. Racket provides some additional operations specific to identifier syntax objects, including the [identifier?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fstx..rkt%2529._identifier%7E3f%2529%2529&version=8.18.0.13) operation to detect identifiers. Most notably, [free-identifier=?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxcmp.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._free-identifier%7E3d%7E3f%2529%2529&version=8.18.0.13) determines whether two identifiers refer to the same binding:\n> ```racket\n> > ( identifier? #' car )\n> #t\n> > ( identifier? #' ( + 1 2 ) )\n> #f\n> > ( free-identifier=? #' car #' cdr )\n> #f\n> > ( free-identifier=? #' car #' car )\n> #t\n> > ( require ( only-in racket/base [ car also-car ] ) )\n> > ( free-identifier=? #' car #' also-car )\n> #t\n> ```\nTo see the lists, symbols, numbers, etc. within a syntax object, use [syntax->datum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-%7E3edatum%2529%2529&version=8.18.0.13):\n> ```racket\n> > ( syntax->datum #' ( + 1 2 ) )\n> '(+ 1 2)\n> ```"} {"text": "# 16.2.1 Syntax Objects\nThe [syntax-e](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-e%2529%2529&version=8.18.0.13) function is similar to [syntax->datum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-%7E3edatum%2529%2529&version=8.18.0.13), but it unwraps a single layer of source-location and lexical-context information, leaving sub-forms that have their own information wrapped as syntax objects:\n> ```racket\n> > ( syntax-e #' ( + 1 2 ) )\n> '(# # #)\n> ```\nThe [syntax-e](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-e%2529%2529&version=8.18.0.13) function always leaves syntax-object wrappers around sub-forms that are represented via symbols, numbers, and other literal values. The only time it unwraps extra sub-forms is when unwrapping a pair, in which case the [cdr](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=pairs.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._cdr%2529%2529&version=8.18.0.13) of the pair may be recursively unwrapped, depending on how the syntax object was constructed."} {"text": "# 16.2.1 Syntax Objects\nThe opposite of [syntax->datum](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-%7E3edatum%2529%2529&version=8.18.0.13) is, of course, [datum->syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._datum-%7E3esyntax%2529%2529&version=8.18.0.13). In addition to a datum like '(+ 1 2), [datum->syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._datum-%7E3esyntax%2529%2529&version=8.18.0.13) needs an existing syntax object to donate its lexical context, and optionally another syntax object to donate its source location:\n> ```racket\n> > ( datum->syntax #' lex ' ( + 1 2 ) #' srcloc )\n> #\n> ```\nIn the above example, the lexical context of #'lex is used for the new syntax object, while the source location of #'[srcloc](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=exns.html%23%2528def._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._srcloc%2529%2529&version=8.18.0.13) is used."} {"text": "# 16.2.1 Syntax Objects\nWhen the second (i.e., the “datum”) argument to [datum->syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._datum-%7E3esyntax%2529%2529&version=8.18.0.13) includes syntax objects, those syntax objects are preserved intact in the result. That is, deconstructing the result with [syntax-e](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-e%2529%2529&version=8.18.0.13) eventually produces the syntax objects that were given to [datum->syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._datum-%7E3esyntax%2529%2529&version=8.18.0.13).\n------------------------------------------------------------------------"} {"text": "# 16.2.2 Macro Transformer Procedures"} {"text": "#### 16.2.2 Macro Transformer Procedures\nAny procedure of one argument can be a [macro transformer](proc-macros.html#%28tech._macro._transformer%29). As it turns out, the [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13) form is a macro that expands to a procedure form. For example, if you evaluate a [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13) form directly (instead of placing on the right-hand of a [define-syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define-syntax%2529%2529&version=8.18.0.13) form), the result is a procedure:\n> ```racket\n> > ( syntax-rules ( ) [ ( nothing ) something ] )\n> #\n> ```"} {"text": "# 16.2.2 Macro Transformer Procedures\nInstead of using [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13), you can write your own macro transformer procedure directly using [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13). The argument to the procedure is a [syntax object](stx-obj.html#%28tech._syntax._object%29) that represents the source form, and the result of the procedure must be a [syntax object](stx-obj.html#%28tech._syntax._object%29) that represents the replacement form:\n> ```racket\n> > ( define-syntax self-as-string ( lambda ( stx ) ( datum->syntax stx ( format \"~s\" ( syntax->datum stx ) ) ) ) )\n> > ( self-as-string ( + 1 2 ) )\n> \"(self-as-string (+ 1 2))\"\n> ```"} {"text": "# 16.2.2 Macro Transformer Procedures\nThe source form passed to a macro transformer represents an expression in which its identifier is used in an application position (i.e., after a parenthesis that starts an expression), or it represents the identifier by itself if it is used as an expression position and not in an application position.The procedure produced by [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13) raises a syntax error if its argument corresponds to a use of the identifier by itself, which is why [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13) does not implement an [identifier macro](pattern-macros.html#%28tech._identifier._macro%29).\n> ```racket\n> > ( self-as-string ( + 1 2 ) )\n> \"(self-as-string (+ 1 2))\"\n> > self-as-string\n> \"self-as-string\"\n> ```"} {"text": "# 16.2.2 Macro Transformer Procedures\nThe [define-syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define-syntax%2529%2529&version=8.18.0.13) form supports the same shortcut syntax for functions as [define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=define.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._define%2529%2529&version=8.18.0.13), so that the following self-as-string definition is equivalent to the one that uses [lambda](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=lambda.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fbase..rkt%2529._lambda%2529%2529&version=8.18.0.13) explicitly:\n> ```racket\n> > ( define-syntax ( self-as-string stx ) ( datum->syntax stx ( format \"~s\" ( syntax->datum stx ) ) ) )\n> > ( self-as-string ( + 1 2 ) )\n> \"(self-as-string (+ 1 2))\"\n> ```\n------------------------------------------------------------------------"} {"text": "# 16.2.3 Mixing Patterns and Expressions: syntax-case"} {"text": "#### 16.2.3 Mixing Patterns and Expressions: [syntax-case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-case%2529%2529&version=8.18.0.13)\nThe procedure generated by [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13) internally uses [syntax-e](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._syntax-e%2529%2529&version=8.18.0.13) to deconstruct the given syntax object, and it uses [datum->syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stxops.html%23%2528def._%2528%2528quote._%7E23%7E25kernel%2529._datum-%7E3esyntax%2529%2529&version=8.18.0.13) to construct the result. The [syntax-rules](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-rules%2529%2529&version=8.18.0.13) form doesn’t provide a way to escape from pattern-matching and template-construction mode into an arbitrary Racket expression."} {"text": "# 16.2.3 Mixing Patterns and Expressions: syntax-case\nThe [syntax-case](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=reference&rel=stx-patterns.html%23%2528form._%2528%2528lib._racket%252Fprivate%252Fstxcase-scheme..rkt%2529._syntax-case%2529%2529&version=8.18.0.13) form lets you mix pattern matching, template construction, and arbitrary expressions:\n> > ```\n(syntax-case stx-expr (literal-id ...)\n> > [ pattern expr ]\n> > ... )\n```\n(shifted)\t→\t\n(-> syntax-case #' (+ 1 2) () [ (op n1 n2) #' (- n1 n2) ])```\n(Simple)\t→\t\n(-> Components)\n```\n(Parsing)\t→\t\n(-> - 4 (+ 1 1))```\nobjects:\ndefined:\nevaluate: ( begin ( define x ( vector 10 20 ) )\n( define y x )\n( vector-set! x 0 11 )\n( vector-ref y 0 ) )\n→ objects: (define  (vector 10 20))\ndefined:\nevaluate: ( begin ( define x )\n( define y x )\n( vector-set! x 0 11 )\n( vector-ref y 0 ) )\n→ objects: (define  (vector 10 20))\ndefined: (define x )\nevaluate: ( begin ( void )\n( define y x )\n( vector-set! x 0 11 )\n( vector-ref y 0 ) )\n→ objects: (define  (vector 10 20))\ndefined: (define x )\nevaluate: ( begin ( define y x )\n( vector-set! x 0 11 )\n( vector-ref y 0 ) )\n→ objects: (define  (vector 10 20))\ndefined: (define x )\nevaluate: ( begin ( define y )\n( vector-set! x 0 11 )\n( vector-ref y 0 ) )\n→ objects: (define  (vector 10 20))\ndefined: ( define x )\n( define y )\nevaluate: ( begin ( void )\n( vector-set! x 0 11 )\n( vector-ref y 0 ) )\n→ objects: (define  (vector 10 20))\ndefined: ( define x )\n( define y )\nevaluate: ( begin ( vector-set! x 0 11 )\n( vector-ref y 0 ) )\n→ objects: (define  (vector 10 20))\ndefined: ( define x )\n( define y )\nevaluate: ( begin ( vector-set! 0 11 )\n( vector-ref y 0 ) )\n→ objects: (define  (vector 11 20))\ndefined: ( define x )\n( define y )\nevaluate: ( begin ( void )\n( vector-ref y 0 ) )\n→ objects: (define  (vector 11 20))\ndefined: ( define x )\n( define y )\nevaluate: (vector-ref y 0)\n→ objects: (define  (vector 11 20))\ndefined: ( define x )\n( define y )\nevaluate: (vector-ref  0)\n→ objects: (define  (vector 11 20))\ndefined: ( define x )\n( define y )\nevaluate: 11"} {"text": "# 16.2.3 Mixing Patterns and Expressions: syntax-case\n```\n\n\nThe distinction between a [top-level variable](#%28tech._top._level._variable%29) and an object reference is crucial. A [top-level variable](#%28tech._top._level._variable%29) is not a [value](#%28tech._value%29), so it must be evaluated. Each time a [variable](#%28tech._variable%29) expression is evaluated, the value of the variable is extracted from the current set of definitions. An object reference, in contrast, is a value and therefore needs no further evaluation. The evaluation steps above use angle-bracketed \\ for an object reference to distinguish it from a [variable](#%28tech._variable%29) name.\n\nAn object reference can never appear directly in a text-based source program. A program representation created with [datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29), however, can embed direct references to existing [objects](#%28tech._object%29).\n\n#### 1.1.6 Garbage Collection\n\n> > > \"+\"See [Memory Management](memory.html) for functions related to garbage collection.\n\nIn the program state\n\n```\nobjects: ( define ( vector 10 20 ) )\n( define ( vector 0 ) )\ndefined: (define x )\nevaluate: (+ 1 x)"} {"text": "# 16.2.3 Mixing Patterns and Expressions: syntax-case\n```\n(x)\t→\t\n(-> define \\ (lambda (x) (+ x 10)))```\nobjects: (define  (lambda (x) (+ x 10)))\ndefined: (define f )\nevaluate: ( 7)\n→ objects: (define  (lambda (x) (+ x 10)))\ndefined: ( define f )\n( define xloc 7 )\nevaluate: (+ xloc 10)\n→ objects: (define  (lambda (x) (+ x 10)))\ndefined: ( define f )\n( define xloc 7 )\nevaluate: (+ 7 10)\n→ objects: (define  (lambda (x) (+ x 10)))\ndefined: ( define f )\n( define xloc 7 )\nevaluate: 17\n```\nA [location](#%28tech._location%29) is the same as a [top-level variable](#%28tech._top._level._variable%29), but when a [location](#%28tech._location%29) is generated, it (conceptually) uses a name that has not been used before and that cannot be generated again or accessed directly.\nGenerating a [location](#%28tech._location%29) in this way means that [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) evaluates for [local variables](#%28tech._local._variable%29), including argument variables, in the same way as for [top-level variables](#%28tech._top._level._variable%29), because the [local variable](#%28tech._local._variable%29) is always replaced with a [location](#%28tech._location%29) by the time the [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) form is evaluated:"} {"text": "# 16.2.3 Mixing Patterns and Expressions: syntax-case\n```\nobjects: (define  (lambda (x) (begin (set! x 3) x)))\ndefined: (define f )\nevaluate: (f 7)\n→ objects: (define  (lambda (x) (begin (set! x 3) x)))\ndefined: (define f )\nevaluate: ( 7)\n→ objects: (define  (lambda (x) (begin (set! x 3) x)))\ndefined: ( define f )\n( define xloc 7 )\nevaluate: (begin (set! xloc 3) xloc)\n→ objects: (define  (lambda (x) (begin (set! x 3) x)))\ndefined: ( define f )\n( define xloc 3 )\nevaluate: (begin (void) xloc)\n→ objects: (define  (lambda (x) (begin (set! x 3) x)))\ndefined: ( define f )\n( define xloc 3 )\nevaluate: xloc\n→ objects: (define  (lambda (x) (begin (set! x 3) x)))\ndefined: ( define f )\n( define xloc 3 )\nevaluate: 3\n```\n(x)\t→\t\n(-> define x ' orig)```\n(parameter)\t→\t\n(-> #%plain-app variable-reference-from-unsafe?\n (#%variable-reference))\n```\n(decimal)\t→\t\n(-> see Weak Boxes)```\nExamples:\n (#1=100 #1# #1#)  reads equal to  (list 100 100 100)\n #0=(1 . #0#)  reads equal to  ( let* ( [ ph ( make-placeholder #f ) ]\n[ v ( cons 1 ph ) ] )\n(placeholder-set! ph v)\n( make-reader-graph v ) )\n```\n(unquoted)\t→\t\n(-> ASCII 32)```\nindicates that the result of each parameter-expr must be a value v for which ([parameter?](parameters.html#%28def._%28%28quote._~23~25kernel%29._parameter~3f%29%29) v) returns true."} {"text": "### 2.3 Notation for Function Documentation\nProcedures and other values are described using a notation based on [contract](contracts.html#%28tech._contract%29)s. In essence, these contracts describe the interfaces of the documented library using Racket predicates and expressions.\nFor example, the following is the header of the definition of a typical procedure:\n> > ```\n(char → integer char)  →  exact-integer?\n  char : char?\n```\nThe function being defined, char → integer, is typeset as if it were being applied. The metavariables that come after the function name stand in for arguments. The white text in the corner identifies the kind of value that is being documented.\n\nEach metavariable is described with a contract. In the preceding example, the metavariable char has the contract char?. This contract specifies that any argument char that answers true to the char? predicate is valid. The documented function may or may not actually check this property, but the contract signals the intent of the implementer.\n\nThe contract on the right of the arrow, exact-integer? in this case, specifies the expected result that is produced by the function.\n\nContract specifications can be more expressive than just names of predicates. Consider the following header for argmax:\n\n> > ```\n(argmax proc lst)  →  any\n  proc : ( →  any/c real?)\n  lst : (and/c pair? list?)```\n\n\nThe contract ([->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29) [real?](number-types.html#%28def._%28%28quote._~23~25kernel%29._real~3f%29%29)) denotes a function contract specifying that proc’s argument can be any single value and the result should be a real number. The contract ([and/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) [pair?](pairs.html#%28def._%28%28quote._~23~25kernel%29._pair~3f%29%29) [list?](pairs.html#%28def._%28%28quote._~23~25kernel%29._list~3f%29%29)) for lst specifies that lst should pass both [pair?](pairs.html#%28def._%28%28quote._~23~25kernel%29._pair~3f%29%29) and [list?](pairs.html#%28def._%28%28quote._~23~25kernel%29._list~3f%29%29) (i.e., that it is a non-empty list).\n\nBoth [->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) and [and/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) are examples of [contract combinator](contracts.html#%28tech._contract._combinator%29)s. Contract combinators such as [or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29), [cons/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._cons%2Fc%29%29), [listof](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._listof%29%29), and others are used throughout the documentation. Clicking on the hyperlinked combinator name will provide more information on its meaning.\n\nA Racket function may be documented as having one or more optional arguments. The [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) function is an example of such a function:\n\n> > ```\n(current-input-port)\t→\t\n(-> current-input-port)\n```"} {"text": "### 2.3 Notation for Function Documentation\n(current-input-port)\t→\t\n(-> any/c any/c . → . any/c)```\nThe brackets around the extract-key and cache-keys? arguments indicate that they are optional as before. The contract section of the header shows the default values that are provided for these keyword arguments."} {"text": "### 2.4 Notation for Structure Type Documentation\nA [structure type](structures.html#%28tech._structure._type%29) is also documented using contract notation:\n> >
\n

struct

\n

([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) color (red green blue alpha))

  red : ([and/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) [natural-number/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._natural-number%2Fc%29%29) ([<=/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._~3c~3d%2Fc%29%29) 255))
  green : ([and/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) [natural-number/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._natural-number%2Fc%29%29) ([<=/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._~3c~3d%2Fc%29%29) 255))
  blue : ([and/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) [natural-number/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._natural-number%2Fc%29%29) ([<=/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._~3c~3d%2Fc%29%29) 255))
  alpha : ([and/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) [natural-number/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._natural-number%2Fc%29%29) ([<=/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._~3c~3d%2Fc%29%29) 255))
"} {"text": "### 2.4 Notation for Structure Type Documentation\nThe structure type is typeset as it were declared in the source code of a program using the [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) form. Each field of the structure is documented with a corresponding contract that specifies the values that are accepted for that field.\nIn the example above, the structure type color has four fields: red, green, blue, and alpha. The constructor for the structure type accepts field values that satisfy ([and/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) [natural-number/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._natural-number%2Fc%29%29) ([<=/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._~3c~3d%2Fc%29%29) 255)), i.e., non-negative exact integers up to 255.\nAdditional keywords may appear after the field names in the documentation for a structure type:\n> >
\n

struct

"} {"text": "### 2.4 Notation for Structure Type Documentation\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) data-source (connector args extensions)
    #:mutable)
  connector : ([or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) 'postgresql 'mysql 'sqlite3 'odbc)
  args : [list?](pairs.html#%28def._%28%28quote._~23~25kernel%29._list~3f%29%29)
  extensions : ([listof](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._listof%29%29) ([list/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._list%2Fc%29%29) [symbol?](symbols.html#%28def._%28%28quote._~23~25kernel%29._symbol~3f%29%29) [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29)))
\nHere, the #:mutable keyword indicates that the fields of instances of the data-source structure type can be mutated with their respective setter functions."} {"text": "### 2.5 Notation for Parameter Documentation\nA [parameter](eval-model.html#%28tech._parameter%29) is documented the same way as a function:\n> > ```\n(current-command-line-arguments)\t→\t\n(-> vectorof string?)\n(current-command-line-arguments argv) → void?\n argv\t:\t\n(-> vectorof string?)\n```\n(current-module-declare-name)\t→\t\n(-> module duck racket/base (provide num-eggs quack) (define num-eggs 2) (define (quack n) (unless (zero? n) (printf \"quack\\n\") (quack (sub1 n)))))```\n\n>\n> \n\n>\n> \n\n>\n> Specifies a library available via the PLaneT server.\n>\n> \n\n>\n> The first form is a shorthand for the last one, where the id’s character sequence must match the following ‹spec› grammar:\n>\n> | | | | |\n> |-----|-----------|--------|-------------------------------------------------|\n> |   | ‹spec› |  ::=  | ‹owner› / ‹pkg› ‹lib› |\n> |   | ‹owner› |  ::=  | ‹elem› |\n> |   | ‹pkg› |  ::=  | ‹elem›  \\|  ‹elem› : ‹version› |\n> |   | ‹version› |  ::=  | ‹int›  \\|  ‹int› : ‹minor› |\n> |   | ‹minor› |  ::=  | ‹int›  \\|  \\<= ‹int›  \\|>= ‹int›  \\|  = ‹int› |\n> |   | |   \\|   | ‹int› - ‹int› |\n> |   | ‹lib› |  ::=  | ‹empty›  \\|  / ‹path› |\n> |   | ‹path› |  ::=  | ‹elem›  \\|  ‹elem› / ‹path› |\n>\n> and where an ‹elem› is a non-empty sequence of characters that are ASCII letters, ASCII digits, -, +, \\_, or % followed by lowercase hexadecimal digits (that do not encode one of the other allowed characters), and an ‹int› is a non-empty sequence of ASCII digits. As this shorthand is expended, a \".plt\" extension is added to ‹pkg›, and a \".rkt\" extension is added to ‹path›; if no ‹path› is included, \"main.rkt\" is used in the expansion.\n>\n> A ([planet](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._planet%29%29) string) form is like a ([planet](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._planet%29%29) id) form with the identifier converted to a string, except that the string can optionally end with a file extension (i.e., a .) for a ‹path›. A \".ss\" file extension is converted to \".rkt\".\n>\n> In the more general last form of a [planet](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._planet%29%29) module path, the rel-strings are similar to the [lib](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lib%29%29) form, except that the (user-string pkg-string vers) names a PLaneT-based package instead of a [collection](collects.html#%28tech._collection%29). A version specification can include an optional major and minor version, where the minor version can be a specific number or a constraint: (nat nat) specifies an inclusive range, (= nat) specifies an exact match, (+ nat) specifies a minimum version and is equivalent to just nat, and (- nat) specifies a maximum version. The =, +, and - identifiers in a minor-version constraint are recognized symbolically.\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > ; \"main.rkt\" in package \"farm\" by \"mcdonald\" :\n> > > ( require ( planet mcdonald/farm ) )\n> > ; \"main.rkt\" in version >= 2.0 of \"farm\" by \"mcdonald\" :\n> > > ( require ( planet mcdonald/farm:2 ) )\n> > ; \"main.rkt\" in version >= 2.5 of \"farm\" by \"mcdonald\" :\n> > > ( require ( planet mcdonald/farm:2:5 ) )\n> > ; \"duck.rkt\" in version >= 2.5 of \"farm\" by \"mcdonald\" :\n> > > ( require ( planet mcdonald/farm:2:5/duck ) )\n> > ```\n>\n> \n\n> \n\n>\n> >
\n\n

syntax

\n\n

([submod](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._submod%29%29) root-module-path submod-path-element ...)

([submod](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._submod%29%29) \".\" submod-path-element ...)
([submod](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._submod%29%29) \"..\" submod-path-element ...)
\n>\n> \n\n>\n> \n\n>\n> Identifies a [submodule](eval-model.html#%28tech._submodule%29) within the module specified by root-module-path or relative to the current module in the case of ([submod](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._submod%29%29) \".\" ....), where ([submod](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._submod%29%29) \"..\" submod-path-element [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) is equivalent to ([submod](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._submod%29%29) \".\" \"..\" submod-path-element [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)). Submodules have symbolic names, and a sequence of identifiers as submod-path-elements determine a path of successively nested submodules with the given names. A \"..\" as a submod-path-element names the enclosing module of a submodule, and it’s intended for use in ([submod](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._submod%29%29) \".\" ....) and ([submod](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._submod%29%29) \"..\" ....) forms.\n>\n> \n\nAs [require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) prepares to handle a sequence of require-specs, it logs a “prefetch” message to the [current logger](logging.html#%28tech._current._logger%29) at the 'info level, using the name 'module-prefetch, and including message data that is a list of two elements: a list of [module paths](Module_Names_and_Loading.html#%28tech._module._path%29) that appear to be imported, and a directory path to use for relative module paths. The logged list of module paths may be incomplete, but a compilation manager can use approximate prefetch information to start on compilations in parallel.\n\nChanged in version 6.0.1.10 of package base: Added prefetch logging.\n\n>
\n\n

syntax

\n\n

([local-require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._local-require%29%29) require-spec ...)

\n\nLike [require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29), but for use in a [internal-definition context](syntax-model.html#%28tech._internal._definition._context%29) to import just into the local context. Only bindings from [phase level](syntax-model.html#%28tech._phase._level%29) 0 are imported.\n\nExamples:\n\n> ```racket\n> > ( let ( ) ( local-require racket/control ) fcontrol )\n> #\n> > fcontrol\n> fcontrol: undefined;\n> cannot reference an identifier before its definition\n> in module: top-level\n> ```\n\n> > > \"+\"[Exports: provide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=module-provide.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29).\n\n>
\n\n

syntax

\n\n

([provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) provide-spec ...)

 
provide-spec = id
  | ([all-defined-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-defined-out%29%29))
  | ([all-from-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-from-out%29%29) module-path ...)
  | ([rename-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._rename-out%29%29) [orig-id export-id] ...)
  | ([except-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._except-out%29%29) provide-spec provide-spec ...)
  | ([prefix-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._prefix-out%29%29) prefix-id provide-spec)
  | ([struct-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct-out%29%29) id)
  | ([combine-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._combine-out%29%29) provide-spec ...)
  | ([protect-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._protect-out%29%29) provide-spec ...)
  | ([for-meta](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-meta%29%29) phase-level provide-spec ...)
  | ([for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-syntax%29%29) provide-spec ...)
  | ([for-template](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-template%29%29) provide-spec ...)
  | ([for-label](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-label%29%29) provide-spec ...)
  | ([for-space](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-space%29%29) space provide-spec ...)
  | derived-provide-spec
     
phase-level = exact-integer
  | #f
     
space = id
  | #f
\n\nDeclares exports from a module. A [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) form must appear in a [module context](syntax-model.html#%28tech._module._context%29) or a [module-begin context](syntax-model.html#%28tech._module._begin._context%29).\n\nA provide-spec indicates one or more bindings to provide. For each exported binding, the external name is a symbol that can be different from the symbolic form of the identifier that is bound within the module. Also, each export is drawn from a particular [phase level](syntax-model.html#%28tech._phase._level%29) and exported at the same [phase level](syntax-model.html#%28tech._phase._level%29); by default, the relevant phase level is the number of [begin-for-syntax](begin.html#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29) forms that enclose the [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) form. Finally, each export is drawn from a [binding space](syntax-model.html#%28tech._binding._space%29) and exported at the same [binding space](syntax-model.html#%28tech._binding._space%29).\n\nThe syntax of provide-spec can be extended by bindings to [provide transformers](stxtrans.html#%28tech._provide._transformer%29) or [provide pre-transformers](stxtrans.html#%28tech._provide._pre._transformer%29), such as via [define-provide-syntax](define.html#%28form._%28%28lib._racket%2Fprovide-syntax..rkt%29._define-provide-syntax%29%29), but the pre-defined forms are as follows.\n\n> > | |\n> > |-----|\n> > | id |\n>\n> Exports id, which must be [bound](syntax-model.html#%28tech._bound%29) within the module (i.e., either defined or imported) at the relevant [phase level](syntax-model.html#%28tech._phase._level%29) and [binding space](syntax-model.html#%28tech._binding._space%29). The symbolic form of id is used as the external name, and the symbolic form of the defined or imported identifier must match (otherwise, the external name could be ambiguous).\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module nest racket ( provide num-eggs ) ( define num-eggs 2 ) )\n> > > ( require ' nest )\n> > > num-eggs\n> > 2\n> > ```\n>\n> \n\n>\n> If id has a transformer binding to a [rename transformer](syntax-model.html#%28tech._rename._transformer%29), then the transformer affects the exported binding. See [make-rename-transformer](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._make-rename-transformer%29%29) for more information.\n\n> \n\n>\n> >
\n\n

syntax

\n\n

([all-defined-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-defined-out%29%29))

\n>\n> \n\n>\n> \n\n>\n> Exports all identifiers that are defined at the relevant [phase level](syntax-model.html#%28tech._phase._level%29) within the exporting module, and that have the same lexical context as the ([all-defined-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-defined-out%29%29)) form, excluding bindings to [rename transformers](syntax-model.html#%28tech._rename._transformer%29) where the target identifier has the 'not-provide-all-defined [syntax property](stxprops.html#%28tech._syntax._property%29). The external name for each identifier is the symbolic form of the identifier. Only identifiers accessible from the lexical context of the ([all-defined-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-defined-out%29%29)) form are included; that is, macro-introduced imports are not re-exported, unless the ([all-defined-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-defined-out%29%29)) form was introduced at the same time.\n>\n> \n\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module nest racket ( provide ( all-defined-out ) ) ( define num-eggs 2 ) )\n> > > ( require ' nest )\n> > > num-eggs\n> > 2\n> > ```\n>\n> \n\n> \n\n>\n> >
\n\n

syntax

\n\n

([all-from-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-from-out%29%29) module-path ...)

\n>\n> \n\n>\n> \n\n>\n> Exports all identifiers that are imported into the exporting module using a require-spec built on each module-path (see [Importing and Exporting: require and provide]()) with no [phase-level](syntax-model.html#%28tech._phase._level%29) shift. The symbolic name for export is derived from the name that is bound within the module, as opposed to the symbolic name of the export from each module-path. Only identifiers accessible from the lexical context of the module-path are included; that is, macro-introduced imports are not re-exported, unless the module-path was introduced at the same time.\n>\n> \n\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module nest racket ( provide num-eggs ) ( define num-eggs 2 ) )\n> > > ( module hen-house racket ( require ' nest ) ( provide ( all-from-out ' nest ) ) )\n> > > ( require ' hen-house )\n> > > num-eggs\n> > 2\n> > ```\n>\n> \n\n> \n\n>\n> >
\n\n

syntax

\n\n

([rename-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._rename-out%29%29) [orig-id export-id] ...)

\n>\n> \n\n>\n> \n\n>\n> Exports each orig-id, which must be [bound](syntax-model.html#%28tech._bound%29) within the module at the relevant [phase level](syntax-model.html#%28tech._phase._level%29) and [binding space](syntax-model.html#%28tech._binding._space%29). The symbolic name for each export is export-id instead of orig-id.\n>\n> \n\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module nest racket ( provide ( rename-out [ count num-eggs ] ) ) ( define count 2 ) )\n> > > ( require ' nest )\n> > > num-eggs\n> > 2\n> > > count\n> > count: undefined;\n> > cannot reference an identifier before its definition\n> > in module: top-level\n> > ```\n>\n> \n\n> \n\n>\n> >
\n\n

syntax

\n\n

([except-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._except-out%29%29) provide-spec provide-spec ...)

\n>\n> \n\n>\n> \n\n>\n> Like the first provide-spec, but omitting the bindings listed in each subsequent provide-spec. If one of the latter bindings is not included in the initial provide-spec, a syntax error is reported. The symbolic export name information in the latter provide-specs is ignored; only the bindings are used.\n>\n> \n\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module nest racket ( provide ( except-out ( all-defined-out ) num-chicks ) ) ( define num-eggs 2 ) ( define num-chicks 3 ) )\n> > > ( require ' nest )\n> > > num-eggs\n> > 2\n> > > num-chicks\n> > num-chicks: undefined;\n> > cannot reference an identifier before its definition\n> > in module: top-level\n> > ```\n>\n> \n\n> \n\n>\n> >
\n\n

syntax

\n\n

([prefix-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._prefix-out%29%29) prefix-id provide-spec)

\n>\n> \n\n>\n> \n\n>\n> Like provide-spec, but with each symbolic export name from provide-spec prefixed with prefix-id.\n>\n> \n\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module nest racket ( provide ( prefix-out chicken: num-eggs ) ) ( define num-eggs 2 ) )\n> > > ( require ' nest )\n> > > chicken:num-eggs\n> > 2\n> > ```\n>\n> \n\n>\n> A [syntax property](stxprops.html#%28tech._syntax._property%29) with the key 'import-or-export-prefix-ranges is added to the exported identifier in the expanded form of [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29).\n>\n> Changed in version 8.9.0.5 of package base: Added the 'import-or-export-prefix-ranges syntax property.\n\n> \n\n>\n> >
\n\n

syntax

\n\n

([struct-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct-out%29%29) id)

\n>\n> \n\n>\n> \n\n>\n> Exports the bindings associated with a structure type id. Typically, id is bound with ([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) id ....); more generally, id must have a [transformer](syntax-model.html#%28tech._transformer%29) binding of structure-type information at the relevant [phase level](syntax-model.html#%28tech._phase._level%29); see [Structure Type Transformer Binding](structinfo.html). Furthermore, for each identifier mentioned in the structure-type information, the enclosing module must define or import one identifier that is [free-identifier=?](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._free-identifier~3d~3f%29%29). If the structure-type information includes a super-type identifier, and if the identifier has a [transformer](syntax-model.html#%28tech._transformer%29) binding of structure-type information, the accessor and mutator bindings of the super-type are not included by [struct-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct-out%29%29) for export.\n>\n> \n\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module nest racket ( provide ( struct-out egg ) ) ( struct egg ( color wt ) ) )\n> > > ( require ' nest )\n> > > ( egg-color ( egg ' blue 10 ) )\n> > 'blue\n> > ```\n>\n> \n\n> \n\n>\n> >
\n\n

syntax

\n\n

([combine-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._combine-out%29%29) provide-spec ...)

\n>\n> \n\n>\n> \n\n>\n> The union of the provide-specs.\n>\n> \n\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module nest racket ( provide ( combine-out num-eggs num-chicks ) ) ( define num-eggs 2 ) ( define num-chicks 1 ) )\n> > > ( require ' nest )\n> > > num-eggs\n> > 2\n> > > num-chicks\n> > 1\n> > ```\n>\n> \n\n> \n\n>\n> >
\n\n

syntax

\n\n

([protect-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._protect-out%29%29) provide-spec ...)

\n>\n> \n\n>\n> \n\n>\n> Like the union of the provide-specs, except that the exports are [protected](modprotect.html#%28tech._protected%29): requiring modules may refer to these bindings, but may not extract these bindings from macro expansions or access them via [eval](eval.html#%28def._%28%28quote._~23~25kernel%29._eval%29%29) without access privileges. For more details, see [Code Inspectors](modprotect.html). The provide-spec must specify only bindings that are defined within the exporting module.\n>\n> \n\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module nest racket ( provide num-eggs ( protect-out num-chicks ) ) ( define num-eggs 2 ) ( define num-chicks 3 ) )\n> > > ( define weak-inspector ( make-inspector ( current-code-inspector ) ) )\n> > > ( define ( weak-eval x ) ( parameterize ( [ current-code-inspector weak-inspector ] ) ( define weak-ns ( make-base-namespace ) ) ( namespace-attach-module ( current-namespace ) ' ' nest weak-ns ) ( parameterize ( [ current-namespace weak-ns ] ) ( namespace-require ' ' nest ) ( eval x ) ) ) )\n> > > ( require ' nest )\n> > > ( list num-eggs num-chicks )\n> > '(2 3)\n> > > ( weak-eval ' num-eggs )\n> > 2\n> > > ( weak-eval ' num-chicks )\n> > ?: access disallowed by code inspector to protected variable\n> > from module: 'nest\n> > at: num-chicks\n> > ```\n>\n> \n\n>\n> See also [Code Inspectors for Trusted and Untrusted Code](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=code-inspectors_protect.html&version=8.18.0.13).\n\n> > | |\n> > |-----------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([for-meta](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-meta%29%29) phase-level provide-spec ...) |\n>\n> Like the union of the provide-specs, but adjusted to apply to the [phase level](syntax-model.html#%28tech._phase._level%29) specified by phase-level relative to the current phase level (where #f corresponds to the [label phase level](syntax-model.html#%28tech._label._phase._level%29)). In particular, an id or [rename-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._rename-out%29%29) form as a provide-spec refers to a binding at phase-level relative to the current level, an [all-defined-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-defined-out%29%29) exports only definitions at phase-level relative to the current phase level, and an [all-from-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-from-out%29%29) exports bindings imported with a shift by phase-level.\n>\n> \n\n>\n> Examples:\n>\n> \n\n>\n> \n\n>\n> > ```racket\n> > > ( module nest racket ( begin-for-syntax ( define eggs 2 ) ) ( define chickens 3 ) ( provide ( for-syntax eggs ) chickens ) )\n> > > ( require ' nest )\n> > > ( define-syntax ( test-eggs stx ) ( printf \"Eggs are ~a\\n\" eggs ) #' 0 )\n> > > ( test-eggs )\n> > Eggs are 2\n> > 0\n> > > chickens\n> > 3\n> > > ( module broken-nest racket ( define eggs 2 ) ( define chickens 3 ) ( provide ( for-syntax eggs ) chickens ) )\n> > eval:7:0: provide: provided identifier is not defined or\n> > required\n> > at: eggs\n> > in: (provide (for-syntax eggs) chickens)\n> > > ( module nest2 racket ( begin-for-syntax ( define eggs 2 ) ) ( provide ( for-syntax eggs ) ) )\n> > > ( require ( for-meta 2 racket/base ) ( for-syntax ' nest2 ) )\n> > > ( define-syntax ( test stx ) ( define-syntax ( show-eggs stx ) ( printf \"Eggs are ~a\\n\" eggs ) #' 0 ) ( begin ( show-eggs ) #' 0 ) )\n> > Eggs are 2\n> > > ( test )\n> > 0\n> > ```\n>\n> \n\n> > | |\n> > |---------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-syntax%29%29) provide-spec ...) |\n>\n> Same as ([for-meta](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-meta%29%29) 1 provide-spec [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n\n> > | |\n> > |-------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([for-template](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-template%29%29) provide-spec ...) |\n>\n> Same as ([for-meta](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-meta%29%29) -1 provide-spec [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n\n> > | |\n> > |-------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([for-label](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-label%29%29) provide-spec ...) |\n>\n> Same as ([for-meta](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-meta%29%29) #f provide-spec [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n\n> > | |\n> > |-------------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([for-space](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-space%29%29) space provide-spec ...) |\n>\n> Like the union of the provide-specs, but adjusted to apply to the [binding space](syntax-model.html#%28tech._binding._space%29) specified by space—where space is either an identifier or #f for the [default binding space](syntax-model.html#%28tech._default._binding._space%29). In particular, an id or [rename-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._rename-out%29%29) form as a provide-spec refers to a binding in space, an [all-defined-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-defined-out%29%29) exports only definitions in space, and an [all-from-out](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-from-out%29%29) exports bindings imported into space.\n>\n> When providing a binding for a non-default binding space, normally a module should also provide a binding for the default binding space, where the default-space binding represents the intended meaning of the identifier. When a module later imports the same name in different spaces from modules that adhere to this convention, then if the two modules also (re)export the same binding for the name in the default space, the imports are likely consistent. If the two modules export different bindings for the name in the default space, then attempting to import both modules will trigger an error about conflicting imports, and a programmer can explicitly resolve the mismatch.\n>\n> Added in version 8.2.0.3 of package base.\n\n> > | |\n> > |----------------------|\n> > | derived-provide-spec |\n>\n> See [define-provide-syntax](define.html#%28form._%28%28lib._racket%2Fprovide-syntax..rkt%29._define-provide-syntax%29%29) for information on expanding the set of provide-spec forms.\n\nEach export specified within a module must have a distinct symbolic export name, though the same binding can be specified with the multiple symbolic names.\n\n>
\n\n

syntax

\n\n

([for-meta](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-meta%29%29) phase-level require-spec ...)

\n\nSee [require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) and [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29).\n\n>
\n\n

syntax

\n\n

([for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-syntax%29%29) require-spec ...)

\n\nSee [require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) and [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29).\n\n>
\n\n

syntax

\n\n

([for-template](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-template%29%29) require-spec ...)

\n\nSee [require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) and [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29).\n\n>
\n\n

syntax

\n\n

([for-label](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-label%29%29) require-spec ...)

\n\nSee [require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) and [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29).\n\n>
\n\n

syntax

\n\n

([for-space](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-space%29%29) space require-spec ...)

\n\nSee [require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) and [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29).\n\n>
\n\n

syntax

\n\n

([#%require](#%28form._%28%28quote._~23~25kernel%29._~23~25require%29%29) raw-require-spec ...)

 
raw-require-spec = phaseless-spec
  | (for-meta phase-level raw-require-spec ...)
  | (for-syntax raw-require-spec ...)
  | (for-template raw-require-spec ...)
  | (for-label raw-require-spec ...)
  | (just-meta phase-level raw-require-spec ...)
  | (portal portal-id content)
     
phase-level = exact-integer
  | #f
     
phaseless-spec = spaceless-spec
  | (for-space space phaseless-spec ...)
  | (just-space space spaceless-spec ...)
     
space = id
  | #f
     
spaceless-spec = raw-module-path
  | (only raw-module-path id ...)
  | (prefix prefix-id raw-module-path)
  | (all-except raw-module-path id ...)
  | 
( prefix-all-except prefix-id\n> raw-module-path id ... )
  | (rename raw-module-path local-id exported-id)
     
raw-module-path = raw-root-module-path
  | (submod raw-root-module-path id ...+)
  | (submod \".\" id ...+)
     
raw-root-module-path = (quote id)
  | rel-string
  | (lib rel-string ...)
  | id
  | (file string)
  | 
( planet rel-string\n> ( user-string pkg-string vers ... ) )
  | literal-path
\n\nThe primitive import form, to which [require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) expands. A raw-require-spec is similar to a require-spec in a [require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) form, except that the syntax is more constrained, not composable, and not extensible. Also, sub-form names like for-syntax and lib are recognized symbolically, instead of via bindings. Some nested constraints are not formalized in the grammar above:\n\n- a just-meta form cannot appear within a just-meta form;\n\n- a for-meta, for-syntax, for-template, or for-label form cannot appear within a for-meta, for-syntax, for-template, or for-label form; and\n\n- a for-space form cannot appear within a for-space form.\n\n- a portal form cannot appear within a just-meta form.\n\nExcept for the portal form, each raw-require-spec corresponds to the obvious require-spec, but the rename sub-form has the identifiers in reverse order compared to [rename-in](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._rename-in%29%29).\n\nFor most raw-require-specs, the lexical context of the raw-require-spec determines the context of introduced identifiers. The exception is the rename sub-form, where the lexical context of the local-id is preserved.\n\nA literal-path as a raw-root-module-path corresponds to a path in the sense of [path?](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._path~3f%29%29). Since path values are never produced by [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29), they appear only in programmatically constructed expressions. They also appear naturally as arguments to functions such as [namespace-require](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._namespace-require%29%29), with otherwise take a quoted raw-module-spec.\n\nThe portal form provides a way to define [portal syntax](stxtrans.html#%28tech._portal._syntax%29) at any phase level. A (portal portal-id content), defines portal-id to portal syntax with content effectively quoted to serve as its content.\n\nChanged in version 8.2.0.3 of package base: Added for-space and just-space. \nChanged in version 8.3.0.8: Added portal.\n\n>
\n\n

syntax

\n\n

([#%provide](#%28form._%28%28quote._~23~25kernel%29._~23~25provide%29%29) raw-provide-spec ...)

 
raw-provide-spec = phaseless-spec
  | (for-meta phase-level phaseless-spec ...)
  | (for-syntax phaseless-spec ...)
  | (for-label phaseless-spec ...)
  | (protect raw-provide-spec ...)
     
phase-level = exact-integer
  | #f
     
phaseless-spec = spaceless-spec
  | (for-space space spaceless-spec ...)
  | (protect phaseless-spec ...)
     
space = id
  | #f
     
spaceless-spec = id
  | (rename local-id export-id)
  | (struct struct-id (field-id ...))
  | (all-from raw-module-path)
  | (all-from-except raw-module-path id ...)
  | (all-defined)
  | (all-defined-except id ...)
  | (prefix-all-defined prefix-id)
  | (prefix-all-defined-except prefix-id id ...)
  | (protect spaceless-spec ...)
  | (expand (id . datum))
  | (expand (id . datum) orig-form)
\n\nThe primitive export form, to which [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) expands. A raw-module-path is as for [#%require](#%28form._%28%28quote._~23~25kernel%29._~23~25require%29%29). A protect sub-form cannot appear within a protect sub-form.\n\nLike [#%require](#%28form._%28%28quote._~23~25kernel%29._~23~25require%29%29), the sub-form keywords for [#%provide](#%28form._%28%28quote._~23~25kernel%29._~23~25provide%29%29) are recognized symbolically, and nearly every raw-provide-spec has an obvious equivalent provide-spec via [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29), with the exception of the struct and expand sub-forms.\n\nA (struct struct-id (field-id [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29))) sub-form expands to struct-id, make-struct-id, struct:struct-id, struct-id?, struct-id-field-id for each field-id, and set-struct-id-field-id! for each field-id. The lexical context of the struct-id is used for all generated identifiers.\n\nUnlike [#%require](#%28form._%28%28quote._~23~25kernel%29._~23~25require%29%29), the [#%provide](#%28form._%28%28quote._~23~25kernel%29._~23~25provide%29%29) form is macro-extensible via an explicit expand sub-form; the (id . datum) part is locally expanded as an expression (even though it is not actually an expression), stopping when a [begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) form is produced; if the expansion result is ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) raw-provide-spec [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)), it is spliced in place of the expand form, otherwise a syntax error is reported. If an orig-form part is provided, then it is used instead of the [#%provide](#%28form._%28%28quote._~23~25kernel%29._~23~25provide%29%29) form when raising syntax errors, such as a “provide identifier is not defined” error. The expand sub-form is not normally used directly; it provides a hook for implementing [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) and [provide transformers](stxtrans.html#%28tech._provide._transformer%29).\n\nThe all-from and all-from-except forms re-export only identifiers that are accessible in lexical context of the all-from or all-from-except form itself. That is, macro-introduced imports are not re-exported, unless the all-from or all-from-except form was introduced at the same time. Similarly, all-defined and its variants export only definitions accessible from the lexical context of the spaceless-spec form.\n\nChanged in version 8.2.0.3 of package base: Added for-space. \nChanged in version 8.2.0.5: Added orig-form support to expand.\n\n#### 3.2.1 Additional [require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) Forms\n\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/require](#%28mod-path._racket%2Frequire%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/require](#%28mod-path._racket%2Frequire%29) library, not [racket/base](index.html) or [racket](index.html).\n\nThe following forms support more complex selection and manipulation of sets of imported identifiers.\n\n>
\n\n

syntax

\n\n

([matching-identifiers-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._matching-identifiers-in%29%29) regexp require-spec)

\n\nLike require-spec, but including only imports whose names match regexp. The regexp must be a literal regular expression (see [Regular Expressions](regexp.html)).\n\nExamples:\n\n> ```racket\n> > ( module zoo racket/base ( provide tunafish swordfish blowfish monkey lizard ant ) ( define tunafish 1 ) ( define swordfish 2 ) ( define blowfish 3 ) ( define monkey 4 ) ( define lizard 5 ) ( define ant 6 ) )\n> > ( require racket/require )\n> > ( require ( matching-identifiers-in #rx\"\\\\w*fish\" ' zoo ) )\n> > tunafish\n> 1\n> > swordfish\n> 2\n> > blowfish\n> 3\n> > monkey\n> monkey: undefined;\n> cannot reference an identifier before its definition\n> in module: top-level\n> ```\n\n>
\n\n

syntax

\n\n

([subtract-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._subtract-in%29%29) require-spec subtracted-spec ...)

\n\nLike require-spec, but omitting those imports that would be imported by one of the subtracted-specs.\n\nExamples:\n\n> ```racket\n> > ( module earth racket ( provide land sea air ) ( define land 1 ) ( define sea 2 ) ( define air 3 ) )\n> > ( module mars racket ( provide aliens ) ( define aliens 4 ) )\n> > ( module solar-system racket ( require ' earth ' mars ) ( provide ( all-from-out ' earth ) ( all-from-out ' mars ) ) )\n> > ( require racket/require )\n> > ( require ( subtract-in ' solar-system ' earth ) )\n> > land\n> land: undefined;\n> cannot reference an identifier before its definition\n> in module: top-level\n> > aliens\n> 4\n> ```\n\n>
\n\n

syntax

\n\n

([filtered-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._filtered-in%29%29) proc-expr require-spec)

\n\nApplies an arbitrary transformation on the import names (as strings) of require-spec. The proc-expr must evaluate at expansion time to a single-argument procedure, which is applied on each of the names from require-spec. For each name, the procedure must return either a string for the import’s new name or #f to exclude the import.\n\n> > > The second part of [filtered-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._filtered-in%29%29) is expand-time code evaluated in the scope of the enclosing module. Accordingly, most uses need ([require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) ([for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-syntax%29%29) racket/base)) if [racket/base](index.html) is not already imported [for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-syntax%29%29). For example, [#lang](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=Module_Syntax.html%23%2528part._hash-lang%2529&version=8.18.0.13) [racket](index.html) establishes this import automatically, while [#lang](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=Module_Syntax.html%23%2528part._hash-lang%2529&version=8.18.0.13) [racket/base](index.html) does not.\n\nFor example,\n\n> ```racket\n> ( require ( filtered-in\n> ( lambda ( name )\n> ( and ( regexp-match? #rx\"^[a-z-]+$\" name )\n> ( regexp-replace #rx\"-\" ( string-titlecase name ) \"\" ) ) )\n> racket/base ) )\n> ```\n\nimports only bindings from [racket/base](index.html) that match the pattern #rx\"^\\[a-z-\\]+$\", and it converts the names to “camel case.”\n\n>
\n\n

syntax

\n\n

([path-up](#%28form._%28%28lib._racket%2Frequire..rkt%29._path-up%29%29) rel-string ...)

\n\nSpecifies paths to modules named by the rel-strings similar to using the rel-strings directly, except that if a required module file is not found relative to the enclosing source, it is searched for in the parent directory, and then in the grand-parent directory, etc., all the way to the root directory. The discovered path relative to the enclosing source becomes part of the expanded form.\n\nThis form is useful in setting up a “project environment.” For example, using the following \"config.rkt\" file in the root directory of your project:\n\n> ```racket\n> #lang racket/base\n> ( require racket/require-syntax\n> ( for-syntax \"utils/in-here.rkt\" ) )\n> ( provide utils-in )\n> ( define-require-syntax utils-in in-here-transformer )\n> ```\n\nand using \"utils/in-here.rkt\" under the same root directory:\n\n> ```racket\n> #lang racket/base\n> ( require racket/runtime-path )\n> ( provide in-here-transformer )\n> ( define-runtime-path here \".\" )\n> ( define ( in-here-transformer stx )\n> ( syntax-case stx ( )\n> [ ( _ sym )\n> ( identifier? #' sym )\n> ( let ( [ path ( build-path here ( format \"~a.rkt\" ( syntax-e #' sym ) ) ) ] )\n> ( datum->syntax stx ` ( file , ( path->string path ) ) stx ) ) ] ) )\n> ```\n\nthen [path-up](#%28form._%28%28lib._racket%2Frequire..rkt%29._path-up%29%29) works for any other module under the project directory to find \"config.rkt\":\n\n> ```racket\n> ( require racket/require\n> ( path-up \"config.rkt\" )\n> ( utils-in foo ) )\n> ```\n\nNote that the order of requires in the example is important, as each of the first two bind the identifier used in the following.\n\nAn alternative in this scenario is to use [path-up](#%28form._%28%28lib._racket%2Frequire..rkt%29._path-up%29%29) directly to find the utility module:\n\n> ```racket\n> ( require racket/require\n> ( path-up \"utils/foo.rkt\" ) )\n> ```\n\nbut then sub-directories that are called \"utils\" override the one in the project’s root. In other words, the previous method requires only a single unique name.\n\n>
\n\n

syntax

\n\n

([multi-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._multi-in%29%29) subs ...+)

 
subs = sub-path
  | (sub-path ...)
     
sub-path = rel-string
  | id
\n\nSpecifies multiple files to be required from a hierarchy of directories or collections. The set of required module paths is computed as the Cartesian product of the subs groups, where each sub-path is combined with other sub-paths in order using a / separator. A sub-path as a subs is equivalent to (sub-path). All sub-paths in a given [multi-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._multi-in%29%29) form must be either strings or identifiers.\n\nExamples:\n\n

([require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) ([multi-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._multi-in%29%29) racket (dict list)))

   is equivalent to 

([require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) racket/dict racket/list)

 

([require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) ([multi-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._multi-in%29%29) \"math\" \"matrix\" \"utils.rkt\"))

   is equivalent to 

([require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) \"math/matrix/utils.rkt\")

 

([require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) ([multi-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._multi-in%29%29) \"utils\" (\"math.rkt\" \"matrix.rkt\")))

   is equivalent to 

([require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) \"utils/math.rkt\" \"utils/matrix.rkt\")

 

([require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) ([multi-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._multi-in%29%29) (\"math\" \"matrix\") \"utils.rkt\"))

   is equivalent to 

([require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) \"math/utils.rkt\" \"matrix/utils.rkt\")

 

([require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) ([multi-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._multi-in%29%29) (\"math\" \"matrix\") (\"utils.rkt\" \"helpers.rkt\")))

   is equivalent to 

( require "math/utils.rkt" "math/helpers.rkt"\n"matrix/utils.rkt" "matrix/helpers.rkt" )
\n\n#### 3.2.2 Additional [provide](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) Forms\n\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/provide](#%28mod-path._racket%2Fprovide%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/provide](#%28mod-path._racket%2Fprovide%29) library, not [racket/base](index.html) or [racket](index.html).\n\n>
\n\n

syntax

\n\n

([matching-identifiers-out](#%28form._%28%28lib._racket%2Fprovide..rkt%29._matching-identifiers-out%29%29) regexp provide-spec)

\n\nLike provide-spec, but including only exports of bindings with an external name that matches regexp. The regexp must be a literal regular expression (see [Regular Expressions](regexp.html)).\n\n>
\n\n

syntax

\n\n

([filtered-out](#%28form._%28%28lib._racket%2Fprovide..rkt%29._filtered-out%29%29) proc-expr provide-spec)

\n\nAnalogous to [filtered-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._filtered-in%29%29), but for filtering and renaming exports.\n\n> > > See the documentation of [filtered-in](#%28form._%28%28lib._racket%2Frequire..rkt%29._filtered-in%29%29) for use with [#lang](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=Module_Syntax.html%23%2528part._hash-lang%2529&version=8.18.0.13) [racket/base](index.html).\n\nFor example,\n\n> ```racket\n> ( provide ( filtered-out\n> ( lambda ( name )\n> ( and ( regexp-match? #rx\"^[a-z-]+$\" name )\n> ( regexp-replace\n> #rx\"-\" ( string-titlecase name ) \"\" ) ) )\n> ( all-defined-out ) ) )\n> ```\n\nexports only bindings that match the pattern #rx\"^\\[a-z-\\]+$\", and it converts the names to “camel case.”\n\n------------------------------------------------------------------------\n\n# 3.3 Literals: quote and #%datum\n\n### 3.3 Literals: [quote](#%28form._%28%28quote._~23~25kernel%29._quote%29%29) and [#%datum](#%28form._%28%28quote._~23~25kernel%29._~23~25datum%29%29)\n\nMany forms are implicitly quoted (via [#%datum](#%28form._%28%28quote._~23~25kernel%29._~23~25datum%29%29)) as literals. See [Expansion Steps](syntax-model.html#%28part._expand-steps%29) for more information.\n\n> > > \"+\"[Quoting: quote and ’](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=quote.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces [quote](#%28form._%28%28quote._~23~25kernel%29._quote%29%29).\n\n>
\n\n

syntax

\n\n

([quote](#%28form._%28%28quote._~23~25kernel%29._quote%29%29) datum)

\n\nProduces a constant value corresponding to datum (i.e., the representation of the program fragment) without its [lexical information](syntax-model.html#%28tech._lexical._information%29), source location, etc. Quoted pairs, vectors, and boxes are immutable.\n\nExamples:\n\n> ```racket\n> > ( quote x )\n> 'x\n> > ( quote ( + 1 2 ) )\n> '(+ 1 2)\n> > ( + 1 2 )\n> 3\n> ```\n\n>
\n\n

syntax

\n\n

([#%datum](#%28form._%28%28quote._~23~25kernel%29._~23~25datum%29%29) . datum)

\n\nExpands to (quote datum), as long as datum is not a keyword. If datum is a keyword, a syntax error is reported.\n\nSee also [Expansion Steps](syntax-model.html#%28part._expand-steps%29) for information on how the expander introduces #%datum identifiers.\n\nExamples:\n\n> ```racket\n> > ( #%datum . 10 )\n> 10\n> > ( #%datum . x )\n> 'x\n> > ( #%datum . #:x )\n> eval:6:0: #%datum: keyword misused as an expression\n> at: #:x\n> ```\n\n------------------------------------------------------------------------\n\n# 3.4 Expression Wrapper: #%expression\n\n### 3.4 Expression Wrapper: [#%expression](#%28form._%28%28quote._~23~25kernel%29._~23~25expression%29%29)\n\n>
\n\n

syntax

\n\n

([#%expression](#%28form._%28%28quote._~23~25kernel%29._~23~25expression%29%29) expr)

\n\nProduces the same result as expr. Using [#%expression](#%28form._%28%28quote._~23~25kernel%29._~23~25expression%29%29) forces the parsing of a form as an expression.\n\nExamples:\n\n> ```racket\n> > ( #%expression ( + 1 2 ) )\n> 3\n> > ( #%expression ( define x 10 ) )\n> eval:8:0: define: not allowed in an expression context\n> in: (define x 10)\n> ```\n\nThe [#%expression](#%28form._%28%28quote._~23~25kernel%29._~23~25expression%29%29) form is helpful in recursive definition contexts where expanding a subsequent definition can provide compile-time information for the current expression. For example, consider a define-sym-case macro that simply records some symbols at compile-time in a given identifier.\n\n> ```racket\n> ( define-syntax ( define-sym-case stx ) ( syntax-case stx ( ) [ ( _ id sym ... ) ( andmap identifier? ( syntax->list #' ( sym ... ) ) ) #' ( define-syntax id ' ( sym ... ) ) ] ) )\n> ```\n\nand then a variant of [case](case.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29) that checks to make sure the symbols used in the expression match those given in the earlier definition:\n\n> ```racket\n> ( define-syntax ( sym-case stx ) ( syntax-case stx ( ) [ ( _ id val-expr [ ( sym ) expr ] ... ) ( let ( ) ( define expected-ids ( syntax-local-value #' id ( λ ( ) ( raise-syntax-error ' sym-case \"expected an identifier bound via define-sym-case\" stx #' id ) ) ) ) ( define actual-ids ( syntax->datum #' ( sym ... ) ) ) ( unless ( equal? expected-ids actual-ids ) ( raise-syntax-error ' sym-case ( format \"expected the symbols ~s\" expected-ids ) stx ) ) #' ( case val-expr [ ( sym ) expr ] ... ) ) ] ) )\n> ```\n\nIf the definition follows the use like this, then the define-sym-case macro does not have a chance to bind [id](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=syntax&rel=Library_Syntax_Classes_and_Literal_Sets.html%23%2528form._%2528%2528lib._syntax%252Fparse..rkt%2529._id%2529%2529&version=8.18.0.13) and the sym-case macro signals an error:\n\n> ```racket\n> > ( let ( ) ( sym-case land-creatures ' bear [ ( bear ) 1 ] [ ( fox ) 2 ] ) ( define-sym-case land-creatures bear fox ) )\n> eval:11:0: sym-case: expected an identifier bound via\n> define-sym-case\n> at: land-creatures\n> in: (sym-case land-creatures (quote bear) ((bear) 1)\n> ((fox) 2))\n> ```\n\nBut if the sym-case is wrapped in an [#%expression](#%28form._%28%28quote._~23~25kernel%29._~23~25expression%29%29), then the expander does not need to expand it to know it is an expression and it moves on to the define-sym-case expression.\n\n> ```racket\n> > ( let ( ) ( #%expression ( sym-case sea-creatures ' whale [ ( whale ) 1 ] [ ( squid ) 2 ] ) ) ( define-sym-case sea-creatures whale squid ) ' more... )\n> 'more...\n> ```\n\nOf course, a macro like sym-case should not require its clients to add [#%expression](#%28form._%28%28quote._~23~25kernel%29._~23~25expression%29%29); instead it should check the basic shape of its arguments and then expand to [#%expression](#%28form._%28%28quote._~23~25kernel%29._~23~25expression%29%29) wrapped around a helper macro that calls [syntax-local-value](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._syntax-local-value%29%29) and finishes the expansion.\n\n------------------------------------------------------------------------\n\n# 3.5 Variable References and #%top\n\n### 3.5 Variable References and [#%top](#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29)\n\n>
\n\n

syntax

\n\n

id

\n\nRefers to a top-level, module-level, or local binding, when id is not bound as a transformer (see [Expansion](syntax-model.html#%28part._expansion%29)). At run-time, the reference evaluates to the value in the [location](eval-model.html#%28tech._location%29) associated with the binding.\n\nWhen the expander encounters an id that is not bound by a module-level or local binding, it converts the expression to (#%top . id) giving #%top the lexical context of the id; typically, that context refers to [#%top](#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29). See also [Expansion Steps](syntax-model.html#%28part._expand-steps%29).\n\nExamples:\n\n> ```racket\n> > ( define x 10 )\n> > x\n> 10\n> > ( let ( [ x 5 ] ) x )\n> 5\n> > ( ( lambda ( x ) x ) 2 )\n> 2\n> ```\n\n>
\n\n

syntax

\n\n

([#%top](#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) . id)

\n\nEquivalent to id when id is bound to a module-level or top-level variable. In a top-level context, ([#%top](#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) . id) always refers to a top-level variable, even if id is [unbound](syntax-model.html#%28tech._unbound%29) or bound to syntax, as long as id does not have a local binding. In all contexts, ([#%top](#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) . id) is a syntax error if id has a local binding.\n\nWithin a [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) form, ([#%top](#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) . id) expands to just id as long as id is defined within the module and has no local binding in its context. At [phase level](syntax-model.html#%28tech._phase._level%29) 0, ([#%top](#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) . id) is an immediate syntax error if id is not bound. At [phase level](syntax-model.html#%28tech._phase._level%29) 1 and higher, a syntax error is reported if id is not defined at the corresponding phase by the end of [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29)-body [partial expansion](syntax-model.html#%28tech._partial._expansion%29).\n\nSee also [Expansion Steps](syntax-model.html#%28part._expand-steps%29) for information on how the expander introduces #%top identifiers.\n\nExamples:\n\n> ```racket\n> > ( define x 12 )\n> > ( #%top . x )\n> 12\n> ```\n\nChanged in version 6.3 of package base: Changed the introduction of [#%top](#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) in a top-level context to [unbound](syntax-model.html#%28tech._unbound%29) identifiers only. \nChanged in version 8.2.0.7: Changed treatment of locally bound id to always report a syntax error, even outside of a module.\n\n------------------------------------------------------------------------\n\n# 3.6 Locations: #%variable-reference\n\n### 3.6 Locations: [#%variable-reference](#%28form._%28%28quote._~23~25kernel%29._~23~25variable-reference%29%29)\n\n>
\n\n

syntax

\n\n

([#%variable-reference](#%28form._%28%28quote._~23~25kernel%29._~23~25variable-reference%29%29) id)

([#%variable-reference](#%28form._%28%28quote._~23~25kernel%29._~23~25variable-reference%29%29) ([#%top](__top.html#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) . id))
([#%variable-reference](#%28form._%28%28quote._~23~25kernel%29._~23~25variable-reference%29%29))
\n\nProduces an opaque variable reference value representing the [location](eval-model.html#%28tech._location%29) of id, which must be bound as a variable. If no id is supplied, the resulting value refers to an “anonymous” variable defined within the enclosing context (i.e., within the enclosing module, or at the top level if the form is not inside a module).\n\nWhen ([#%top](__top.html#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) . id) is used, then the variable reference refers to the same variable as ([#%top](__top.html#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) . id). Note that ([#%top](__top.html#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) . id) is not allowed if id is locally bound or within a module if id is bound as a transformer.\n\nA [variable reference](#%28tech._variable._reference%29) can be used with [variable-reference->empty-namespace](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._variable-reference-~3eempty-namespace%29%29), [variable-reference->resolved-module-path](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._variable-reference-~3eresolved-module-path%29%29), and [variable-reference->namespace](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._variable-reference-~3enamespace%29%29), but facilities like [define-namespace-anchor](Namespaces.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-namespace-anchor%29%29) and [namespace-anchor->namespace](Namespaces.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._namespace-anchor-~3enamespace%29%29) wrap those to provide a clearer interface. A [variable reference](#%28tech._variable._reference%29) is also useful to low-level extensions; see [Inside: Racket C API](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=inside&rel=index.html&version=8.18.0.13).\n\nChanged in version 8.2.0.7 of package base: Changed [#%top](__top.html#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) treatment to be consistent with [#%top](__top.html#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) by itself.\n\n------------------------------------------------------------------------\n\n# 3.7 Procedure Applications and #%app\n\n### 3.7 Procedure Applications and [#%app](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~23~25app%29%29)\n\n> > > \"+\"[Function Calls](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=application.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces procedure applications.\n\n> ```\nsyntax\n\n(proc-expr arg ...)\n```"} {"text": "### 2.5 Notation for Parameter Documentation\n(parameter)\t→```\nCombines [letrec-syntaxes](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._letrec-syntaxes%29%29) with a variant of [letrec-values](#%28form._%28%28quote._~23~25kernel%29._letrec-values%29%29): each trans-id and val-id is bound in all trans-exprs and val-exprs.\nThe [letrec-syntaxes+values](#%28form._%28%28quote._~23~25kernel%29._letrec-syntaxes%2Bvalues%29%29) form is the core form for local compile-time bindings, since forms like [letrec-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._letrec-syntax%29%29) and [internal-definition contexts](syntax-model.html#%28tech._internal._definition._context%29) expand to it. In a fully expanded expression (see [Fully Expanded Programs](syntax-model.html#%28part._fully-expanded%29)), the trans-id bindings are discarded and the form reduces to a combination of [letrec-values](#%28form._%28%28quote._~23~25kernel%29._letrec-values%29%29) or [let-values](#%28form._%28%28quote._~23~25kernel%29._let-values%29%29)."} {"text": "### 2.5 Notation for Parameter Documentation\nFor variables bound by [letrec-syntaxes+values](#%28form._%28%28quote._~23~25kernel%29._letrec-syntaxes%2Bvalues%29%29), the [location](eval-model.html#%28tech._location%29)-creation rules differ slightly from [letrec-values](#%28form._%28%28quote._~23~25kernel%29._letrec-values%29%29). The \\[(val-id [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) val-expr\\] binding clauses are partitioned into minimal sets of clauses that satisfy the following rule: if a clause has a val-id binding that is referenced (in a full expansion) by the val-expr of an earlier clause, the two clauses and all in between are in the same set. If a set consists of a single clause whose val-expr does not refer to any of the clause’s val-ids, then [locations](eval-model.html#%28tech._location%29) for the val-ids are created after the val-expr is evaluated. Otherwise, [locations](eval-model.html#%28tech._location%29) for all val-ids in a set are created just before the first val-expr in the set is evaluated. For the purposes of forming sets, a ([quote-syntax](Syntax_Quoting__quote-syntax.html#%28form._%28%28quote._~23~25kernel%29._quote-syntax%29%29) datum #:local) form counts as a reference to all bindings in the [letrec-syntaxes+values](#%28form._%28%28quote._~23~25kernel%29._letrec-syntaxes%2Bvalues%29%29) form"} {"text": "### 2.5 Notation for Parameter Documentation\nThe end result of the [location](eval-model.html#%28tech._location%29)-creation rules is that scoping and evaluation order are the same as for [letrec-values](#%28form._%28%28quote._~23~25kernel%29._letrec-values%29%29), but the compiler has more freedom to optimize away [location](eval-model.html#%28tech._location%29) creation. The rules also correspond to a nesting of [let-values](#%28form._%28%28quote._~23~25kernel%29._let-values%29%29) and [letrec-values](#%28form._%28%28quote._~23~25kernel%29._letrec-values%29%29), which is how [letrec-syntaxes+values](#%28form._%28%28quote._~23~25kernel%29._letrec-syntaxes%2Bvalues%29%29) for a fully-expanded expression.\nSee also [local](local.html#%28form._%28%28lib._racket%2Flocal..rkt%29._local%29%29), which supports local bindings with [define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), and more.\n------------------------------------------------------------------------"} {"text": "# 3.10 Local Definitions: local"} {"text": "### 3.10 Local Definitions: [local](#%28form._%28%28lib._racket%2Flocal..rkt%29._local%29%29)\n| | |\n|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/local]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/local]() and [racket](index.html) libraries, but not [racket/base](index.html).\n>
\n

syntax

\n

([local](#%28form._%28%28lib._racket%2Flocal..rkt%29._local%29%29) [definition ...] body ...+)

"} {"text": "### 3.10 Local Definitions: [local](#%28form._%28%28lib._racket%2Flocal..rkt%29._local%29%29)\nLike [letrec-syntaxes+values](let.html#%28form._%28%28quote._~23~25kernel%29._letrec-syntaxes%2Bvalues%29%29), except that the bindings are expressed in the same way as in the top-level or in a module body: using [define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-values](define.html#%28form._%28%28quote._~23~25kernel%29._define-values%29%29), [define-syntax](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29), etc. Definitions are distinguished from non-definitions by partially expanding definition forms (see [Partial Expansion](syntax-model.html#%28part._partial-expansion%29)). As in the top-level or in a module body, a [begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29)-wrapped sequence is spliced into the sequence of definitions.\n------------------------------------------------------------------------"} {"text": "# 3.11 Constructing Graphs: shared"} {"text": "### 3.11 Constructing Graphs: [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29)\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/shared]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/shared]() and [racket](index.html) libraries, but not [racket/base](index.html).\n>
\n

syntax

\n

([shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29) ([id expr] ...) body ...+)

\nBinds ids with shared structure according to exprs and then evaluates the bodys, returning the result of the last expression."} {"text": "### 3.11 Constructing Graphs: [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29)\nThe [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29) form is similar to [letrec](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._letrec%29%29), except that special forms of expr are recognized (after partial macro expansion) to construct graph-structured data, where the corresponding [letrec](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._letrec%29%29) would instead produce a use-before-initialization error.\nEach expr (after partial expansion) is matched against the following shared-expr grammar, where earlier variants in a production take precedence over later variants:"} {"text": "### 3.11 Constructing Graphs: [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29)\n| | | | | |\n|--------------------:|:----|:---:|:----|:----------------------------------------------------------------------------------------------------------------------------------------------------|\n|   shared-expr |   | = |   | shell-expr |\n|   |   | \\| |   | plain-expr |\n|   |   |   |   |   |\n|   shell-expr |   | = |   | ([cons](pairs.html#%28def._%28%28quote._~23~25kernel%29._cons%29%29) in-immutable-expr in-immutable-expr) |\n|   |   | \\| |   | ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) in-immutable-expr ...) |\n|   |   | \\| |   | ([list*](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%2A%29%29) in-immutable-expr ...) |\n|   |   | \\| |   | ([append](pairs.html#%28def._%28%28quote._~23~25kernel%29._append%29%29) early-expr ... in-immutable-expr) |\n|   |   | \\| |   | ([vector-immutable](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector-immutable%29%29) in-immutable-expr ...) |\n|   |   | \\| |   | ([box-immutable](boxes.html#%28def._%28%28quote._~23~25kernel%29._box-immutable%29%29) in-immutable-expr) |\n|   |   | \\| |   | ([mcons](mpairs.html#%28def._%28%28quote._~23~25kernel%29._mcons%29%29) patchable-expr patchable-expr) |\n|   |   | \\| |   | ([vector](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector%29%29) patchable-expr ...) |\n|   |   | \\| |   | ([box](boxes.html#%28def._%28%28quote._~23~25kernel%29._box%29%29) patchable-expr) |\n|   |   | \\| |   | (prefix:make-id patchable-expr ...) |\n|   |   |   |   |   |\n|   in-immutable-expr |   | = |   | shell-id |\n|   |   | \\| |   | shell-expr |\n|   |   | \\| |   | early-expr |\n|   |   |   |   |   |\n|   shell-id |   | = |   | id |\n|   |   |   |   |   |\n|   patchable-expr |   | = |   | expr |\n|   |   |   |   |   |\n|   early-expr |   | = |   | expr |\n|   |   |   |   |   |\n|   plain-expr |   | = |   | expr |"} {"text": "### 3.11 Constructing Graphs: [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29)\nThe prefix:make-id identifier above matches three kinds of references. The first kind is any binding whose name has make- in the middle, and where prefix:id has a [transformer](syntax-model.html#%28tech._transformer%29) binding to structure information with a full set of mutator bindings; see [Structure Type Transformer Binding](structinfo.html). The second kind is an identifier that itself has a [transformer](syntax-model.html#%28tech._transformer%29) binding to structure information. The third kind is an identifier that has a 'constructor-for [syntax property](stxprops.html#%28tech._syntax._property%29) whose value is an identifier with a [transformer](syntax-model.html#%28tech._transformer%29) binding to structure information. A shell-id, meanwhile, must be one of the ids bound by the [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29) form to a shell-expr."} {"text": "### 3.11 Constructing Graphs: [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29)\nWhen the exprs of the [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29) form are parsed as shared-expr (taking into account the order of the variants for parsing precedence), the sub-expressions that were parsed via early-expr will be evaluated first when the [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29) form is evaluated. Among such expressions, they are evaluated in the order as they appear within the [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29) form. However, any reference to an id bound by [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29) produces a use-before-initialization errror, even if the binding for the id appears before the corresponding early-expr within the [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29) form.\nThe shell-ids and shell-exprs (not counting patchable-expr and early-expr sub-expressions) are effectively evaluated next:\n- A shell-id reference produces the same value as the corresponding id will produce within the bodys, assuming that id is never mutated with [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29). This special handling of a shell-id reference is one way in which [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29) supports the creation of cyclic data, including immutable cyclic data."} {"text": "### 3.11 Constructing Graphs: [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29)\n- A shell-expr of the form ([mcons](mpairs.html#%28def._%28%28quote._~23~25kernel%29._mcons%29%29) patchable-expr patchable-expr), ([vector](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector%29%29) patchable-expr [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)), ([box](boxes.html#%28def._%28%28quote._~23~25kernel%29._box%29%29) patchable-expr), or (prefix:make-id patchable-expr [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) produces a mutable value whose content positions are initialized to [undefined](undefined.html#%28def._%28%28lib._racket%2Fundefined..rkt%29._undefined%29%29). Each content position is patched (i.e., updated) after the corresponding patchable-expr expression is later evaluated.\nNext, the plain-exprs are evaluated as for [letrec](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._letrec%29%29), where a reference to an id raises [exn:fail:contract:variable](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3avariable%29%29) if it is evaluated before the right-hand side of the id binding."} {"text": "### 3.11 Constructing Graphs: [shared](#%28form._%28%28lib._racket%2Fshared..rkt%29._shared%29%29)\nFinally, the patchable-exprs are evaluated and their values replace [undefined](undefined.html#%28def._%28%28lib._racket%2Fundefined..rkt%29._undefined%29%29)s in the results of shell-exprs. At this point, all ids are bound, so patchable-exprs can create data cycles (but only with cycles that can be created via mutation).\nExamples:\n> ```racket\n> > ( shared ( [ a ( cons 1 a ) ] ) a )\n> #0='(1 . #0#)\n> > ( shared ( [ a ( cons 1 b ) ] [ b ( cons 2 a ) ] ) a )\n> #0='(1 2 . #0#)\n> > ( shared ( [ a ( cons 1 b ) ] [ b 7 ] ) a )\n> '(1 . 7)\n> > ( shared ( [ a a ] ) ; no indirection... a )\n> a: undefined;\n> cannot use before initialization\n> > ( shared ( [ a ( cons 1 b ) ] ; b is early... [ b a ] ) a )\n> a: undefined;\n> cannot use before initialization\n> > ( shared ( [ a ( mcons 1 b ) ] ; b is patchable... [ b a ] ) a )\n> #0=(mcons 1 #0#)\n> > ( shared ( [ a ( vector b b b ) ] [ b ( box 1 ) ] ) ( set-box! b 5 ) a )\n> '#(#&5 #&5 #&5)\n> > ( shared ( [ a ( box b ) ] [ b ( vector ( unbox a ) ; unbox after a is patched ( unbox c ) ) ] ; unbox before c is patched [ c ( box b ) ] ) b )\n> #0='#(#0# #)\n> ```\n------------------------------------------------------------------------"} {"text": "# 3.12 Conditionals: if, cond, and, and or"} {"text": "### 3.12 Conditionals: [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29), [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29), [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29), and [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29)\n> > > \"+\"[Conditionals](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=conditionals.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces conditionals.\n>
\n

syntax

\n

([if](#%28form._%28%28quote._~23~25kernel%29._if%29%29) test-expr then-expr else-expr)

\nEvaluates test-expr. If it produces any value other than #f, then then-expr is evaluated, and its results are the result for the [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29) form. Otherwise, else-expr is evaluated, and its results are the result for the [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29) form. The then-expr and else-expr are in tail position with respect to the [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29) form.\nExamples:"} {"text": "### 3.12 Conditionals: [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29), [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29), [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29), and [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29)\n> ```racket\n> > ( if ( positive? -5 ) ( error \"doesn't get here\" ) 2 )\n> 2\n> > ( if ( positive? 5 ) 1 ( error \"doesn't get here\" ) )\n> 1\n> > ( if ' we-have-no-bananas \"yes\" \"no\" )\n> \"yes\"\n> ```\n>
\n

syntax

"} {"text": "### 3.12 Conditionals: [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29), [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29), [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29), and [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29)\n

([cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29) cond-clause ...)

 
cond-clause = [test-expr then-body ...+]
  | [[else](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._else%29%29) then-body ...+]
  | [test-expr [=>](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._~3d~3e%29%29) proc-expr]
  | [test-expr]
"} {"text": "### 3.12 Conditionals: [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29), [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29), [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29), and [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29)\n> > > \"+\"[Chaining Tests: cond](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=conditionals.html%23%2528part._cond%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29).\nA cond-clause that starts with [else](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._else%29%29) must be the last cond-clause.\nIf no cond-clauses are present, the result is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13)."} {"text": "### 3.12 Conditionals: [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29), [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29), [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29), and [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29)\nIf only a \\[[else](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._else%29%29) then-body [...+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=syntax&rel=stxparse-patterns.html%23%2528form._%2528%2528lib._syntax%252Fparse..rkt%2529._......%252B%2529%2529&version=8.18.0.13)\\] is present, then the then-bodys are evaluated. The results from all but the last then-body are ignored. The results of the last then-body, which is in tail position with respect to the [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29) form, are the results for the whole [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29) form.\nOtherwise, the first test-expr is evaluated. If it produces #f, then the result is the same as a [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29) form with the remaining cond-clauses, in tail position with respect to the original [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29) form. Otherwise, evaluation depends on the form of the cond-clause:"} {"text": "### 3.12 Conditionals: [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29), [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29), [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29), and [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29)\n> > | |\n> > |------------------------------|\n> > | \\[test-expr then-body ...+\\] |\n>\n> The then-bodys are evaluated in order, and the results from all but the last then-body are ignored. The results of the last then-body, which is in tail position with respect to the [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29) form, provides the result for the whole [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29) form."} {"text": "### 3.12 Conditionals: [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29), [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29), [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29), and [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29)\n> > | |\n> > |--------------------------------------------------------------------------------------------------------------------------------------------|\n> > | \\[test-expr [=>](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._~3d~3e%29%29) proc-expr\\] |\n>\n> The proc-expr is evaluated, and it must produce a procedure that accepts one argument, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. The procedure is applied to the result of test-expr in tail position with respect to the [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29) expression.\n> > | |\n> > |---------------|\n> > | \\[test-expr\\] |\n>\n> The result of the test-expr is returned as the result of the [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29) form. The test-expr is not in tail position.\nExamples:"} {"text": "### 3.12 Conditionals: [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29), [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29), [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29), and [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29)\n> ```racket\n> > ( cond )\n> > ( cond [ else 5 ] )\n> 5\n> > ( cond [ ( positive? -5 ) ( error \"doesn't get here\" ) ] [ ( zero? -5 ) ( error \"doesn't get here, either\" ) ] [ ( positive? 5 ) ' here ] )\n> 'here\n> > ( cond [ ( member 2 ' ( 1 2 3 ) ) => ( lambda ( l ) ( map - l ) ) ] )\n> '(-2 -3)\n> > ( cond [ ( member 2 ' ( 1 2 3 ) ) ] )\n> '(2 3)\n> ```\n>
\n

syntax

\n

[else](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._else%29%29)

\nRecognized specially within forms like [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29). An [else](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._else%29%29) form as an expression is a syntax error.\n>
\n

syntax

\n

[=>](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._~3d~3e%29%29)

"} {"text": "### 3.12 Conditionals: [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29), [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29), [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29), and [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29)\nRecognized specially within forms like [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29). A [=>](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._~3d~3e%29%29) form as an expression is a syntax error.\n>
\n

syntax

\n

([and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29) expr ...)

\n> > > \"+\"[Combining Tests: and and or](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=conditionals.html%23%2528part._and%252Bor%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29).\nIf no exprs are provided, then result is #t."} {"text": "### 3.12 Conditionals: [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29), [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29), [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29), and [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29)\nIf a single expr is provided, then it is in tail position, so the results of the [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29) expression are the results of the expr.\nOtherwise, the first expr is evaluated. If it produces #f, the result of the [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29) expression is #f. Otherwise, the result is the same as an [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29) expression with the remaining exprs in tail position with respect to the original [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29) form.\nExamples:\n> ```racket\n> > ( and )\n> #t\n> > ( and 1 )\n> 1\n> > ( and ( values 1 2 ) )\n> 1 2\n> > ( and #f ( error \"doesn't get here\" ) )\n> #f\n> > ( and #t 5 )\n> 5\n> ```\n>
\n

syntax

\n

([or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29) expr ...)

"} {"text": "### 3.12 Conditionals: [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29), [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29), [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29), and [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29)\n> > > \"+\"[Combining Tests: and and or](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=conditionals.html%23%2528part._and%252Bor%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29).\nIf no exprs are provided, then result is #f.\nIf a single expr is provided, then it is in tail position, so the results of the [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29) expression are the results of the expr.\nOtherwise, the first expr is evaluated. If it produces a value other than #f, that result is the result of the [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29) expression. Otherwise, the result is the same as an [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29) expression with the remaining exprs in tail position with respect to the original [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29) form.\nExamples:"} {"text": "### 3.12 Conditionals: [if](#%28form._%28%28quote._~23~25kernel%29._if%29%29), [cond](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._cond%29%29), [and](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29), and [or](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29)\n> ```racket\n> > ( or )\n> #f\n> > ( or 1 )\n> 1\n> > ( or ( values 1 2 ) )\n> 1 2\n> > ( or 5 ( error \"doesn't get here\" ) )\n> 5\n> > ( or #f 5 )\n> 5\n> ```\n------------------------------------------------------------------------"} {"text": "# 3.13 Dispatch: case"} {"text": "### 3.13 Dispatch: [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29)\n>
\n

syntax

\n

([case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29) val-expr case-clause ...)

 
case-clause = [(datum ...) then-body ...+]
  | [[else](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._else%29%29) then-body ...+]
"} {"text": "### 3.13 Dispatch: [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29)\nEvaluates val-expr and uses the result to select a case-clause. The selected clause is the first one with a datum whose [quote](quote.html#%28form._%28%28quote._~23~25kernel%29._quote%29%29)d form is [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) to the result of val-expr. If no such datum is present, the [else](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._else%29%29) case-clause is selected; if no [else](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._else%29%29) case-clause is present, either, then the result of the [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29) form is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13)."} {"text": "### 3.13 Dispatch: [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29)\n> > > The [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29) form of [racket](index.html) differs from that of [R6RS](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?tag=%28part._%28.%27%28lib._r6rs%2Fscribblings%2Fr6rs..scrbl%29.%27._.%27top.%27%29%29&version=8.18.0.13) or [R5RS](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?tag=%28part._%28.%27%28lib._r5rs%2Fr5rs..scrbl%29.%27._.%27top.%27%29%29&version=8.18.0.13) by being based on [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) instead of [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29) (in addition to allowing internal definitions).\nFor the selected case-clause, the results of the last then-body, which is in tail position with respect to the [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29) form, are the results for the whole [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29) form.\nA case-clause that starts with [else](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._else%29%29) must be the last case-clause.\nThe [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29) form can dispatch to a matching case-clause in O(log N) time for N datums.\nExamples:"} {"text": "### 3.13 Dispatch: [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29)\n> ```racket\n> > ( case ( + 7 5 ) [ ( 1 2 3 ) ' small ] [ ( 10 11 12 ) ' big ] )\n> 'big\n> > ( case ( - 7 5 ) [ ( 1 2 3 ) ' small ] [ ( 10 11 12 ) ' big ] )\n> 'small\n> > ( case ( string-append \"do\" \"g\" ) [ ( \"cat\" \"dog\" \"mouse\" ) \"animal\" ] [ else \"mineral or vegetable\" ] )\n> \"animal\"\n> > ( case ( list ' y ' x ) [ ( ( a b ) ( x y ) ) ' forwards ] [ ( ( b a ) ( y x ) ) ' backwards ] )\n> 'backwards\n> > ( case ' x [ ( x ) \"ex\" ] [ ( ' x ) \"quoted ex\" ] )\n> \"ex\"\n> > ( case ( list ' quote ' x ) [ ( x ) \"ex\" ] [ ( ' x ) \"quoted ex\" ] )\n> \"quoted ex\"\n> ( define ( classify c ) ( case ( char-general-category c ) [ ( ll lu lt ln lo ) \"letter\" ] [ ( nd nl no ) \"number\" ] [ else \"other\" ] ) )\n> > ( classify #\\A )\n> \"letter\"\n> > ( classify #\\1 )\n> \"number\"\n> > ( classify #\\! )\n> \"other\"\n> ```"} {"text": "#### 3.13.1 Variants of [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29)\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/case](#%28mod-path._racket%2Fcase%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/case](#%28mod-path._racket%2Fcase%29) library, not [racket/base](index.html) or [racket](index.html).\nAdded in version 8.11.1.8 of package base.\n>
\n

syntax

"} {"text": "### 3.13 Dispatch: [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29)\n

([case/equal](#%28form._%28%28lib._racket%2Fcase..rkt%29._case%2Fequal%29%29) val-expr case-clause ...)

\n

syntax

\n

([case/equal-always](#%28form._%28%28lib._racket%2Fcase..rkt%29._case%2Fequal-always%29%29) val-expr case-clause ...)

\n

syntax

\n

([case/eq](#%28form._%28%28lib._racket%2Fcase..rkt%29._case%2Feq%29%29) val-expr case-clause ...)

\n

syntax

\n

([case/eqv](#%28form._%28%28lib._racket%2Fcase..rkt%29._case%2Feqv%29%29) val-expr case-clause ...)

"} {"text": "### 3.13 Dispatch: [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29)\nLike [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29), but using [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29), or [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29) for comparing the result of val-expr to the literals in the case-clauses. The [case/equal](#%28form._%28%28lib._racket%2Fcase..rkt%29._case%2Fequal%29%29) form is equivalent to [case](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._case%29%29).\n------------------------------------------------------------------------"} {"text": "# 3.14 Definitions: define, define-syntax, ..."} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n> > > \"+\"[Definitions: define](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=define.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces definitions.\n>
\n

syntax

"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n

([define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr)

([define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) (head args) body ...+)
 
head = id
  | (head args)
     
args = arg ...
  | arg ... . rest-id
     
arg = arg-id
  | [arg-id default-expr]
  | keyword arg-id
  | keyword [arg-id default-expr]
"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nThe first form [bind](syntax-model.html#%28tech._bind%29)s id to the result of expr, and the second form [bind](syntax-model.html#%28tech._bind%29)s id to a procedure. In the second case, the generated procedure is (CVT (head args) body [...+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=syntax&rel=stxparse-patterns.html%23%2528form._%2528%2528lib._syntax%252Fparse..rkt%2529._......%252B%2529%2529&version=8.18.0.13)), using the CVT meta-function defined as follows:\n> ```racket\n> ( CVT ( id . kw-formals ) . datum ) = ( lambda kw-formals . datum )\n> ( CVT ( head . kw-formals ) . datum ) = ( lambda kw-formals expr )\n> if ( CVT head . datum ) = expr\n> ```\nIn an [internal-definition context](syntax-model.html#%28tech._internal._definition._context%29), a [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) form introduces a local binding; see [Internal Definitions](syntax-model.html#%28part._intdef-body%29). At the top level, the top-level binding for id is created after evaluating expr, if it does not exist already, and the top-level mapping of id (in the [namespace](syntax-model.html#%28tech._namespace%29) linked with the compiled definition) is set to the binding at the same time."} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nIn a context that allows [liberal expansion](stxtrans.html#%28tech._liberal._expansion%29) of [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), id is bound as syntax if expr is an immediate [lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) form with keyword arguments or args include keyword arguments.\nExamples:\n> ```racket\n> ( define x 10 )\n> > x\n> 10\n> ( define ( f x ) ( + x 1 ) )\n> > ( f 10 )\n> 11\n> ( define ( ( f x ) [ y 20 ] ) ( + x y ) )\n> > ( ( f 10 ) 30 )\n> 40\n> > ( ( f 10 ) )\n> 30\n> ```\n>
\n

syntax

\n

([define-values](#%28form._%28%28quote._~23~25kernel%29._define-values%29%29) (id ...) expr)

\nEvaluates the expr, and [bind](syntax-model.html#%28tech._bind%29)s the results to the ids, in order, if the number of results matches the number of ids; if expr produces a different number of results, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised."} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nIn an [internal-definition context](syntax-model.html#%28tech._internal._definition._context%29) (see [Internal Definitions](syntax-model.html#%28part._intdef-body%29)), a [define-values](#%28form._%28%28quote._~23~25kernel%29._define-values%29%29) form introduces local bindings. At the top level, the top-level binding for each id is created after evaluating expr, if it does not exist already, and the top-level mapping of each id (in the [namespace](syntax-model.html#%28tech._namespace%29) linked with the compiled definition) is set to the binding at the same time.\nExamples:\n> ```racket\n> > ( define-values ( ) ( values ) )\n> > ( define-values ( x y z ) ( values 1 2 3 ) )\n> > z\n> 3\n> ```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nIf a [define-values](#%28form._%28%28quote._~23~25kernel%29._define-values%29%29) form for a function definition in a module body has a 'compiler-hint:cross-module-inline [syntax property](stxprops.html#%28tech._syntax._property%29) with a true value, then the Racket treats the property as a performance hint. See [Function-Call Optimizations](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=performance.html%23%2528part._func-call-performance%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) for more information, and see also [begin-encourage-inline](performance-hint.html#%28form._%28%28lib._racket%2Fperformance-hint..rkt%29._begin-encourage-inline%29%29).\n>
\n

syntax

\n

([define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29) id expr)

([define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29) (head args) body ...+)
"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nThe first form creates a [transformer](syntax-model.html#%28tech._transformer%29) binding (see [Transformer Bindings](syntax-model.html#%28part._transformer-model%29)) of id with the value of expr, which is an expression at [phase level](syntax-model.html#%28tech._phase._level%29) 1 relative to the surrounding context. (See [Identifiers, Binding, and Scopes](syntax-model.html#%28part._id-model%29) for information on [phase levels](syntax-model.html#%28tech._phase._level%29).) Evaluation of expr side is [parameterize](parameters.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize%29%29)d to set [current-namespace](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._current-namespace%29%29) as in [let-syntax](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let-syntax%29%29).\nThe second form is a shorthand the same as for [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29); it expands to a definition of the first form where the expr is a [lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) form."} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nIn an [internal-definition context](syntax-model.html#%28tech._internal._definition._context%29) (see [Internal Definitions](syntax-model.html#%28part._intdef-body%29)), a [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29) form introduces a local binding.\nExamples:\n> ```racket\n> > ( define-syntax foo ( syntax-rules ( ) ( ( _ a ... ) ( printf \"~a\\n\" ( list a ... ) ) ) ) )\n> > ( foo 1 2 3 4 )\n> (1 2 3 4)\n> > ( define-syntax ( bar syntax-object ) ( syntax-case syntax-object ( ) ( ( _ a ... ) #' ( printf \"~a\\n\" ( list a ... ) ) ) ) )\n> > ( bar 1 2 3 4 )\n> (1 2 3 4)\n> ```\n>
\n

syntax

\n

([define-syntaxes](#%28form._%28%28quote._~23~25kernel%29._define-syntaxes%29%29) (id ...) expr)

\nLike [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), but creates a [transformer](syntax-model.html#%28tech._transformer%29) binding for each id. The expr should produce as many values as ids, and each value is bound to the corresponding id."} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nWhen expr produces zero values for a top-level [define-syntaxes](#%28form._%28%28quote._~23~25kernel%29._define-syntaxes%29%29) (i.e., not in a module or internal-definition position), then the ids are effectively declared without binding; see [Macro-Introduced Bindings](syntax-model.html#%28part._macro-introduced-bindings%29).\nIn an [internal-definition context](syntax-model.html#%28tech._internal._definition._context%29) (see [Internal Definitions](syntax-model.html#%28part._intdef-body%29)), a [define-syntaxes](#%28form._%28%28quote._~23~25kernel%29._define-syntaxes%29%29) form introduces local bindings.\nExamples:\n> ```racket\n> > ( define-syntaxes ( foo1 foo2 foo3 ) ( let ( [ transformer1 ( lambda ( syntax-object ) ( syntax-case syntax-object ( ) [ ( _ ) #' 1 ] ) ) ] [ transformer2 ( lambda ( syntax-object ) ( syntax-case syntax-object ( ) [ ( _ ) #' 2 ] ) ) ] [ transformer3 ( lambda ( syntax-object ) ( syntax-case syntax-object ( ) [ ( _ ) #' 3 ] ) ) ] ) ( values transformer1 transformer2 transformer3 ) ) )\n> > ( foo1 )\n> 1\n> > ( foo2 )\n> 2\n> > ( foo3 )\n> 3\n> ```\n>
\n

syntax

"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n

([define-for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-for-syntax%29%29) id expr)

([define-for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-for-syntax%29%29) (head args) body ...+)
\nLike [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), except that the binding is at [phase level](syntax-model.html#%28tech._phase._level%29) 1 instead of [phase level](syntax-model.html#%28tech._phase._level%29) 0 relative to its context. The expression for the binding is also at [phase level](syntax-model.html#%28tech._phase._level%29) 1. (See [Identifiers, Binding, and Scopes](syntax-model.html#%28part._id-model%29) for information on [phase levels](syntax-model.html#%28tech._phase._level%29).) The form is a shorthand for ([begin-for-syntax](begin.html#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29) ([define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr)) or ([begin-for-syntax](begin.html#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29) ([define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) (head args) body [...+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=syntax&rel=stxparse-patterns.html%23%2528form._%2528%2528lib._syntax%252Fparse..rkt%2529._......%252B%2529%2529&version=8.18.0.13)))."} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nWithin a module, bindings introduced by [define-for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-for-syntax%29%29) must appear before their uses or in the same [define-for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-for-syntax%29%29) form (i.e., the [define-for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-for-syntax%29%29) form must be expanded before the use is expanded). In particular, mutually recursive functions bound by [define-for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-for-syntax%29%29) must be defined by the same [define-for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-for-syntax%29%29) form.\nExamples:"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n> ```racket\n> > ( define-for-syntax helper 2 )\n> > ( define-syntax ( make-two syntax-object ) ( printf \"helper is ~a\\n\" helper ) #' 2 )\n> > ( make-two )\n> helper is 2\n> 2\n> ; ‘ helper ' is not bound in the runtime phase\n> > helper\n> helper: undefined;\n> cannot reference an identifier before its definition\n> in module: top-level\n> > ( define-for-syntax ( filter-ids ids ) ( filter identifier? ids ) )\n> > ( define-syntax ( show-variables syntax-object ) ( syntax-case syntax-object ( ) [ ( _ expr ... ) ( with-syntax ( [ ( only-ids ... ) ( filter-ids ( syntax->list #' ( expr ... ) ) ) ] ) #' ( list only-ids ... ) ) ] ) )\n> > ( let ( [ a 1 ] [ b 2 ] [ c 3 ] ) ( show-variables a 5 2 b c ) )\n> '(1 2 3)\n> ```\n>
\n

syntax

\n

([define-values-for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fdefine..rkt%29._define-values-for-syntax%29%29) (id ...) expr)

\nLike [define-for-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-for-syntax%29%29), but expr must produce as many values as supplied ids, and all of the ids are bound (at [phase level](syntax-model.html#%28tech._phase._level%29) 1).\nExamples:"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n> ```racket\n> > ( define-values-for-syntax ( foo1 foo2 ) ( values 1 2 ) )\n> > ( define-syntax ( bar syntax-object ) ( printf \"foo1 is ~a foo2 is ~a\\n\" foo1 foo2 ) #' 2 )\n> > ( bar )\n> foo1 is 1 foo2 is 2\n> 2\n> ```"} {"text": "#### 3.14.1 [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) Macros\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/require-syntax](#%28mod-path._racket%2Frequire-syntax%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/require-syntax](#%28mod-path._racket%2Frequire-syntax%29) library, not [racket/base](index.html) or [racket](index.html).\n>
\n

syntax

"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n

([define-require-syntax](#%28form._%28%28lib._racket%2Frequire-syntax..rkt%29._define-require-syntax%29%29) id proc-expr)

([define-require-syntax](#%28form._%28%28lib._racket%2Frequire-syntax..rkt%29._define-require-syntax%29%29) (id args ...) body ...+)
\nThe first form is like [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), but for a [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) sub-form. The proc-expr must produce a procedure that accepts and returns a syntax object representing a [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) sub-form.\nThis form expands to [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29) with a use of [make-require-transformer](stxtrans.html#%28def._%28%28lib._racket%2Frequire-transform..rkt%29._make-require-transformer%29%29) (see [require Transformers](stxtrans.html#%28part._require-trans%29) for more information).\nThe second form is a shorthand the same as for [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29); it expands to a definition of the first form where the proc-expr is a [lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) form.\n> ```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n(syntax-local-require-introduce stx)  →  syntax?\n  stx : syntax?\n```\nFor backward compatibility only; equivalent to syntax-local-introduce.\n\nChanged in version 6.90.0.29 of package base: Made equivalent to syntax-local-introduce.\n\n#### 3.14.2 provide Macros\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require racket/provide-syntax) |  package: base |\n\nThe bindings documented in this section are provided by the racket/provide-syntax library, not racket/base or racket.\n\n>
\n\n

syntax

\n\n

(define-provide-syntax id proc-expr)

(define-provide-syntax (id args ...) body ...+)
\n\nThe first form is like define-syntax, but for a provide sub-form. The proc-expr must produce a procedure that accepts and returns a syntax object representing a provide sub-form.\n\nThis form expands to define-syntax with a use of make-provide-transformer (see provide Transformers for more information).\n\nThe second form is a shorthand the same as for define-syntax; it expands to a definition of the first form where the expr is a lambda form.\n\n> ```\n(syntax-local-provide-introduce stx) → syntax?\n  stx : syntax?```\n\n\nFor backward compatibility only; equivalent to [syntax-local-introduce](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._syntax-local-introduce%29%29).\n\nChanged in version 6.90.0.29 of package base: Made equivalent to [syntax-local-introduce](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._syntax-local-introduce%29%29).\n\n------------------------------------------------------------------------\n\n# 3.15 Sequencing: begin, begin0, and begin-for-syntax\n\n### 3.15 Sequencing: [begin](#%28form._%28%28quote._~23~25kernel%29._begin%29%29), [begin0](#%28form._%28%28quote._~23~25kernel%29._begin0%29%29), and [begin-for-syntax](#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29)\n\n> > > \"+\"[Sequencing](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=begin.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces [begin](#%28form._%28%28quote._~23~25kernel%29._begin%29%29) and [begin0](#%28form._%28%28quote._~23~25kernel%29._begin0%29%29).\n\n>
\n\n

syntax

\n\n

([begin](#%28form._%28%28quote._~23~25kernel%29._begin%29%29) form ...)

([begin](#%28form._%28%28quote._~23~25kernel%29._begin%29%29) expr ...+)
\n\nThe first form applies when [begin](#%28form._%28%28quote._~23~25kernel%29._begin%29%29) appears at the top level, at module level, or in an internal-definition position. In that case, the [begin](#%28form._%28%28quote._~23~25kernel%29._begin%29%29) form is equivalent to splicing the forms into the enclosing context.\n\nThe second form applies for [begin](#%28form._%28%28quote._~23~25kernel%29._begin%29%29) in an expression position. In that case, the exprs are evaluated in order, and the results are ignored for all but the last expr. The last expr is in tail position with respect to the [begin](#%28form._%28%28quote._~23~25kernel%29._begin%29%29) form.\n\nExamples:\n\n> ```racket\n> > ( begin ( define x 10 ) x )\n> 10\n> > ( + 1 ( begin ( printf \"hi\\n\" ) 2 ) )\n> hi\n> 3\n> > ( let-values ( [ ( x y ) ( begin ( values 1 2 3 ) ( values 1 2 ) ) ] ) ( list x y ) )\n> '(1 2)\n> ```\n\n>
\n\n

syntax

\n\n

([begin0](#%28form._%28%28quote._~23~25kernel%29._begin0%29%29) expr ...+)

\n\nEvaluates the first expr, then evaluates the other exprss in order, ignoring their results. The results of the first expr are the results of the [begin0](#%28form._%28%28quote._~23~25kernel%29._begin0%29%29) form; the first expr is in tail position only if no other exprs are present.\n\nExample:\n\n> ```racket\n> > ( begin0 ( values 1 2 ) ( printf \"hi\\n\" ) )\n> hi\n> 1 2\n> ```\n\n>
\n\n

syntax

\n\n

([begin-for-syntax](#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29) form ...)

\n\nAllowed only in a [top-level context](syntax-model.html#%28tech._top._level._context%29) or [module context](syntax-model.html#%28tech._module._context%29), shifts the [phase level](syntax-model.html#%28tech._phase._level%29) of each form by one:\n\n- expressions reference bindings at a [phase level](syntax-model.html#%28tech._phase._level%29) one greater than in the context of the [begin-for-syntax](#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29) form;\n\n- [define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-values](define.html#%28form._%28%28quote._~23~25kernel%29._define-values%29%29), [define-syntax](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), and [define-syntaxes](define.html#%28form._%28%28quote._~23~25kernel%29._define-syntaxes%29%29) forms bind at a [phase level](syntax-model.html#%28tech._phase._level%29) one greater than in the context of the [begin-for-syntax](#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29) form;\n\n- in [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) and [provide](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) forms, the default [phase level](syntax-model.html#%28tech._phase._level%29) is greater, which is roughly like wrapping the content of the [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) form with [for-syntax](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-syntax%29%29);\n\n- expression form expr: converted to ([define-values-for-syntax](define.html#%28form._%28%28lib._racket%2Fprivate%2Fdefine..rkt%29._define-values-for-syntax%29%29) () ([begin](#%28form._%28%28quote._~23~25kernel%29._begin%29%29) expr ([values](values.html#%28def._%28%28quote._~23~25kernel%29._values%29%29)))), which effectively evaluates the expression at expansion time and, in the case of a [module context](syntax-model.html#%28tech._module._context%29), preserves the expression for future [visit](syntax-model.html#%28tech._visit%29)s of the module.\n\nSee also [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) for information about expansion order and partial expansion for [begin-for-syntax](#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29) within a module context. Evaluation of an [expr](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=syntax&rel=Library_Syntax_Classes_and_Literal_Sets.html%23%2528form._%2528%2528lib._syntax%252Fparse..rkt%2529._expr%2529%2529&version=8.18.0.13) within [begin-for-syntax](#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29) is [parameterize](parameters.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize%29%29)d to set [current-namespace](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._current-namespace%29%29) as in [let-syntax](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let-syntax%29%29).\n\n------------------------------------------------------------------------\n\n# 3.16 Guarded Evaluation: when and unless\n\n### 3.16 Guarded Evaluation: [when](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._when%29%29) and [unless](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._unless%29%29)\n\n> > > \"+\"[Effects If...: when and unless](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=begin.html%23%2528part._when%252Bunless%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces [when](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._when%29%29) and [unless](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._unless%29%29).\n\n>
\n\n

syntax

\n\n

([when](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._when%29%29) test-expr body ...+)

\n\nEvaluates test-expr. If the result is #f, then the result of the [when](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._when%29%29) expression is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13). Otherwise, the bodys are evaluated, and the last body is in tail position with respect to the [when](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._when%29%29) form.\n\nExamples:\n\n> ```racket\n> > ( when ( positive? -5 ) ( display \"hi\" ) )\n> > ( when ( positive? 5 ) ( display \"hi\" ) ( display \" there\" ) )\n> hi there\n> ```\n\n>
\n\n

syntax

\n\n

([unless](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._unless%29%29) test-expr body ...+)

\n\nEquivalent to ([when](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._when%29%29) ([not](booleans.html#%28def._%28%28quote._~23~25kernel%29._not%29%29) test-expr) body [...+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=syntax&rel=stxparse-patterns.html%23%2528form._%2528%2528lib._syntax%252Fparse..rkt%2529._......%252B%2529%2529&version=8.18.0.13)).\n\nExamples:\n\n> ```racket\n> > ( unless ( positive? 5 ) ( display \"hi\" ) )\n> > ( unless ( positive? -5 ) ( display \"hi\" ) ( display \" there\" ) )\n> hi there\n> ```\n\n------------------------------------------------------------------------\n\n# 3.17 Assignment: set! and set!-values\n\n### 3.17 Assignment: [set!](#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) and [set!-values](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._set%21-values%29%29)\n\n> > > \"+\"[Assignment: set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=set_.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces [set!](#%28form._%28%28quote._~23~25kernel%29._set%21%29%29).\n\n>
\n\n

syntax

\n\n

([set!](#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) id expr)

\n\nIf id has a [transformer](syntax-model.html#%28tech._transformer%29) binding to an [assignment transformer](syntax-model.html#%28tech._assignment._transformer%29), as produced by [make-set!-transformer](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._make-set%21-transformer%29%29) or as an instance of a structure type with the [prop:set!-transformer](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._prop~3aset%21-transformer%29%29) property, then this form is expanded by calling the assignment transformer with the full expressions. If id has a [transformer](syntax-model.html#%28tech._transformer%29) binding to a [rename transformer](syntax-model.html#%28tech._rename._transformer%29) as produced by [make-rename-transformer](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._make-rename-transformer%29%29) or as an instance of a structure type with the [prop:rename-transformer](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._prop~3arename-transformer%29%29) property, then this form is expanded by replacing id with the target identifier (e.g., the one provided to [make-rename-transformer](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._make-rename-transformer%29%29)). If a transformer binding has both [prop:set!-transformer](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._prop~3aset%21-transformer%29%29) and [prop:rename-transformer](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._prop~3arename-transformer%29%29) properties, the latter takes precedence.\n\nOtherwise, evaluates expr and installs the result into the location for id, which must be bound as a local variable or defined as a [top-level variable](eval-model.html#%28tech._top._level._variable%29) or [module-level variable](eval-model.html#%28tech._module._level._variable%29). If id refers to an imported binding, a syntax error is reported. If id refers to a [top-level variable](eval-model.html#%28tech._top._level._variable%29) that has not been defined, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nSee also [compile-allow-set!-undefined](eval.html#%28def._%28%28quote._~23~25kernel%29._compile-allow-set%21-undefined%29%29).\n\nExamples:\n\n> ```racket\n> > ( define x 12 )\n> > ( set! x ( add1 x ) )\n> > x\n> 13\n> > ( let ( [ x 5 ] ) ( set! x ( add1 x ) ) x )\n> 6\n> > ( set! i-am-not-defined 10 )\n> set!: assignment disallowed;\n> cannot set variable before its definition\n> variable: i-am-not-defined\n> in module: top-level\n> ```\n\n>
\n\n

syntax

\n\n

([set!-values](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._set%21-values%29%29) (id ...) expr)

\n\nAssuming that all ids refer to variables, this form evaluates expr, which must produce as many values as supplied ids. The location of each id is filled with the corresponding value from expr in the same way as for [set!](#%28form._%28%28quote._~23~25kernel%29._set%21%29%29).\n\nExample:\n\n> ```racket\n> > ( let ( [ a 1 ] [ b 2 ] ) ( set!-values ( a b ) ( values b a ) ) ( list a b ) )\n> '(2 1)\n> ```\n\nMore generally, the [set!-values](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._set%21-values%29%29) form is expanded to\n\n> ```racket\n> ( let-values ( [ ( tmp-id ... ) expr ] )\n> ( set! id tmp-id ) ... )\n> ```\n\nwhich triggers further expansion if any id has a transformer binding to an [assignment transformer](syntax-model.html#%28tech._assignment._transformer%29).\n\n------------------------------------------------------------------------\n\n# 3.18 Iterations and Comprehensions: for, for/list, ...\n\n### 3.18 Iterations and Comprehensions: [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29), [for/list](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29), ...\n\n> > > \"+\"[Iterations and Comprehensions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=for.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces iterations and comprehensions.\n\nThe [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) iteration forms are based on SRFI-42 \\[[SRFI-42](doc-bibliography.html#%28cite._.S.R.F.I-42%29)\\].\n\n#### 3.18.1 Iteration and Comprehension Forms\n\n>
\n\n

syntax

\n\n

([for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) (for-clause ...) body-or-break ... body)

 
for-clause = [id seq-expr]
  | [(id ...) seq-expr]
  | #:when guard-expr
  | #:unless guard-expr
  | #:do [do-body ...]
  | break-clause
  | #:splice (splicing-id . form)
     
break-clause = #:break guard-expr
  | #:final guard-expr
     
body-or-break = body
  | break-clause
 
  seq-expr : [sequence?](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence~3f%29%29)
\n\nIteratively evaluates bodys. The for-clauses introduce bindings whose scope includes body and that determine the number of times that body is evaluated. A break-clause either among the for-clauses or bodys stops further iteration.\n\nIn the simple case, each for-clause has one of its first two forms, where \\[id seq-expr\\] is a shorthand for \\[(id) seq-expr\\]. In this simple case, the seq-exprs are evaluated left-to-right, and each must produce a sequence value (see [Sequences](sequences.html)).\n\nThe [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) form iterates by drawing an element from each sequence; if any sequence is empty, then the iteration stops, and [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13) is the result of the [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) expression. Otherwise a location is created for each id to hold the values of each element; the sequence produced by a seq-expr must return as many values for each iteration as corresponding ids.\n\nThe ids are then bound in the body, which is evaluated, and whose results are ignored. Iteration continues with the next element in each sequence and with fresh locations for each id.\n\nA [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) form with zero for-clauses is equivalent to a single for-clause that binds an unreferenced id to a sequence containing a single element. All of the ids must be distinct according to [bound-identifier=?](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._bound-identifier~3d~3f%29%29).\n\nIf any for-clause has the form #:when guard-expr, then only the preceding clauses (containing no #:when, #:unless, or #:do) determine iteration as above, and the body is effectively wrapped as\n\n> ```racket\n> ( when guard-expr\n> ( for ( for-clause ... ) body ...+ ) )\n> ```\n\nusing the remaining for-clauses. A for-clause of the form #:unless guard-expr corresponds to the same transformation with [unless](when_unless.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._unless%29%29) in place of [when](when_unless.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._when%29%29). A for-clause of the form #:do \\[do-body [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)\\] similarly creates nesting and corresponds to\n\n> ```racket\n> ( let ( )\n> do-body ...\n> ( for ( for-clause ... ) body ...+ ) )\n> ```\n\nwhere the do-body forms may introduce definitions that are visible in the remaining for-clauses.\n\nA #:break guard-expr clause is similar to a #:unless guard-expr clause, but when #:break avoids evaluation of the bodys, it also effectively ends all sequences within the [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) form. A #:final guard-expr clause is similar to #:break guard-expr, but instead of immediately ending sequences and skipping the bodys, it allows at most one more element from each later sequence and at most one more evaluation of the following bodys. Among the bodys, besides stopping the iteration and preventing later body evaluations, a #:break guard-expr or #:final guard-expr clause starts a new internal-definition context.\n\nA #:splice (splicing-id . form) clause is replaced by the sequence of forms that are produced by expanding (splicing-id . form), where splicing-id is bound using [define-splicing-for-clause-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-splicing-for-clause-syntax%29%29). The binding context of that expansion includes previous binding from any clause preceding both the #:splice form and a #:when, #:unless, #:do, #:break, or #:final form. The result of a #:splice expansion can include more #:splice forms to further interleave clause binding and expansion. Support for #:splice clauses is intended less for direct use in source [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) forms than for building new forms that expand to [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29).\n\nIn the case of [list](pairs.html#%28tech._list%29) and [stream](streams.html#%28tech._stream%29) sequences, the [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) form itself does not keep each element reachable. If a list or stream produced by a seq-expr is otherwise unreachable, and if the [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) body can no longer reference an id for a list element, then the element is subject to [garbage collection](eval-model.html#%28tech._garbage._collection%29). The [make-do-sequence](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-do-sequence%29%29) sequence constructor supports additional sequences that behave like lists and streams in this way.\n\nIf a seq-expr is a quoted literal list, vector, exact integer, string, byte string, immutable hash, or expands to such a literal, then it may be treated as if a sequence transformer such as [in-list](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-list%29%29) was used, unless the seq-expr has a true value for the 'for:no-implicit-optimization syntax property; in most cases this improves performance.\n\nExamples:\n\n> ```racket\n> > ( for ( [ i ' ( 1 2 3 ) ] [ j \"abc\" ] #:when ( odd? i ) [ k # ( #t #f ) ] ) ( display ( list i j k ) ) )\n> (1 a #t)(1 a #f)(3 c #t)(3 c #f)\n> > ( for ( [ i ' ( 1 2 3 ) ] #:do [ ( define neg-i ( * i -1 ) ) ] [ j ( list neg-i 0 i ) ] ) ( display ( list j ) ) )\n> (-1)(0)(1)(-2)(0)(2)(-3)(0)(3)\n> > ( for ( [ ( i j ) #hash ( ( \"a\" . 1 ) ( \"b\" . 20 ) ) ] ) ( display ( list i j ) ) )\n> (a 1)(b 20)\n> > ( for ( [ i ' ( 1 2 3 ) ] [ j \"abc\" ] #:break ( not ( odd? i ) ) [ k # ( #t #f ) ] ) ( display ( list i j k ) ) )\n> (1 a #t)(1 a #f)\n> > ( for ( [ i ' ( 1 2 3 ) ] [ j \"abc\" ] #:final ( not ( odd? i ) ) [ k # ( #t #f ) ] ) ( display ( list i j k ) ) )\n> (1 a #t)(1 a #f)(2 b #t)\n> > ( for ( [ i ' ( 1 2 3 ) ] [ j \"abc\" ] [ k # ( #t #f ) ] ) #:break ( not ( or ( odd? i ) k ) ) ( display ( list i j k ) ) )\n> (1 a #t)\n> > ( for ( ) ( display \"here\" ) )\n> here\n> > ( for ( [ i ' ( ) ] ) ( error \"doesn't get here\" ) )\n> ```\n\nChanged in version 6.7.0.4 of package base: Added support for the optional second result. \nChanged in version 7.8.0.11: Added support for implicit optimization. \nChanged in version 8.4.0.2: Added #:do. \nChanged in version 8.4.0.3: Added #:splice.\n\n>
\n\n

syntax

\n\n

([for/list](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29) (for-clause ...) body-or-break ... body)

\n\nIterates like [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29), but that the last expression in the bodys must produce a single value, and the result of the [for/list](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29) expression is a list of the results in order. When evaluation of a body is skipped due to a #:when or #:unless clause, the result list includes no corresponding element.\n\nExamples:\n\n> ```racket\n> > ( for/list ( [ i ' ( 1 2 3 ) ] [ j \"abc\" ] #:when ( odd? i ) [ k # ( #t #f ) ] ) ( list i j k ) )\n> '((1 #\\a #t) (1 #\\a #f) (3 #\\c #t) (3 #\\c #f))\n> > ( for/list ( [ i ' ( 1 2 3 ) ] [ j \"abc\" ] #:break ( not ( odd? i ) ) [ k # ( #t #f ) ] ) ( list i j k ) )\n> '((1 #\\a #t) (1 #\\a #f))\n> > ( for/list ( ) ' any )\n> '(any)\n> > ( for/list ( [ i ' ( ) ] ) ( error \"doesn't get here\" ) )\n> '()\n> ```\n\n>
\n\n

syntax

\n\n

([for/vector](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fvector%29%29) maybe-length (for-clause ...) body-or-break ... body)

 
maybe-length = 
  | #:length length-expr
  | #:length length-expr #:fill fill-expr
 
  length-expr : [exact-nonnegative-integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-nonnegative-integer~3f%29%29)
\n\nIterates like [for/list](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29), but results are accumulated into a vector instead of a list.\n\nIf the optional #:length clause is specified, the result of length-expr determines the length of the result vector. In that case, the iteration can be performed more efficiently, and it terminates when the vector is full or the requested number of iterations have been performed, whichever comes first. If length-expr specifies a length longer than the number of iterations, then the remaining slots of the vector are initialized to the value of fill-expr, which defaults to 0 (i.e., the default argument of [make-vector](vectors.html#%28def._%28%28quote._~23~25kernel%29._make-vector%29%29)).\n\nExamples:\n\n> ```racket\n> > ( for/vector ( [ i ' ( 1 2 3 ) ] ) ( number->string i ) )\n> '#(\"1\" \"2\" \"3\")\n> > ( for/vector #:length 2 ( [ i ' ( 1 2 3 ) ] ) ( number->string i ) )\n> '#(\"1\" \"2\")\n> > ( for/vector #:length 4 ( [ i ' ( 1 2 3 ) ] ) ( number->string i ) )\n> '#(\"1\" \"2\" \"3\" 0)\n> > ( for/vector #:length 4 #:fill \"?\" ( [ i ' ( 1 2 3 ) ] ) ( number->string i ) )\n> '#(\"1\" \"2\" \"3\" \"?\")\n> ```\n\nThe [for/vector](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fvector%29%29) form may allocate a vector and mutate it after each iteration of body, which means that capturing a continuation during body and applying it multiple times may mutate a shared vector.\n\n>
\n\n

syntax

\n\n

([for/hash](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fhash%29%29) (for-clause ...) body-or-break ... body)

\n\n

syntax

\n\n

([for/hasheq](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fhasheq%29%29) (for-clause ...) body-or-break ... body)

\n\n

syntax

\n\n

([for/hasheqv](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fhasheqv%29%29) (for-clause ...) body-or-break ... body)

\n\n

syntax

\n\n

([for/hashalw](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fhashalw%29%29) (for-clause ...) body-or-break ... body)

\n\nLike [for/list](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29), but the result is an immutable [hash table](hashtables.html#%28tech._hash._table%29); [for/hash](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fhash%29%29) creates a table using [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) to distinguish keys, [for/hasheq](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fhasheq%29%29) produces a table using [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29), [for/hasheqv](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fhasheqv%29%29) produces a table using [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), and [for/hashalw](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fhashalw%29%29) produces a table using [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29). The last expression in the bodys must return two values: a key and a value to extend the hash table accumulated by the iteration.\n\nExample:\n\n> ```racket\n> > ( for/hash ( [ i ' ( 1 2 3 ) ] ) ( values i ( number->string i ) ) )\n> '#hash((1 . \"1\") (2 . \"2\") (3 . \"3\"))\n> ```\n\nChanged in version 8.5.0.3 of package base: Added the [for/hashalw](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fhashalw%29%29) form.\n\n>
\n\n

syntax

\n\n

([for/and](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fand%29%29) (for-clause ...) body-or-break ... body)

\n\nIterates like [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29), but when last expression of body produces #f, then iteration terminates, and the result of the [for/and](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fand%29%29) expression is #f. If the body is never evaluated, then the result of the [for/and](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fand%29%29) expression is #t. Otherwise, the result is the (single) result from the last evaluation of body.\n\nExamples:\n\n> ```racket\n> > ( for/and ( [ i ' ( 1 2 3 \"x\" ) ] ) ( i . < . 3 ) )> #f\n> > ( for/and ( [ i ' ( 1 2 3 4 ) ] ) i )\n> 4\n> > ( for/and ( [ i ' ( 1 2 3 4 ) ] ) #:break ( = i 3 ) i )\n> 2\n> > ( for/and ( [ i ' ( ) ] ) ( error \"doesn't get here\" ) )\n> #t\n> ```\n\n>
\n\n

syntax

\n\n

([for/or](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2For%29%29) (for-clause ...) body-or-break ... body)

\n\nIterates like [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29), but when last expression of body produces a value other than #f, then iteration terminates, and the result of the [for/or](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2For%29%29) expression is the same (single) value. If the body is never evaluated, then the result of the [for/or](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2For%29%29) expression is #f. Otherwise, the result is #f.\n\nExamples:\n\n> ```racket\n> > ( for/or ( [ i ' ( 1 2 3 \"x\" ) ] ) ( i . < . 3 ) )> #t\n> > ( for/or ( [ i ' ( 1 2 3 4 ) ] ) i )\n> 1\n> > ( for/or ( [ i ' ( ) ] ) ( error \"doesn't get here\" ) )\n> #f\n> ```\n\n>
\n\n

syntax

\n\n

([for/sum](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fsum%29%29) (for-clause ...) body-or-break ... body)

\n\nIterates like [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29), but each result of the last body is accumulated into a result with [+](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._%2B%29%29).\n\nExample:\n\n> ```racket\n> > ( for/sum ( [ i ' ( 1 2 3 4 ) ] ) i )\n> 10\n> ```\n\n>
\n\n

syntax

\n\n

([for/product](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fproduct%29%29) (for-clause ...) body-or-break ... body)

\n\nIterates like [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29), but each result of the last body is accumulated into a result with [*](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._%2A%29%29).\n\nExample:\n\n> ```racket\n> > ( for/product ( [ i ' ( 1 2 3 4 ) ] ) i )\n> 24\n> ```\n\n> ```\nsyntax\n\n(for/lists (id ... maybe-result)\n> ( for-clause ... )\n> body-or-break ... body )\n \nmaybe-result   =  \n    |   #:result result-expr\n```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nSimilar to for/list, but the last body expression should produce as many values as given ids. The ids are bound to the reversed lists accumulated so far in the for-clauses and bodys.\nIf a result-expr is provided, it is used as with for/fold when iteration terminates; otherwise, the result is as many lists as supplied ids.\nThe scope of id bindings is the same as for accumulator identifiers in for/fold. Mutating a id affects the accumulated lists, and mutating it in a way that produces a non-list can cause a final reverse for each id to fail.\nExamples:\n> ```racket\n> > ( for/lists ( l1 l2 l3 ) ( [ i ' ( 1 2 3 ) ] [ j \"abc\" ] #:when ( odd? i ) [ k # ( #t #f ) ] ) ( values i j k ) )\n> '(1 1 3 3) '(#\\a #\\a #\\c #\\c) '(#t #f #t #f)\n> > ( for/lists ( acc ) ( [ x ' ( tvp tofu seitan tvp tofu ) ] #:unless ( member x acc ) ) x )\n> '(tvp tofu seitan)\n> > ( for/lists ( firsts seconds #:result ( list firsts seconds ) ) ( [ pr ' ( ( 1 . 2 ) ( 3 . 4 ) ( 5 . 6 ) ) ] ) ( values ( car pr ) ( cdr pr ) ) )\n> '((1 3 5) (2 4 6))\n> ```\nChanged in version 7.1.0.2 of package base: Added the #:result form.\n>
\n

syntax

\n

(for/first (for-clause ...) body-or-break ... body)

"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nIterates like for, but after body is evaluated the first time, then the iteration terminates, and the for/first result is the (single) result of body. If the body is never evaluated, then the result of the for/first expression is #f.\nExamples:\n> ```racket\n> > ( for/first ( [ i ' ( 1 2 3 \"x\" ) ] #:when ( even? i ) ) ( number → string i ) )\n> \"2\"\n> > ( for/first ( [ i ' ( ) ] ) ( error \"doesn't get here\" ) )\n> #f\n> ```\n>
\n

syntax

\n

(for/last (for-clause ...) body-or-break ... body)

\nIterates like for, but the for/last result is the (single) result of the last evaluation of body. If the body is never evaluated, then the result of the for/last expression is #f.\nExamples:\n> ```racket\n> > ( for/last ( [ i ' ( 1 2 3 4 5 ) ] #:when ( even? i ) ) ( number → string i ) )\n> \"4\"\n> > ( for/last ( [ i ' ( ) ] ) ( error \"doesn't get here\" ) )\n> #f\n> ```\n> ```\nsyntax\n(for/fold ([accum-id init-expr] ... maybe-result) (for-clause ...)\n> body-or-break ... body )\nmaybe-result   =  \n    |   #:result result-expr```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nIterates like [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29). Before iteration starts, the init-exprs are evaluated to produce initial accumulator values. At the start of each iteration, a location is generated for each accum-id, and the corresponding current accumulator value is placed into the location. The last expression in body must produce as many values as accum-ids, and those values become the current accumulator values. When iteration terminates, if a result-expr is provided then the result of the [for/fold](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Ffold%29%29) is the result of evaluating result-expr (with accum-ids in scope and bound to their final values), otherwise the results of the [for/fold](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Ffold%29%29) expression are the accumulator values.\nExamples:\n> ```racket\n> > ( for/fold ( [ sum 0 ] [ rev-roots null ] ) ( [ i ' ( 1 2 3 4 ) ] ) ( values ( + sum i ) ( cons ( sqrt i ) rev-roots ) ) )\n> 10 '(2 1.7320508075688772 1.4142135623730951 1)\n> > ( for/fold ( [ acc ' ( ) ] [ seen ( hash ) ] #:result ( reverse acc ) ) ( [ x ( in-list ' ( 0 1 1 2 3 4 4 4 ) ) ] ) ( cond [ ( hash-ref seen x #f ) ( values acc seen ) ] [ else ( values ( cons x acc ) ( hash-set seen x #t ) ) ] ) )\n> '(0 1 2 3 4)\n> ```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nThe binding and evaluation order of accum-ids and init-exprs follow the textual, left-to-right order relative to the for-clauses, except that (for historical reasons) accum-ids are not available in the for-clauses for the outermost iteration. The lifetimes of variables are not quite the same as the lexical nesting, however: the variable referenced by a accum-id has a fresh location in each iteration.\nChanged in version 6.11.0.1 of package base: Added the #:result form. \nChanged in version 8.11.1.3: Changed evaluation order to match textual left-to-right order, including evaluating init-exprs before the first for-clause’s right-hand side and fixing shadowing of accum-id.\n> ```\nsyntax\n(for/foldr ([accum-id init-expr] ... accum-option ...)\n> ( for-clause ... )\n> body-or-break ... body )\naccum-option   =   #:result result-expr\n    |   #:delay\n    |   #:delay-as delayed-id\n    |   #:delay-with delayer-id"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n```\nLike for/fold, but analogous to foldr rather than foldl: the given sequences are still iterated in the same order, but the loop body is evaluated in reverse order. Evaluation of a for/foldr expression uses space proportional to the number of iterations it performs, and all elements produced by the given sequences are retained until backwards evaluation of the loop body begins (assuming the element is, in fact, referenced in the body).\n\nExamples:\n\n> ```racket\n> > ( define ( in-printing seq ) ( sequence-map ( lambda ( v ) ( println v ) v ) seq ) )\n> > ( for/foldr ( [ acc ' ( ) ] ) ( [ v ( in-printing ( in-range 1 4 ) ) ] ) ( println v ) ( cons v acc ) )\n> 1 2 3 3 2 1\n> '(1 2 3)\n> ```\n\nFurthermore, unlike for/fold, the accum-ids are not bound within guard-exprs or body-or-break forms that appear before a break-clause.\n\nWhile the aforementioned limitations make for/foldr less generally useful than for/fold, for/foldr provides the additional capability to iterate lazily via the #:delay, #:delay-as, and #:delay-with options, which can mitigate many of for/foldr’s disadvantages. If at least one such option is specified, the loop body is given explicit control over when iteration continues: by default, each accum-id is bound to a promise that, when forced, produces the accum-id’s current value.\n\nIn this mode, iteration does not continue until one such promise is forced, which triggers any additional iteration necessary to produce a value. If the loop body is lazy in its accum-ids—that is, it returns a value without forcing any of them—then the loop (or any of its iterations) will produce a value before iteration has completely finished. If a reference to at least one such promise is retained, then forcing it will resume iteration from the point at which it was suspended, even if control has left the dynamic extent of the loop body.\n\nExamples:\n\n> ```racket\n> > ( for/foldr ( [ acc ' ( ) ] #:delay ) ( [ v ( in-range 1 4 ) ] ) ( printf \"- → ~v\\n\" v ) ( begin0 ( cons v ( force acc ) ) ( printf \"<-- ~v\\n\" v ) ) )> - → 1 - → 2 - → 3 <-- 3 <-- 2 <-- 1> '(1 2 3)\n> > ( define resume ( for/foldr ( [ acc ' ( ) ] #:delay ) ( [ v ( in-range 1 5 ) ] ) ( printf \"- → ~v\\n\" v ) ( begin0 ( cond [ ( = v 1 ) ( force acc ) ] [ ( = v 2 ) acc ] [ else ( cons v ( force acc ) ) ] ) ( printf \"<-- ~v\\n\" v ) ) ) )> - → 1 - → 2 <-- 2 <-- 1> > ( force resume )\n> - → 3 - → 4 <-- 4 <-- 3> '(3 4)\n> ```\n\nThis extra control over iteration order allows for/foldr to both consume and construct infinite sequences, so long as it is at least sometimes lazy in its accumulators.\n\n> > > \"+\"See also for/stream for a more convenient (albeit less flexible) way to lazily transform infinite sequences. (Internally, for/stream is defined in terms of for/foldr.)\n\nExamples:\n\n> ```racket\n> > ( define squares ( for/foldr ( [ s empty-stream ] #:delay ) ( [ n ( in-naturals ) ] ) ( stream-cons ( * n n ) ( force s ) ) ) )\n> > ( stream → list ( stream-take squares 10 ) )\n> '(0 1 4 9 16 25 36 49 64 81)\n> ```\n\nThe suspension introduced by the #:delay option does not ordinarily affect the loop’s eventual return value, but if #:delay and #:result are combined, the accum-ids will be delayed in the scope of the result-expr in the same way they are delayed within the loop body. This can be used to introduce an additional layer of suspension around the evaluation of the entire loop, if desired.\n\nExamples:\n\n> ```racket\n> > ( define evaluated-yet? #f )\n> > ( for/foldr ( [ acc ( set! evaluated-yet? #t ) ] #:delay ) ( ) ( force acc ) )\n> > evaluated-yet?\n> #t\n> ```\n\n> ```racket\n> > ( define evaluated-yet? #f )\n> > ( define start ( for/foldr ( [ acc ( set! evaluated-yet? #t ) ] #:delay #:result acc ) ( ) ( force acc ) ) )\n> > evaluated-yet?\n> #f\n> > ( force start )\n> > evaluated-yet?\n> #t\n> ```\n\nIf the #:delay-as option is provided, then delayed-id is bound to an additional promise that returns the values of all accum-ids at once. When multiple accum-ids are provided, forcing this promise can be slightly more efficient than forcing the promises bound to the accum-ids individually.\n\nIf the #:delay-with option is provided, the given delayer-id is used to suspend nested iterations (instead of the default, delay). A form of the shape (delayer-id recur-expr) is constructed and placed in expression position, where recur-expr is an expression that, when evaluated, will perform the next iteration and return its result (or results). Sensible choices for delayer-id include lazy, delay/sync, delay/thread, or any of the other promise constructors from racket/promise, as well as thunk from racket/function. However, beware that choices such as thunk or delay/name may evaluate their subexpression multiple times, which can lead to nonsensical results for sequences that have state, as the state will be shared between all evaluations of the recur-expr.\n\nIf multiple accum-ids are given, the #:delay-with option is provided, and delayer-id is not bound to one of delay, lazy, delay/strict, delay/sync, delay/thread, or delay/idle, the accum-ids will not be bound at all, even within the loop body. Instead, the #:delay-as option must be specified to access the accumulator values via delayed-id.\n\nAdded in version 7.3.0.3 of package base.\n\n>
\n\n

syntax

\n\n

(for* (for-clause ...) body-or-break ... body)

\n\nLike for, but with an implicit #:when #t between each pair of for-clauses, so that all sequence iterations are nested.\n\nExample:\n\n> ```racket\n> > ( for* ( [ i ' ( 1 2 ) ] [ j \"ab\" ] ) ( display ( list i j ) ) )\n> (1 a)(1 b)(2 a)(2 b)\n> ```\n\n> ```\nsyntax\n\n(for*/list (for-clause ...) body-or-break ... body)\n\nsyntax\n\n( for*/lists ( id ... maybe-result ) ( for-clause ... )\n> body-or-break ... body )\n\nsyntax\n\n(for*/vector maybe-length (for-clause ...) body-or-break ... body)\n\nsyntax\n\n(for*/hash (for-clause ...) body-or-break ... body)\n\nsyntax\n\n(for*/hasheq (for-clause ...) body-or-break ... body)\n\nsyntax\n\n(for*/hasheqv (for-clause ...) body-or-break ... body)\n\nsyntax\n\n(for*/hashalw (for-clause ...) body-or-break ... body)\n\nsyntax\n\n(for*/and (for-clause ...) body-or-break ... body)\n\nsyntax\n\n(for*/or (for-clause ...) body-or-break ... body)\n\nsyntax\n\n(for*/sum (for-clause ...) body-or-break ... body)\n\nsyntax\n\n(for*/product (for-clause ...) body-or-break ... body)\n\nsyntax\n\n(for*/first (for-clause ...) body-or-break ... body)\n\nsyntax\n\n(for*/last (for-clause ...) body-or-break ... body)\n\nsyntax\n\n( for*/fold ( [ accum-id init-expr ] ... maybe-result ) ( for-clause ... )\n> body-or-break ... body )\n\nsyntax\n\n( for*/foldr ( [ accum-id init-expr ] ... accum-option ... )\n> ( for-clause ... )\n> body-or-break ... body )```\n\n\nLike [for/list](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29), etc., but with the implicit nesting of [for*](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%29%29).\n\nExample:\n\n> ```racket\n> > ( for*/list ( [ i ' ( 1 2 ) ] [ j \"ab\" ] ) ( list i j ) )\n> '((1 #\\a) (1 #\\b) (2 #\\a) (2 #\\b))\n> ```\n\nChanged in version 7.3.0.3 of package base: Added the [for*/foldr](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%2Ffoldr%29%29) form. \nChanged in version 8.5.0.3: Added the [for*/hashalw](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%2Fhashalw%29%29) form.\n\n#### 3.18.2 Deriving New Iteration Forms\n\n> ```\nsyntax\n\n(for/fold/derived orig-datum\n> ( [ accum-id init-expr ] ... maybe-result ) ( for-clause ... )\n> body-or-break ... body )\n```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n(parameter)\t→```\nLike [for*/fold](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%2Ffold%29%29), but the extra orig-datum is used as the source for all syntax errors.\nExamples:\n> ```racket\n> > ( require ( for-syntax syntax/for-body ) syntax/parse/define )\n> > ( define-syntax-parse-rule ( for*/digits clauses body ... tail-expr ) #:with original this-syntax #:with ( ( pre-body ... ) ( post-body ... ) ) ( split-for-body this-syntax #' ( body ... tail-expr ) ) ( for*/fold/derived original ( [ n 0 ] [ k 1 ] #:result n ) clauses pre-body ... ( values ( + n ( * ( let ( ) post-body ... ) k ) ) ( * k 10 ) ) ) )\n> > ( for*/digits [ ds ( in-list ' ( ( 8 3 ) ( 1 1 ) ) ) ] [ d ( in-list ds ) ] d )\n> eval:10:0: for*/digits: bad sequence binding clause\n> at: ds\n> in: (for*/digits (ds (in-list (quote ((8 3) (1 1))))) (d\n> (in-list ds)) d)\n> > ( for*/digits ( [ ds ( in-list ' ( ( 8 3 ) ( 1 1 ) ) ) ] [ d ( in-list ds ) ] ) d )\n> 1138\n> ```\nChanged in version 6.11.0.1 of package base: Added the #:result form.\n> ```\nsyntax\n(for/foldr/derived orig-datum\n> ( [ accum-id init-expr ] ... accum-option ... ) ( for-clause ... )\n> body-or-break ... body )\nsyntax\n( for*/foldr/derived orig-datum\n> ( [ accum-id init-expr ] ... accum-option ... ) ( for-clause ... )\n> body-or-break ... body )"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n```\nLike for/foldr and for*/foldr, but the extra orig-datum is used as the source for all syntax errors as in for/fold/derived and for*/fold/derived.\n\nAdded in version 7.3.0.3 of package base.\n\n> ```\nsyntax\n\n( define-sequence-syntax id\n> expr-transform-expr\n> clause-transform-expr )\n \n   expr-transform-expr   :   ( or/c ( → identifier? )\n> ( syntax? . → . syntax? ) )\n   clause-transform-expr   :   (syntax? . → . syntax?)```\n\n\nDefines id as syntax. An (id . rest) form is treated specially when used to generate a sequence in a for-clause of [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) (or one of its variants). In that case, the procedure result of clause-transform-expr is called to transform the clause.\n\nWhen id is used in any other expression position, the result of expr-transform-expr is used. If it is a procedure of zero arguments, then the result must be an identifier other-id, and any use of id is converted to a use of other-id. Otherwise, expr-transform-expr must produce a procedure (of one argument) that is used as a macro transformer.\n\nWhen the clause-transform-expr transformer is used, it is given a for-clause as an argument, where the clause’s form is normalized so that the left-hand side is a parenthesized sequence of identifiers. The right-hand side is of the form (id . rest). The result can be either #f, to indicate that the forms should not be treated specially (perhaps because the number of bound identifiers is inconsistent with the (id . rest) form), or a new for-clause to replace the given one. The new clause might use [:do-in](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~3ado-in%29%29). To protect identifiers in the result of clause-transform-expr, use [for-clause-syntax-protect](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-clause-syntax-protect%29%29) instead of [syntax-protect](stxcerts.html#%28def._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax-protect%29%29).\n\nExamples:\n\n> ```racket\n> > ( define ( check-nat n ) ( unless ( exact-nonnegative-integer? n ) ( raise-argument-error ' in-digits \"exact-nonnegative-integer?\" n ) ) )\n> > ( define-sequence-syntax in-digits ( lambda ( ) #' in-digits/proc ) ( lambda ( stx ) ( syntax-case stx ( ) [ [ ( d ) ( _ nat ) ] #' [ ( d ) ( :do-in ( [ ( n ) nat ] ) ( check-nat n ) ( [ i n ] ) ( not ( zero? i ) ) ( [ ( j d ) ( quotient/remainder i 10 ) ] ) #t #t [ j ] ) ] ] [ _ #f ] ) ) )\n> > ( define ( in-digits/proc n ) ( for/list ( [ d ( in-digits n ) ] ) d ) )\n> > ( for/list ( [ d ( in-digits 1138 ) ] ) d )\n> '(8 3 1 1)\n> > ( map in-digits ( list 137 216 ) )\n> '((7 3 1) (6 1 2))\n> ```\n\n>
\n\n

syntax

\n\n
( :do-in ( [ ( outer-id ... ) outer-expr ] ... )\n> outer-defn-or-expr\n> ( [ loop-id loop-expr ] ... )\n> pos-guard\n> ( [ ( inner-id ... ) inner-expr ] ... )\n> maybe-inner-defn-or-expr\n> pre-guard\n> post-guard\n> ( loop-arg ... ) )
 
maybe-inner-defn/expr = 
  | inner-defn-or-expr
\n\nA form that can only be used as a seq-expr in a for-clause of [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) (or one of its variants).\n\nWithin a [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29), the pieces of the [:do-in](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~3ado-in%29%29) form are spliced into the iteration essentially as follows:\n\n> ```racket\n> ( let-values ( [ ( outer-id ... ) outer-expr ] ... )\n> outer-defn-or-expr\n> ( let loop ( [ loop-id loop-expr ] ... )\n> ( if pos-guard\n> ( let-values ( [ ( inner-id ... ) inner-expr ] ... )\n> inner-defn-or-expr\n> ( if pre-guard\n> ( let body-bindings\n> ( if post-guard\n> ( loop loop-arg ... )\n> done-expr ) )\n> done-expr ) )\n> done-expr ) ) )\n> ```\n\nwhere body-bindings and done-expr are from the context of the [:do-in](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~3ado-in%29%29) use. The identifiers bound by the [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) clause are typically part of the (\\[(inner-id [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) inner-expr\\] [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) section. When inner-defn-or-expr is not provided ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29)) is used in its place.\n\nBeware that body-bindings and done-expr can contain arbitrary expressions, potentially including [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) on outer-id or inner-id identifiers if they are visible in the original [for](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) form, so beware of depending on such identifiers in post-guard and loop-arg.\n\nThe actual loop binding and call has additional loop arguments to support iterations in parallel with the [:do-in](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~3ado-in%29%29) form, and the other pieces are similarly accompanied by pieces from parallel iterations.\n\nFor an example of [:do-in](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~3ado-in%29%29), see [define-sequence-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-sequence-syntax%29%29).\n\nChanged in version 8.10.0.3 of package base: Added support for non-empty maybe-inner-defn-or-expr.\n\n> ```\n(for-clause-syntax-protect stx)  →  syntax?\n  stx : syntax?\n```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nProvided for-syntax: Like syntax-protect, just returns its argument.\nChanged in version 8.2.0.4 of package base: Changed to just return stx instead of returning “armed” syntax.\n>
\n

syntax

\n

(define-splicing-for-clause-syntax id proc-expr)

\nBinds id for reference via a #:splice clause in a for form. The proc-expr expression is evaluated in phase level 1, and it must produce a procedure that accepts a syntax object and returns a syntax object.\nThe procedure’s input is a syntax object that appears after #:splice. The result syntax object must be a parenthesized sequence of forms, and the forms are spliced in place of the #:splice clause in the enclosing for form.\nExamples:\n> ```racket\n> > ( define-splicing-for-clause-syntax cross3 ( lambda ( stx ) ( syntax-case stx ( ) [ ( _ n m ) #' ( [ n ( in-range 3 ) ] #:when #t [ m ( in-range 3 ) ] ) ] ) ) )\n> > ( for ( #:splice ( cross3 n m ) ) ( println ( list n m ) ) )\n> '(0 0) '(0 1) '(0 2) '(1 0) '(1 1) '(1 2) '(2 0) '(2 1) '(2 2)\n> ```\nAdded in version 8.4.0.3 of package base."} {"text": "#### 3.18.3 Iteration Expansion\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require racket/for-clause) |  package: base |\nThe bindings documented in this section are provided by the racket/for-clause library, not racket/base or racket.\n> ```\n(syntax-local-splicing-for-clause-introduce stx) → syntax?\n  stx : syntax?```\nAnalogous to [syntax-local-introduce](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._syntax-local-introduce%29%29), but for use in an expander bound with [define-splicing-for-clause-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-splicing-for-clause-syntax%29%29).\nAdded in version 8.11.1.4 of package base."} {"text": "#### 3.18.4 Do Loops\n> ```\nsyntax\n(do ([id init-expr step-expr-maybe] ...)\n> ( stop?-expr finish-expr ... )\n> expr ... )\nstep-expr-maybe   =  \n    |   step-expr\n```\nIteratively evaluates the exprs for as long as stop?-expr returns #f.\n\nTo initialize the loop, the init-exprs are evaluated in order and bound to the corresponding ids. The ids are bound in all expressions within the form other than the init-exprs.\n\nAfter the ids have been bound, the stop?-expr is evaluated. If it produces #f, each expr is evaluated for its side-effect. The ids are then effectively updated with the values of the step-exprs, where the default step-expr for id is just id; more precisely, iteration continues with fresh locations for the ids that are initialized with the values of the corresponding step-exprs.\n\nWhen stop?-expr produces a true value, then the finish-exprs are evaluated in order, and the last one is evaluated in tail position to produce the overall value for the do form. If no finish-expr is provided, the value of the do form is #.\n\n------------------------------------------------------------------------\n\n# 3.19 Continuation Marks: with-continuation-mark\n\n### 3.19 Continuation Marks: with-continuation-mark\n\n>
\n\n

syntax

\n\n

(with-continuation-mark key-expr val-expr result-expr)

\n\nThe key-expr, val-expr, and result-expr expressions are evaluated in order. After key-expr is evaluated to obtain a key and val-expr is evaluated to obtain a value, the key is mapped to the value as a continuation mark in the current continuation’s initial continuation frame. If the frame already has a mark for the key, the mark is replaced. Finally, the result-expr is evaluated; the continuation for evaluating result-expr is the continuation of the with-continuation-mark expression (so the result of the result-expr is the result of the with-continuation-mark expression, and result-expr is in tail position for the with-continuation-mark expression).\n\n> > > \"+\"Continuation Marks provides more information on continuation marks.\n\n------------------------------------------------------------------------\n\n# 3.20 Quasiquoting: quasiquote, unquote, and unquote-splicing\n\n### 3.20 Quasiquoting: quasiquote, unquote, and unquote-splicing\n\n> > > \"+\"Quasiquoting: quasiquote and ‘ in The Racket Guide introduces quasiquote.\n\n>
\n\n

syntax

\n\n

(quasiquote datum)

\n\nThe same as 'datum if datum does not include (unquote expr) or (unquote-splicing expr). An (unquote expr) form escapes from the quote, however, and the result of the expr takes the place of the (unquote expr) form in the quasiquote result. An (unquote-splicing expr) similarly escapes, but the expr produces a list whose elements are spliced as multiple values place of the (unquote-splicing expr).\n\nAn unquote or unquote-splicing form is recognized in any of the following escaping positions within datum: in a pair, in a vector, in a box, in a prefab structure field after the name position, and in hash table value position (but not in a hash table key position). Such escaping positions can be nested to an arbitrary depth.\n\nAn unquote-splicing form must appear as the car of a quoted pair, as an element of a quoted vector, or as an element of a quoted prefab structure. In the case of a pair, if the cdr of the relevant quoted pair is empty, then expr need not produce a list, and its result is used directly in place of the quoted pair (in the same way that append accepts a non-list final argument).\n\nIf unquote or unquote-splicing appears within quasiquote in an escaping position but in a way other than as (unquote expr) or (unquote-splicing expr), a syntax error is reported.\n\nExamples:\n\n> ```racket\n> > ( quasiquote ( 0 1 2 ) )\n> '(0 1 2)\n> > ( quasiquote ( 0 ( unquote ( + 1 2 ) ) 4 ) )\n> '(0 3 4)\n> > ( quasiquote ( 0 ( unquote-splicing ( list 1 2 ) ) 4 ) )\n> '(0 1 2 4)\n> > ( quasiquote ( 0 ( unquote-splicing 1 ) 4 ) )\n> unquote-splicing: contract violation\n> expected: list?\n> given: 1\n> > ( quasiquote ( 0 ( unquote-splicing 1 ) ) )\n> '(0 . 1)\n> ```\n\nA quasiquote, unquote, or unquote-splicing form is typically abbreviated with \\`, ,, or ,@, respectively. See also Reading Quotes.\n\nExamples:\n\n> ```racket\n> > ` ( 0 1 2 )\n> '(0 1 2)\n> > ` ( 1 , ( + 1 2 ) 4 )\n> '(1 3 4)\n> > ` #s ( stuff 1 , ( + 1 2 ) 4 )\n> '#s(stuff 1 3 4)\n> > ` #hash ( ( \"a\" . , ( + 1 2 ) ) )\n> '#hash((\"a\" . 3))\n> > ` #hash ( ( , ( + 1 2 ) . \"a\" ) )\n> '#hash((,(+ 1 2) . \"a\"))\n> > ` ( 1 ,@ ( list 1 2 ) 4 )\n> '(1 1 2 4)\n> > ` # ( 1 ,@ ( list 1 2 ) 4 )\n> '#(1 1 2 4)\n> ```\n\nA quasiquote form within the original datum increments the level of quasiquotation: within the quasiquote form, each unquote or unquote-splicing is preserved, but a further nested unquote or unquote-splicing escapes. Multiple nestings of quasiquote require multiple nestings of unquote or unquote-splicing to escape.\n\nExamples:\n\n> ```racket\n> > ` ( 1 ` , ( + 1 , ( + 2 3 ) ) 4 )\n> '(1 `,(+ 1 5) 4)\n> > ` ( 1 ` ` ` , ,@ , ,@ ( list ( + 1 2 ) ) 4 )\n> '(1 ```,,@,3 4)\n> ```\n\nThe quasiquote form allocates only as many fresh cons cells, vectors, and boxes as are needed without analyzing unquote and unquote-splicing expressions. For example, in\n\n> \\`(,1 2 3)\n\na single tail '(2 3) is used for every evaluation of the quasiquote expression. When allocating fresh data, the quasiquote form allocates mutable vectors, mutable boxes and immutable hashes.\n\nExamples:\n\n> ```racket\n> > ( immutable? ` # ( , 0 ) )\n> #f\n> > ( immutable? ` #hash ( ( a . , 0 ) ) )\n> #t\n> ```\n\n>
\n\n

syntax

\n\n

unquote

\n\nSee quasiquote, where unquote is recognized as an escape. An unquote form as an expression is a syntax error.\n\n>
\n\n

syntax

\n\n

unquote-splicing

\n\nSee quasiquote, where unquote-splicing is recognized as an escape. An unquote-splicing form as an expression is a syntax error.\n\n------------------------------------------------------------------------\n\n# 3.21 Syntax Quoting: quote-syntax\n\n### 3.21 Syntax Quoting: quote-syntax\n\n>
\n\n

syntax

\n\n

(quote-syntax datum)

(quote-syntax datum #:local)
\n\nSimilar to quote, but produces a syntax object that preserves the lexical information and source-location information attached to datum at expansion time.\n\nWhen #:local is specified, then all scopes in the syntax object’s lexical information are preserved. When #:local is omitted, then the scope sets within datum are pruned to omit the scope for any binding form that appears between the quote-syntax form and the enclosing top-level context, module body, or phase level crossing, whichever is closer.\n\nUnlike syntax (#'), quote-syntax does not substitute pattern variables bound by with-syntax, syntax-parse, or syntax-case.\n\nExamples:\n\n> ```racket\n> > ( syntax? ( quote-syntax x ) )\n> #t\n> > ( quote-syntax ( 1 2 3 ) )\n> #\n> > ( with-syntax ( [ a #' 5 ] ) ( quote-syntax ( a b c ) ) )\n> #\n> > ( free-identifier=? ( let ( [ x 1 ] ) ( quote-syntax x ) ) ( quote-syntax x ) )\n> #t\n> > ( free-identifier=? ( let ( [ x 1 ] ) ( quote-syntax x #:local ) ) ( quote-syntax x ) )\n> #f\n> ```\n\nChanged in version 6.3 of package base: Added scope pruning and support for #:local.\n\n------------------------------------------------------------------------\n\n# 3.22 Interaction Wrapper: #%top-interaction\n\n### 3.22 Interaction Wrapper: #%top-interaction\n\n>
\n\n

syntax

\n\n

(#%top-interaction . form)

\n\nExpands to simply form. The #%top-interaction form is similar to #%app and #%module-begin, in that it provides a hook to control interactive evaluation through load (more precisely, the default load handler) or read-eval-print-loop.\n\n------------------------------------------------------------------------\n\n# 3.23 Blocks: block\n\n### 3.23 Blocks: block\n\n| | |\n|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/block]()) |  package: base |\n\nThe bindings documented in this section are provided by the [racket/block]() library, not racket/base or racket.\n\n>
\n\n

syntax

\n\n

(block defn-or-expr ...)

\n\nSupports a mixture of expressions and mutually recursive definitions, as in a module body. Unlike an internal-definition context, the last defn-or-expr need not be an expression.\n\nThe result of the block form is the result of the last defn-or-expr if it is an expression, # otherwise. If no defn-or-expr is provided (after flattening begin forms), the result is #.\n\nThe final defn-or-expr is executed in tail position, if it is an expression.\n\nExamples:\n\n> ```racket\n> > ( define ( f x ) ( block ( define y ( add1 x ) ) ( displayln y ) ( define z ( * 2 y ) ) ( + 3 z ) ) )\n> > ( f 12 )\n> 13\n> 29\n> ```\n\n------------------------------------------------------------------------\n\n# 3.24 Internal-Definition Limiting: #%stratified-body\n\n### 3.24 Internal-Definition Limiting: #%stratified-body\n\n>
\n\n

syntax

\n\n

(#%stratified-body defn-or-expr ...)

\n\nLike (let () defn-or-expr ...) for an internal-definition context sequence, except that an expression is not allowed to precede a definition, and all definitions are treated as referring to all other definitions (i.e., locations for variables are all allocated first, like letrec and unlike letrec-syntaxes+values).\n\nThe #%stratified-body form is useful for implementing syntactic forms or languages that supply a more limited kind of internal-definition context.\n\n------------------------------------------------------------------------\n\n# 3.25 Performance Hints: begin-encourage-inline\n\n### 3.25 Performance Hints: begin-encourage-inline\n\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/performance-hint]()) |  package: base |\n\nThe bindings documented in this section are provided by the [racket/performance-hint]() library, not racket/base or racket.\n\n>
\n\n

syntax

\n\n

(begin-encourage-inline form ...)

\n\nAttaches a 'compiler-hint:cross-module-inline syntax property to each form, which is useful when a form is a function definition. See define-values.\n\nThe begin-encourage-inline form is also provided by the (submod racket/performance-hint begin-encourage-inline) module, which has fewer dependencies than [racket/performance-hint]().\n\nChanged in version 6.2 of package base: Added the (submod racket/performance-hint begin-encourage-inline) submodule.\n\n>
\n\n

syntax

\n\n

(define-inline id expr)

(define-inline (head args) body ...+)
 
head = id
  | (head args)
     
args = arg ...
  | arg ... . rest-id
     
arg = arg-id
  | [arg-id default-expr]
  | keyword arg-id
  | keyword [arg-id default-expr]
\n\nLike define, but ensures that the definition will be inlined at its call sites. Recursive calls are not inlined, to avoid infinite inlining. Higher-order uses are supported, but also not inlined. Misapplication (by supplying the wrong number of arguments or incorrect keyword arguments) is also not inlined and left as a run-time error.\n\nThe define-inline form may interfere with the Racket compiler’s own inlining heuristics, and should only be used when other inlining attempts (such as begin-encourage-inline) fail.\n\nChanged in version 8.1.0.5 of package base: Changed to treat misapplication as a run-time error.\n\n------------------------------------------------------------------------\n\n# 3.26 Importing Modules Lazily: lazy-require\n\n### 3.26 Importing Modules Lazily: lazy-require\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/lazy-require]()) |  package: base |\n\nThe bindings documented in this section are provided by the [racket/lazy-require]() library, not racket/base or racket.\n\n>
\n\n

syntax

\n\n

(lazy-require [module-path (fun-import ...)] ...)

 
fun-import = fun-id
  | (orig-fun-id fun-id)
\n\nDefines each fun-id as a function that, when called, dynamically requires the export named orig-fun-id from the module specified by module-path and calls it with the same arguments. If orig-fun-id is not given, it defaults to fun-id.\n\nIf the enclosing relative phase level is not 0, then module-path is also placed in a submodule (with a use of define-runtime-module-path-index at phase level 0 within the submodule). Introduced submodules have the names lazy-require-auxn-m, where n is a phase-level number and m is a number.\n\nWhen the use of a lazily-required function triggers module loading, it also triggers a use of register-external-module to declare an indirect compilation dependency (in case the function is used in the process of compiling a module).\n\nExamples:\n\n> ```racket\n> > ( lazy-require [ racket/list ( partition ) ] )\n> > ( partition even? ' ( 1 2 3 4 5 ) )\n> '(2 4) '(1 3 5)\n> > ( module hello racket/base ( provide hello ) ( printf \"starting hello server\\n\" ) ( define ( hello ) ( printf \"hello!\\n\" ) ) )\n> > ( lazy-require [ ' hello ( [ hello greet ] ) ] )\n> > ( greet )\n> starting hello server hello!\n> ```\n\n>
\n\n

syntax

\n\n

(lazy-require-syntax [module-path (macro-import ...)] ...)

 
macro-import = macro-id
  | (orig-macro-id macro-id)
\n\nLike lazy-require but for macros. That is, it defines each macro-id as a macro that, when used, dynamically loads the macro’s implementation from the given module-path. If orig-macro-id is not given, it defaults to macro-id.\n\nUse lazy-require-syntax in the implementation of a library with large, complicated macros to avoid a dependence from clients of the library on the macro “compilers.” Note that only macros with exceptionally large compile-time components (such as Typed Racket, which includes a type checker and optimizer) benefit from lazy-require-syntax; typical macros do not.\n\nWarning: lazy-require-syntax breaks the invariants that Racket’s module loader and linker rely on; these invariants normally ensure that the references in code produced by a macro are loaded before the code runs. Safe use of lazy-require-syntax requires a particular structure in the macro implementation. (In particular, lazy-require-syntax cannot simply be introduced in the client code.) The macro implementation must follow these rules:\n\n1. the interface module must require the runtime-support module\n\n2. the compiler module must require the runtime-support module via an absolute module path rather than a relative path\n\nTo explain the concepts of “interface, compiler, and runtime-support modules”, here is an example module that exports a macro:\n\n> ```racket\n> ( module original racket/base\n> ( define ( ntimes-proc n thunk )\n> ( for ( [ i ( in-range n ) ] ) ( thunk ) ) )\n> ( define-syntax-rule ( ntimes n expr )\n> ( ntimes-proc n ( lambda ( ) expr ) ) )\n> ( provide ntimes ) )\n> ```\n\nSuppose we want to use lazy-require-syntax to lazily load the implementation of the ntimes macro transformer. The original module must be split into three parts:\n\n> ```racket\n> ( module runtime-support racket/base\n> ( define ( ntimes-proc n thunk )\n> ( for ( [ i ( in-range n ) ] ) ( thunk ) ) )\n> ( provide ntimes-proc ) )\n> ( module compiler racket/base\n> ( require ' runtime-support )\n> ( define-syntax-rule ( ntimes n expr )\n> ( ntimes-proc n ( lambda ( ) expr ) ) )\n> ( provide ntimes ) )\n> ( module interface racket/base\n> ( require racket/lazy-require )\n> ( require ' runtime-support )\n> ( lazy-require-syntax [ ' compiler ( ntimes ) ] )\n> ( provide ntimes ) )\n> ```\n\nThe runtime support module contains the function and value definitions that the macro refers to. The compiler module contains the macro definition(s) themselves—the part of the code that “disappears” after compile time. The interface module lazily loads the macro transformer, but it makes sure the runtime support module is defined at run time by requiring it normally. In a larger example, of course, the runtime support and compiler may both consist of multiple modules.\n\nHere what happens when we don’t separate the runtime support into a separate module:\n\n> ```racket\n> > ( module bad-no-runtime racket/base ( define ( ntimes-proc n thunk ) ( for ( [ i ( in-range n ) ] ) ( thunk ) ) ) ( define-syntax-rule ( ntimes n expr ) ( ntimes-proc n ( lambda ( ) expr ) ) ) ( provide ntimes ) )\n> > ( module bad-client racket/base ( require racket/lazy-require ) ( lazy-require-syntax [ ' bad-no-runtime ( ntimes ) ] ) ( ntimes 3 ( printf \"hello?\\n\" ) ) )\n> > ( require ' bad-client )\n> require: namespace mismatch;\n> reference to a module that is not instantiated\n> module: 'bad-no-runtime\n> phase: 0\n> ```\n\nA similar error occurs when the interface module doesn’t introduce a dependency on the runtime support module.\n\n------------------------------------------------------------------------\n\n# 4 Datatypes\n\n## 4 Datatypes\n\n> > > \"+\"Built-In Datatypes in The Racket Guide introduces Datatypes.\n\nEach pre-defined datatype comes with a set of procedures for manipulating instances of the datatype.\n\n| |\n|-------------------------------------------------------------------------------------|\n|     4.1 Equality |\n|     4.2 Booleans |\n|     4.3 Numbers |\n|     4.4 Strings |\n|     4.5 Byte Strings |\n|     4.6 Characters |\n|     4.7 Symbols |\n|     4.8 Regular Expressions |\n|     4.9 Keywords |\n|     4.10 Pairs and Lists |\n|     4.11 Mutable Pairs and Lists |\n|     4.12 Vectors |\n|     4.13 Stencil Vectors |\n|     4.14 Boxes |\n|     4.15 Hash Tables |\n|     4.16 Treelists |\n|     4.17 Sequences and Streams |\n|     4.18 Dictionaries |\n|     4.19 Sets |\n|     4.20 Procedures |\n|     4.21 Void |\n|     4.22 Undefined |\n\n------------------------------------------------------------------------\n\n# 4.1 Equality\n\n8.18.0.13\n\n### 4.1 Equality\n\nEquality is the concept of whether two values are “the same.” Racket supports a few different kinds of equality by default, although equal? is preferred for most uses.\n\n> ```\n(equal? v1 v2) → boolean?\n  v1 : any/c\n  v2 : any/c```\n\n\nTwo values are [equal?](#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) if and only if they are [eqv?](#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), unless otherwise specified for a particular datatype.\n\nDatatypes with further specification of [equal?](#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) include strings, byte strings, pairs, mutable pairs, vectors, boxes, hash tables, and inspectable structures. In the last six cases, equality is recursively defined; if both v1 and v2 contain reference cycles, they are equal when the infinite unfoldings of the values would be equal. See also [gen:equal+hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._gen~3aequal%2Bhash%29%29) and [prop:impersonator-of](chaperones.html#%28def._%28%28quote._~23~25kernel%29._prop~3aimpersonator-of%29%29).\n\nExamples:\n\n> ```racket\n> > ( equal? ' yes ' yes )\n> #t\n> > ( equal? ' yes ' no )\n> #f\n> > ( equal? ( * 6 7 ) 42 )\n> #t\n> > ( equal? ( expt 2 100 ) ( expt 2 100 ) )\n> #t\n> > ( equal? 2 2.0 )\n> #f\n> > ( let ( [ v ( mcons 1 2 ) ] ) ( equal? v v ) )\n> #t\n> > ( equal? ( mcons 1 2 ) ( mcons 1 2 ) )\n> #t\n> > ( equal? ( integer->char 955 ) ( integer->char 955 ) )\n> #t\n> > ( equal? ( make-string 3 #\\z ) ( make-string 3 #\\z ) )\n> #t\n> > ( equal? #t #t )\n> #t\n> ```\n\n> ```\n(equal-always? v1 v2)  →  boolean?\n  v1 : any/c\n  v2 : any/c\n```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nIndicates whether v1 and v2 are equal and will always stay equal independent of mutations. Generally, for two values to be equal-always, corresponding immutable values within v1 and v2 must be equal?, while corresponding mutable values within them must be eq?. Precedents for this operator in other languages include egal \\[Baker93\\].\nTwo values v1 and v2 are equal-always? if and only if there exists a third value v3 such that v1 and v2 are both chaperones of v3, meaning (chaperone-of? v1 v3) and (chaperone-of? v2 v3) are both true.\nFor values that include no chaperones or other impersonators, v1 and v2 can be considered equal-always if they are equal?, except that corresponding mutable vectors, boxes, hash tables, strings, byte strings, mutable pairs, and mutable structures within v1 and v2 must be eq?, and equality on structures can be specialized for equal-always? through gen:equal-mode+hash.\nExamples:"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n> ```racket\n> > ( equal-always? ' yes ' yes )\n> #t\n> > ( equal-always? ' yes ' no )\n> #f\n> > ( equal-always? ( * 6 7 ) 42 )\n> #t\n> > ( equal-always? ( expt 2 100 ) ( expt 2 100 ) )\n> #t\n> > ( equal-always? 2 2.0 )\n> #f\n> > ( equal-always? ( list 1 2 ) ( list 1 2 ) )\n> #t\n> > ( let ( [ v ( mcons 1 2 ) ] ) ( equal-always? v v ) )\n> #t\n> > ( equal-always? ( mcons 1 2 ) ( mcons 1 2 ) )\n> #f\n> > ( equal-always? ( integer → char 955 ) ( integer → char 955 ) )\n> #t\n> > ( equal-always? ( make-string 3 #\\z ) ( make-string 3 #\\z ) )\n> #f\n> > ( equal-always? ( string → immutable-string ( make-string 3 #\\z ) ) ( string → immutable-string ( make-string 3 #\\z ) ) )\n> #t\n> > ( equal-always? #t #t )\n> #t\n> ```\nAdded in version 8.5.0.3 of package base.\n> ```\n(eqv? v1 v2) → boolean?\n  v1 : any/c\n  v2 : any/c```\nTwo values are [eqv?](#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29) if and only if they are [eq?](#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29), unless otherwise specified for a particular datatype."} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nThe [number](numbers.html#%28tech._number%29) and [character](characters.html#%28tech._character%29) datatypes are the only ones for which [eqv?](#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29) differs from [eq?](#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29). Two numbers are [eqv?](#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29) when they have the same exactness, precision, and are both equal and non-zero, both +0.0, both +0.0f0, both -0.0, both -0.0f0, both +nan.0, or both +nan.f—considering real and imaginary components separately in the case of [complex numbers](numbers.html#%28tech._complex._number%29). Two characters are [eqv?](#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29) when their [char->integer](characters.html#%28def._%28%28quote._~23~25kernel%29._char-~3einteger%29%29) results are equal.\nGenerally, [eqv?](#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29) is identical to [equal?](#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) except that the former cannot recursively compare the contents of compound data types (such as lists and structs) and cannot be customized by user-defined data types. The use of [eqv?](#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29) is lightly discouraged in favor of [equal?](#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29).\nExamples:"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n> ```racket\n> > ( eqv? ' yes ' yes )\n> #t\n> > ( eqv? ' yes ' no )\n> #f\n> > ( eqv? ( * 6 7 ) 42 )\n> #t\n> > ( eqv? ( expt 2 100 ) ( expt 2 100 ) )\n> #t\n> > ( eqv? 2 2.0 )\n> #f\n> > ( let ( [ v ( mcons 1 2 ) ] ) ( eqv? v v ) )\n> #t\n> > ( eqv? ( mcons 1 2 ) ( mcons 1 2 ) )\n> #f\n> > ( eqv? ( integer->char 955 ) ( integer->char 955 ) )\n> #t\n> > ( eqv? ( make-string 3 #\\z ) ( make-string 3 #\\z ) )\n> #f\n> > ( eqv? #t #t )\n> #t\n> ```\n> ```\n(eq? v1 v2)  →  boolean?\n  v1 : any/c\n  v2 : any/c"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n```\nReturn #t if v1 and v2 refer to the same object, #f otherwise. As a special case among numbers, two fixnums that are = are also the same according to eq?. See also Object Identity and Comparisons.\n\nExamples:\n\n> ```racket\n> > ( eq? ' yes ' yes )\n> #t\n> > ( eq? ' yes ' no )\n> #f\n> > ( eq? ( * 6 7 ) 42 )\n> #t\n> > ( eq? ( expt 2 100 ) ( expt 2 100 ) )\n> #f\n> > ( eq? 2 2.0 )\n> #f\n> > ( let ( [ v ( mcons 1 2 ) ] ) ( eq? v v ) )\n> #t\n> > ( eq? ( mcons 1 2 ) ( mcons 1 2 ) )\n> #f\n> > ( eq? ( integer → char 955 ) ( integer → char 955 ) )\n> #t\n> > ( eq? ( make-string 3 #\\z ) ( make-string 3 #\\z ) )\n> #f\n> > ( eq? #t #t )\n> #t\n> ```\n\n> ```\n(equal?/recur v1 v2 recur-proc) → boolean?\n  v1 : any/c\n  v2 : any/c\n  recur-proc : (any/c any/c . → . any/c)```\n\n\nLike [equal?](#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), but using recur-proc for recursive comparisons (which means that reference cycles are not handled automatically). Non-#f results from recur-proc are converted to #t before being returned by [equal?/recur](#%28def._%28%28quote._~23~25kernel%29._equal~3f%2Frecur%29%29).\n\nExamples:\n\n> ```racket\n> > ( equal?/recur 1 1 ( lambda ( a b ) #f ) )\n> #t\n> > ( equal?/recur ' ( 1 ) ' ( 1 ) ( lambda ( a b ) #f ) )\n> #f\n> > ( equal?/recur ' # ( 1 1 1 ) ' # ( 1 1.2 3/4 ) ( lambda ( a b ) ( <= ( abs ( - a b ) ) 0.25 ) ) )> #t\n> ```\n\n> ```\n(equal-always?/recur v1 v2 recur-proc)  →  boolean?\n  v1 : any/c\n  v2 : any/c\n  recur-proc : (any/c any/c . → . any/c)\n```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nLike equal-always?, but using recur-proc for recursive comparisons (which means that reference cycles are not handled automatically). Non-#f results from recur-proc are converted to #t before being returned by equal-always?/recur.\nExamples:\n> ```racket\n> > ( equal-always?/recur 1 1 ( lambda ( a b ) #f ) )\n> #t\n> > ( equal-always?/recur ' ( 1 ) ' ( 1 ) ( lambda ( a b ) #f ) )\n> #f\n> > ( equal-always?/recur ( vector-immutable 1 1 1 ) ( vector-immutable 1 1.2 3/4 ) ( lambda ( a b ) ( <= ( abs ( - a b ) ) 0.25 ) ) )> #t\n> ```"} {"text": "#### 4.1.1 Object Identity and Comparisons\nThe eq? operator compares two values, returning #t when the values refer to the same object. This form of equality is suitable for comparing objects that support imperative update (e.g., to determine that the effect of modifying an object through one reference is visible through another reference). Also, an eq? test evaluates quickly, and eq?-based hashing is more lightweight than equal?-based hashing in hash tables.\nIn some cases, however, eq? is unsuitable as a comparison operator, because the generation of objects is not clearly defined. In particular, two applications of + to the same two exact integers may or may not produce results that are eq?, although the results are always equal?. Similarly, evaluation of a lambda form typically generates a new procedure object, but it may re-use a procedure object previously generated by the same source lambda form.\nThe behavior of a datatype with respect to eq? is generally specified with the datatype and its associated procedures."} {"text": "#### 4.1.2 Equality and Hashing\nAll comparable values have at least one hash code — an arbitrary integer (more specifically a fixnum) computed by applying a hash function to the value. The defining property of these hash codes is that equal values have equal hash codes. Note that the reverse is not true: two unequal values can still have equal hash codes. Hash codes are useful for various indexing and comparison operations, especially in the implementation of hash tables. See Hash Tables for more information.\n> ```\n(equal-hash-code v) → fixnum?\n  v : any/c```\nReturns a [hash code](#%28tech._hash._code%29) consistent with [equal?](#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29). For any two calls with [equal?](#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) values, the returned number is the same. A hash code is computed even when v contains a cycle through pairs, vectors, boxes, and/or inspectable structure fields. Additionally, user-defined data types can customize how this hash code is computed by implementing [gen:equal+hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._gen~3aequal%2Bhash%29%29) or [gen:equal-mode+hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._gen~3aequal-mode%2Bhash%29%29)."} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nFor any v that could be produced by [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29), if v2 is produced by [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) for the same input characters, the ([equal-hash-code](#%28def._%28%28quote._~23~25kernel%29._equal-hash-code%29%29) v) is the same as ([equal-hash-code](#%28def._%28%28quote._~23~25kernel%29._equal-hash-code%29%29) v2) — even if v and v2 do not exist at the same time (and therefore could not be compared by calling [equal?](#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29)).\nChanged in version 6.4.0.12 of package base: Strengthened guarantee for [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29)able values.\n> ```\n(equal-hash-code/recur v recur-proc)  →  fixnum?\n  v : any/c\n  recur-proc : ( →  any/c exact-integer?)"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n```\nLike equal-hash-code, but using recur-proc for recursive hashing within v.\n\nExamples:\n\n> ```racket\n> > ( define ( rational-hash x ) ( cond [ ( rational? x ) ( equal-hash-code ( inexact → exact x ) ) ] [ else ( equal-hash-code/recur x rational-hash ) ] ) )\n> > ( = ( rational-hash 0.0 ) ( rational-hash -0 .0 ) )\n> #t\n> > ( = ( rational-hash 1.0 ) ( rational-hash -1 .0 ) )\n> #f\n> > ( = ( rational-hash ( list ( list ( list 4.0 0.0 ) 9.0 ) 6.0 ) ) ( rational-hash ( list ( list ( list 4 0 ) 9 ) 6 ) ) )\n> #t\n> ```\n\nAdded in version 8.8.0.9 of package base.\n\n> ```\n(equal-secondary-hash-code v) → fixnum?\n  v : any/c```\n\n\nLike [equal-hash-code](#%28def._%28%28quote._~23~25kernel%29._equal-hash-code%29%29), but computes a secondary [hash code](#%28tech._hash._code%29) suitable for use in double hashing.\n\n> ```\n(equal-always-hash-code v)  →  fixnum?\n  v : any/c\n```\nReturns a hash code consistent with equal-always?. For any two calls with equal-always? values, the returned number is the same.\nAs equal-always-hash-code traverses v, immutable values within v are hashed with equal-hash-code, while mutable values within v are hashed with eq-hash-code.\n> ```\n(equal-always-hash-code/recur v recur-proc)  →  fixnum?\n  v : any/c\n  recur-proc : ( →  any/c exact-integer?)```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nLike [equal-always-hash-code](#%28def._%28%28quote._~23~25kernel%29._equal-always-hash-code%29%29), but using recur-proc for recursive hashing within v.\nAdded in version 8.8.0.9 of package base.\n> ```\n(equal-always-secondary-hash-code v)  →  fixnum?\n  v : any/c\n```\nLike equal-always-hash-code, but computes a secondary hash code suitable for use in double hashing.\n\n> ```\n(eq-hash-code v)  →  fixnum?\n  v : any/c```\n\n\nReturns a [hash code](#%28tech._hash._code%29) consistent with [eq?](#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29). For any two calls with [eq?](#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) values, the returned number is the same.\n\n> > > Equal [fixnums](numbers.html#%28tech._fixnum%29) are always [eq?](#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29).\n\n> ```\n(eqv-hash-code v)  →  fixnum?\n  v : any/c\n```\nReturns a hash code consistent with eqv?. For any two calls with eqv? values, the returned number is the same."} {"text": "#### 4.1.3 Implementing Equality for Custom Types\n>
\n

value

\n

gen:equal+hash : any/c

\nA generic interface (see Generic Interfaces) for types that can be compared for equality using equal?. The following methods must be implemented:\n- equal-proc : ( → any/c any/c ( → any/c any/c boolean?) any/c) — tests whether the first two arguments are equal, where both values are instances of the structure type to which the generic interface is associated (or a subtype of the structure type).\nThe third argument is an equal? predicate to use for recursive equality checks; use the given predicate instead of equal? to ensure that data cycles are handled properly and to work with equal?/recur (but beware that an arbitrary function can be provided to equal?/recur for recursive checks, which means that arguments provided to the predicate might be exposed to arbitrary code).\nThe equal-proc is called for a pair of structures only when they are not eq?, and only when they both have a gen:equal+hash value inherited from the same structure type. With this strategy, the order in which equal? receives two structures does not matter. It also means that, by default, a structure sub-type inherits the equality predicate of its parent, if any."} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n- hash-proc : ( → any/c ( → any/c exact-integer?) exact-integer?) — computes a hash code for the given structure, like equal-hash-code. The first argument is an instance of the structure type (or one of its subtypes) to which the generic interface is associated.\nThe second argument is an equal-hash-code-like procedure to use for recursive hash-code computation; use the given procedure instead of equal-hash-code to ensure that data cycles are handled properly.\nAlthough the result of hash-proc can be any exact integer, it will be truncated for most purposes to a fixnum (e.g., for the result of equal-hash-code). Roughly, truncation uses bitwise-and to take the lower bits of the number. Thus, variation in the hash-code computation should be reflected in the fixnum-compatible bits of hash-proc’s result. Consumers of a hash code are expected to use variation within the fixnum range appropriately, and producers are not responsible to reflect variation in hash codes across the full range of bits that fit within a fixnum.\n- hash2-proc : ( → any/c ( → any/c exact-integer?) exact-integer?) — computes a secondary hash code for the given structure. This procedure is like hash-proc, but analogous to equal-secondary-hash-code."} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nTake care to ensure that hash-proc and hash2-proc are consistent with equal-proc. Specifically, hash-proc and hash2-proc should produce the same value for any two structures for which equal-proc produces a true value.\nThe equal-proc is not only used for equal?, it is also used for equal?/recur, and impersonator-of?. Furthermore, if the structure type has no mutable fields, equal-proc is used for equal-always?, and chaperone-of?. Likewise hash-proc and hash2-proc are used for equal-always-hash-code and equal-always-secondary-hash-code, respectively, when the structure type has no mutable fields. Instances of these methods should follow the guidelines in Honest Custom Equality to implement all of these operations reasonably. In particular, these methods should not access mutable data unless the struct is declared mutable."} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nWhen a structure type has no gen:equal+hash or gen:equal-mode+hash implementation, then transparent structures (i.e., structures with an inspector that is controlled by the current inspector) are equal? when they are instances of the same structure type (not counting sub-types), and when they have equal? field values. For transparent structures, equal-hash-code and equal-secondary-hash-code (in the case of no mutable fields) derive hash code using the field values. For a transparent structure type with at least one mutable field, equal-always? is the same as eq?, and an equal-secondary-hash-code result is based only on eq-hash-code. For opaque structure types, equal? is the same as eq?, and equal-hash-code and equal-secondary-hash-code results are based only on eq-hash-code. If a structure has a prop:impersonator-of property, then the prop:impersonator-of property takes precedence over gen:equal+hash if the property value’s procedure returns a non-#f value when applied to the structure.\nExamples:"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n> ```racket\n> ( define ( farm=? farm1 farm2 recursive-equal? ) ( and ( = ( farm-apples farm1 ) ( farm-apples farm2 ) ) ( = ( farm-oranges farm1 ) ( farm-oranges farm2 ) ) ( = ( farm-sheep farm1 ) ( farm-sheep farm2 ) ) ) ) ( define ( farm-hash-code farm recursive-equal-hash ) ( + ( * 10000 ( farm-apples farm ) ) ( * 100 ( farm-oranges farm ) ) ( * 1 ( farm-sheep farm ) ) ) ) ( define ( farm-secondary-hash-code farm recursive-equal-hash ) ( + ( * 10000 ( farm-sheep farm ) ) ( * 100 ( farm-apples farm ) ) ( * 1 ( farm-oranges farm ) ) ) ) ( struct farm ( apples oranges sheep ) #:methods gen:equal+hash [ ( define equal-proc farm=? ) ( define hash-proc farm-hash-code ) ( define hash2-proc farm-secondary-hash-code ) ] ) ( define eastern-farm ( farm 5 2 20 ) ) ( define western-farm ( farm 18 6 14 ) ) ( define northern-farm ( farm 5 20 20 ) ) ( define southern-farm ( farm 18 6 14 ) )\n> > ( equal? eastern-farm western-farm )\n> #f\n> > ( equal? eastern-farm northern-farm )\n> #f\n> > ( equal? western-farm southern-farm )\n> #t\n> ```\nChanged in version 8.7.0.5 of package base: Added a check so that omitting any of equal-proc, hash-proc, and hash2-proc is now a syntax error.\n>
\n

value

\n

gen:equal-mode+hash : any/c

"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nA generic interface (see Generic Interfaces) for types that may specify differences between equal? and equal-always?. The following methods must be implemented:\n- equal-mode-proc : ( → any/c any/c ( → any/c any/c boolean?) boolean? any/c) — the first two arguments are the values to compare, the third argument is an equality function to use for recursive comparisons, and the last argument is the mode: #t for an equal? or impersonator-of? comparison or #f for an equal-always? or chaperone-of? comparison.\n- hash-mode-proc : ( → any/c ( → any/c exact-integer?) boolean? exact-integer?) — the first argument is the value to compute a hash code for, the second argument is a hashing function to use for recursive hashing, and the last argument is the mode: #t for equal? hashing or #f for equal-always? hashing.\nThe hash-mode-proc implementation is used both for a primary hash code and secondary hash code.\nWhen implementing these methods, follow the guidelines in Honest Custom Equality. In particular, these methods should only access mutable data if the “mode” argument is true to indicate equal? or impersonator-of?.\nImplementing gen:equal-mode+hash is most useful for types that specify differences between equal? and equal-always?, such as a structure type that wraps mutable data with getter and setter procedures:\nExamples:"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n> ```racket\n> > ( define ( get gs ) ( ( getset-getter gs ) ) )\n> > ( define ( set gs new ) ( ( getset-setter gs ) new ) )\n> > ( struct getset ( getter setter ) #:methods gen:equal-mode+hash [ ( define ( equal-mode-proc self other rec mode ) ( and mode ( rec ( get self ) ( get other ) ) ) ) ( define ( hash-mode-proc self rec mode ) ( if mode ( rec ( get self ) ) ( eq-hash-code self ) ) ) ] )\n> > ( define x 1 )\n> > ( define y 2 )\n> > ( define gsx ( getset ( lambda ( ) x ) ( lambda ( new ) ( set! x new ) ) ) )\n> > ( define gsy ( getset ( lambda ( ) y ) ( lambda ( new ) ( set! y new ) ) ) )\n> > ( equal? gsx gsy )\n> #f\n> > ( equal-always? gsx gsy )\n> #f\n> > ( set gsx 3 )\n> > ( set gsy 3 )\n> > ( equal? gsx gsy )\n> #t\n> > ( equal-always? gsx gsy )\n> #f\n> > ( equal-always? gsx gsx )\n> #t\n> ```\nAdded in version 8.5.0.3 of package base. \nChanged in version 8.7.0.5: Added a check so that omitting either equal-mode-proc or hash-mode-proc is now a syntax error.\n>
\n

value

\n

prop:equal+hash : struct-type-property?

"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nA structure type property (see Structure Type Properties) that supplies an equality predicate and hashing functions for a structure type. Using the prop:equal+hash property is an alternative to using the gen:equal+hash or gen:equal-mode+hash generic interface.\nA prop:equal+hash property value is a list of either three procedures (list equal-proc hash-proc hash2-proc) or two procedures (list equal-mode-proc hash-mode-proc):\n- The three-procedure case corresponds to the procedures of gen:equal-hash:\n- equal-proc : ( → any/c any/c ( → any/c any/c boolean?) any/c)\n- hash-proc : ( → any/c ( → any/c exact-integer?) exact-integer?)\n- hash2-proc : ( → any/c ( → any/c exact-integer?) exact-integer?)\n- The two-procedure case corresponds to the procedures of gen:equal-mode-hash:\n- equal-mode-proc : ( → any/c any/c ( → any/c any/c boolean?) boolean? any/c)\n- hash-mode-proc : ( → any/c ( → any/c exact-integer?) boolean? exact-integer?)\nWhen implementing these methods, follow the guidelines in Honest Custom Equality. In particular, these methods should only access mutable data if the struct is declared mutable or the mode is true.\nChanged in version 8.5.0.3 of package base: Added support for two-procedure values to customize equal-always?."} {"text": "#### 4.1.4 Honest Custom Equality\nSince the equal-proc or equal-mode-proc is used for more than just equal?, instances of them should follow certain guidelines to make sure that they work correctly for equal-always?, chaperone-of?, and impersonator-of?.\nDue to the differences between these operations, avoid calling equal? within them. Instead, use the third argument to “recur” on the pieces, which allows equal?/recur to work properly, lets the other operations behave in their own distinct ways on the pieces, and enables some cycle detection.\n

good

( define ( equal-proc self other rec )\n(rec (fish-size self) (fish-size other)))

bad

(define (equal-proc self other rec)\n( equal? ( fish-size self ) ( fish-size other ) ) )
"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nDon’t use the third argument to “recur” on counts of elements. When a data structure cares about discrete numbers, it can use = on those, not equal? or “recur”. Using “recur” on counts is bad when a “recur” argument from equal?/recur is too tolerant on numbers within some range of each other.```\ngood( define ( equal-proc self other rec )\n(and (= (tuple-length self) (tuple-length other))\n( for/and ( [ i ( in-range ( tuple-length self ) ) ] )\n( rec ( ( tuple-getter self ) i )\n( ( tuple-getter other ) i ) ) ) ) ) bad( define ( equal-proc self other rec )\n( and ( rec ( tuple-length self ) ( tuple-length other ) )\n( for/and ( [ i ( in-range ( tuple-length self ) ) ] )\n( rec ( ( tuple-getter self ) i )\n( ( tuple-getter other ) i ) ) ) ) )\n```\n\n\nThe operations [equal?](#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) and [equal-always?](#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29) should be symmetric, so equal-proc instances should not change their answer when the arguments swap:\n\n```\ngood( define ( equal-proc self other rec )\n(rec (fish-size self) (fish-size other))) bad(define (equal-proc self other rec)\n( <= ( fish-size self ) ( fish-size other ) ) )"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n```\nHowever, the operations chaperone-of? and impersonator-of? are not symmetric, so when calling the third argument to “recur” on pieces, pass the pieces in the same order they came in:\n\n

good

( define ( equal-proc self other rec )\n(rec (fish-size self) (fish-size other)))

bad

(define (equal-proc self other rec)\n( rec ( fish-size other ) ( fish-size self ) ) )
\n\nThe operations equal-always? and chaperone-of? shouldn’t change on mutation, so equal-proc instances should not access potentially-mutable data. This includes avoiding string=?, since strings can be mutable. Type-specific equality functions for immutable types, such as symbol=?, are fine.```\nfine( define ( equal-proc self other rec )\n; symbols are immutable: no problem\n(symbol=? (thing-name self) (thing-name other))) bad(define (equal-proc self other rec)\n; strings can be mutable: accesses mutable data\n( string=? ( thing-name self ) ( thing-name other ) ) )\n```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nDeclaring a struct as mutable makes [equal-always?](#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29) and [chaperone-of?](chaperones.html#%28def._%28%28quote._~23~25kernel%29._chaperone-of~3f%29%29) avoid using equal-proc, so equal-proc instances are free to access mutable data if the struct is declared mutable:\n```\ngood( struct mcell ( value ) #:mutable\n#:methods gen:equal+hash\n[ ( define ( equal-proc self other rec )\n(rec (mcell-value self)\n( mcell-value other ) ) )\n( define ( hash-proc self rec )\n( + ( eq-hash-code struct:mcell )\n( rec ( mcell-value self ) ) ) )\n( define ( hash2-proc self rec )\n( + ( eq-hash-code struct:mcell )\n( rec ( mcell-value self ) ) ) ) ] ) bad( struct mcell ( box )\n; not declared mutable,\n; but represents mutable data anyway\n#:methods gen:equal+hash\n[ ( define ( equal-proc self other rec )\n( rec ( unbox ( mcell-box self ) )\n( unbox ( mcell-box other ) ) ) )\n( define ( hash-proc self rec )\n( + ( eq-hash-code struct:mcell )\n( rec ( unbox ( mcell-value self ) ) ) ) )\n( define ( hash2-proc self rec )\n( + ( eq-hash-code struct:mcell )\n( rec ( unbox ( mcell-value self ) ) ) ) ) ] )\n```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nAnother way for a struct to control access to mutable data is by implementing [gen:equal-mode+hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._gen~3aequal-mode%2Bhash%29%29) instead of [gen:equal+hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._gen~3aequal%2Bhash%29%29). When the mode is true, equal-mode-proc instances are free to access mutable data, and when the mode is false, they shouldn’t:\n```\nalso good( struct mcell ( value ) #:mutable\n; only accesses mutable data when mode is true\n#:methods gen:equal-mode+hash\n[ ( define ( equal-mode-proc self other rec mode )\n(and mode\n( rec ( mcell-value self )\n( mcell-value other ) ) ) )\n( define ( hash-mode-proc self rec mode )\n( if mode\n( + ( eq-hash-code struct:mcell )\n( rec ( mcell-value self ) ) )\n( eq-hash-code self ) ) ) ] ) still bad( struct mcell ( value ) #:mutable\n; accesses mutable data ignoring mode\n#:methods gen:equal-mode+hash\n[ ( define ( equal-mode-proc self other rec mode )\n( rec ( mcell-value self )\n( mcell-value other ) ) )\n( define ( hash-mode-proc self rec mode )\n( + ( eq-hash-code struct:mcell )\n( rec ( mcell-value self ) ) ) ) ] )\n```"} {"text": "#### 4.1.5 Combining Hash Codes\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require racket/hash-code) |  package: base |\nThe bindings documented in this section are provided by the racket/hash-code library, not racket/base or racket.\nAdded in version 8.8.0.5 of package base.\n> ```\n(hash-code-combine hc ...) → fixnum?\n  hc : exact-integer?```\nCombines the hcs into a [hash code](#%28tech._hash._code%29) that depends on the order of the inputs. Useful for combining the hash codes of different fields in a structure.\nExamples:"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n> ```racket\n> > ( require racket/hash-code )\n> > ( struct ordered-triple ( fst snd thd ) #:methods gen:equal+hash [ ( define ( equal-proc self other rec ) ( and ( rec ( ordered-triple-fst self ) ( ordered-triple-fst other ) ) ( rec ( ordered-triple-snd self ) ( ordered-triple-snd other ) ) ( rec ( ordered-triple-thd self ) ( ordered-triple-thd other ) ) ) ) ( define ( hash-proc self rec ) ( hash-code-combine ( eq-hash-code struct:ordered-triple ) ( rec ( ordered-triple-fst self ) ) ( rec ( ordered-triple-snd self ) ) ( rec ( ordered-triple-thd self ) ) ) ) ( define ( hash2-proc self rec ) ( hash-code-combine ( eq-hash-code struct:ordered-triple ) ( rec ( ordered-triple-fst self ) ) ( rec ( ordered-triple-snd self ) ) ( rec ( ordered-triple-thd self ) ) ) ) ] )\n> > ( equal? ( ordered-triple ' A ' B ' C ) ( ordered-triple ' A ' B ' C ) )\n> #t\n> > ( = ( equal-hash-code ( ordered-triple ' A ' B ' C ) ) ( equal-hash-code ( ordered-triple ' A ' B ' C ) ) )\n> #t\n> > ( equal? ( ordered-triple ' A ' B ' C ) ( ordered-triple ' C ' B ' A ) )\n> #f\n> > ( = ( equal-hash-code ( ordered-triple ' A ' B ' C ) ) ( equal-hash-code ( ordered-triple ' C ' B ' A ) ) )\n> #f\n> > ( equal? ( ordered-triple ' A ' B ' C ) ( ordered-triple ' C ' A ' B ) )\n> #f\n> > ( = ( equal-hash-code ( ordered-triple ' A ' B ' C ) ) ( equal-hash-code ( ordered-triple ' C ' A ' B ) ) )\n> #f\n> ```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nWith one argument, ([hash-code-combine](#%28def._%28%28lib._racket%2Fhash-code..rkt%29._hash-code-combine%29%29) hc) mixes the hash code so that it isn’t just hc.\nExamples:\n> ```racket\n> > ( require racket/hash-code )\n> > ( struct wrap ( value ) #:methods gen:equal+hash [ ( define ( equal-proc self other rec ) ( rec ( wrap-value self ) ( wrap-value other ) ) ) ( define ( hash-proc self rec ) ; demonstrates `hash-code-combine` with only one argument ; but it's good to combine `(eq-hash-code struct:wrap)` too ( hash-code-combine ( rec ( wrap-value self ) ) ) ) ( define ( hash2-proc self rec ) ( hash-code-combine ( rec ( wrap-value self ) ) ) ) ] )\n> > ( equal? ( wrap ' A ) ( wrap ' A ) )\n> #t\n> > ( = ( equal-hash-code ( wrap ' A ) ) ( equal-hash-code ( wrap ' A ) ) )\n> #t\n> > ( equal? ( wrap ' A ) ' A )\n> #f\n> > ( = ( equal-hash-code ( wrap ' A ) ) ( equal-hash-code ' A ) )\n> #f\n> ```\n> ```\n(hash-code-combine-unordered hc ...) → fixnum?\n  hc : exact-integer?"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\n```\nCombines the hcs into a hash code that does not depend on the order of the inputs. Useful for combining the hash codes of elements of an unordered set.\n\nExamples:\n\n> ```racket\n> > ( require racket/hash-code )\n> > ( struct flip-triple ( left mid right ) #:methods gen:equal+hash [ ( define ( equal-proc self other rec ) ( and ( rec ( flip-triple-mid self ) ( flip-triple-mid other ) ) ( or ( and ( rec ( flip-triple-left self ) ( flip-triple-left other ) ) ( rec ( flip-triple-right self ) ( flip-triple-right other ) ) ) ( and ( rec ( flip-triple-left self ) ( flip-triple-right other ) ) ( rec ( flip-triple-right self ) ( flip-triple-left other ) ) ) ) ) ) ( define ( hash-proc self rec ) ( hash-code-combine ( eq-hash-code struct:flip-triple ) ( rec ( flip-triple-mid self ) ) ( hash-code-combine-unordered ( rec ( flip-triple-left self ) ) ( rec ( flip-triple-right self ) ) ) ) ) ( define ( hash2-proc self rec ) ( hash-code-combine ( eq-hash-code struct:flip-triple ) ( rec ( flip-triple-mid self ) ) ( hash-code-combine-unordered ( rec ( flip-triple-left self ) ) ( rec ( flip-triple-right self ) ) ) ) ) ] )\n> > ( equal? ( flip-triple ' A ' B ' C ) ( flip-triple ' A ' B ' C ) )\n> #t\n> > ( = ( equal-hash-code ( flip-triple ' A ' B ' C ) ) ( equal-hash-code ( flip-triple ' A ' B ' C ) ) )\n> #t\n> > ( equal? ( flip-triple ' A ' B ' C ) ( flip-triple ' C ' B ' A ) )\n> #t\n> > ( = ( equal-hash-code ( flip-triple ' A ' B ' C ) ) ( equal-hash-code ( flip-triple ' C ' B ' A ) ) )\n> #t\n> > ( equal? ( flip-triple ' A ' B ' C ) ( flip-triple ' C ' A ' B ) )\n> #f\n> > ( = ( equal-hash-code ( flip-triple ' A ' B ' C ) ) ( equal-hash-code ( flip-triple ' C ' A ' B ) ) )\n> #f\n> > ( struct rotate-triple ( rock paper scissors ) #:methods gen:equal+hash [ ( define ( equal-proc self other rec ) ( or ( and ( rec ( rotate-triple-rock self ) ( rotate-triple-rock other ) ) ( rec ( rotate-triple-paper self ) ( rotate-triple-paper other ) ) ( rec ( rotate-triple-scissors self ) ( rotate-triple-scissors other ) ) ) ( and ( rec ( rotate-triple-rock self ) ( rotate-triple-paper other ) ) ( rec ( rotate-triple-paper self ) ( rotate-triple-scissors other ) ) ( rec ( rotate-triple-scissors self ) ( rotate-triple-rock other ) ) ) ( and ( rec ( rotate-triple-rock self ) ( rotate-triple-scissors other ) ) ( rec ( rotate-triple-paper self ) ( rotate-triple-rock other ) ) ( rec ( rotate-triple-scissors self ) ( rotate-triple-paper other ) ) ) ) ) ( define ( hash-proc self rec ) ( define r ( rec ( rotate-triple-rock self ) ) ) ( define p ( rec ( rotate-triple-paper self ) ) ) ( define s ( rec ( rotate-triple-scissors self ) ) ) ( hash-code-combine ( eq-hash-code struct:rotate-triple ) ( hash-code-combine-unordered ( hash-code-combine r p ) ( hash-code-combine p s ) ( hash-code-combine s r ) ) ) ) ( define ( hash2-proc self rec ) ( define r ( rec ( rotate-triple-rock self ) ) ) ( define p ( rec ( rotate-triple-paper self ) ) ) ( define s ( rec ( rotate-triple-scissors self ) ) ) ( hash-code-combine ( eq-hash-code struct:rotate-triple ) ( hash-code-combine-unordered ( hash-code-combine r p ) ( hash-code-combine p s ) ( hash-code-combine s r ) ) ) ) ] )\n> > ( equal? ( rotate-triple ' A ' B ' C ) ( rotate-triple ' A ' B ' C ) )\n> #t\n> > ( = ( equal-hash-code ( rotate-triple ' A ' B ' C ) ) ( equal-hash-code ( rotate-triple ' A ' B ' C ) ) )\n> #t\n> > ( equal? ( rotate-triple ' A ' B ' C ) ( rotate-triple ' C ' B ' A ) )\n> #f\n> > ( = ( equal-hash-code ( rotate-triple ' A ' B ' C ) ) ( equal-hash-code ( rotate-triple ' C ' B ' A ) ) )\n> #f\n> > ( equal? ( rotate-triple ' A ' B ' C ) ( rotate-triple ' C ' A ' B ) )\n> #t\n> > ( = ( equal-hash-code ( rotate-triple ' A ' B ' C ) ) ( equal-hash-code ( rotate-triple ' C ' A ' B ) ) )\n> #t\n> ```\n\n> ```\n(hash-code-combine* hc ... hcs) → fixnum?\n  hc : exact-integer?\n  hcs : (listof exact-integer?)```\n\n\nLike [hash-code-combine](#%28def._%28%28lib._racket%2Fhash-code..rkt%29._hash-code-combine%29%29), but the last argument is used as a list of arguments for [hash-code-combine](#%28def._%28%28lib._racket%2Fhash-code..rkt%29._hash-code-combine%29%29), so ([hash-code-combine*](#%28def._%28%28lib._racket%2Fhash-code..rkt%29._hash-code-combine%2A%29%29) hc [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) hcs) is the same as ([apply](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._apply%29%29) [hash-code-combine](#%28def._%28%28lib._racket%2Fhash-code..rkt%29._hash-code-combine%29%29) hc [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) hcs). In other words, the relationship between [hash-code-combine](#%28def._%28%28lib._racket%2Fhash-code..rkt%29._hash-code-combine%29%29) and [hash-code-combine*](#%28def._%28%28lib._racket%2Fhash-code..rkt%29._hash-code-combine%2A%29%29) is similar to the one between [list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) and [list*](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%2A%29%29).\n\n> ```\n(hash-code-combine-unordered* hc ... hcs) → fixnum?\n  hc : exact-integer?\n  hcs : (listof exact-integer?)\n```"} {"text": "### 3.14 Definitions: [define](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29), [define-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), ...\nLike hash-code-combine-unordered, but the last argument is used as a list of arguments for hash-code-combine-unordered, so (hash-code-combine-unordered* hc ... hcs) is the same as (apply hash-code-combine-unordered hc ... hcs). In other words, the relationship between hash-code-combine-unordered and hash-code-combine-unordered* is similar to the one between list and list*.\n------------------------------------------------------------------------"} {"text": "# 4.2 Booleans"} {"text": "### 4.2 Booleans\nTrue and false booleans are represented by the values #t and #f, respectively, though operations that depend on a boolean value typically treat anything other than #f as true. The #t value is always eq? to itself, and #f is always eq? to itself.\nSee Reading Booleans for information on reading booleans and Printing Booleans for information on printing booleans.\nSee also and, or, andmap, and ormap.\n> ```\n(boolean? v) → boolean?\n  v : any/c```\nReturns #t if v is #t or #f, #f otherwise.\nExamples:\n> ```racket\n> > ( boolean? #f )\n> #t\n> > ( boolean? #t )\n> #t\n> > ( boolean? ' true )\n> #f\n> ```\n> ```\n(not v)  →  boolean?\n  v : any/c\n```\n\n\nReturns #t if v is #f, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( not #f )\n> #t\n> > ( not #t )\n> #f\n> > ( not ' we-have-no-bananas )\n> #f\n> ```\n\n> ```\n(immutable? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is an immutable [string](strings.html#%28tech._string%29), [byte string](bytestrings.html#%28tech._byte._string%29), [vector](vectors.html#%28tech._vector%29), [hash table](hashtables.html#%28tech._hash._table%29), or [box](boxes.html#%28tech._box%29), #f otherwise."} {"text": "# 4.2 Booleans\nNote that [immutable?](#%28def._%28%28quote._~23~25kernel%29._immutable~3f%29%29) is not a general predicate for immutability (despite its name). It works only for a handful of datatypes for which a single predicate—[string?](strings.html#%28def._%28%28quote._~23~25kernel%29._string~3f%29%29), [vector?](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector~3f%29%29), etc.—recognizes both mutable and immutable variants of the datatype. In particular, [immutable?](#%28def._%28%28quote._~23~25kernel%29._immutable~3f%29%29) produces #f for a [pair](pairs.html#%28tech._pair%29), even though pairs are immutable, since [pair?](pairs.html#%28def._%28%28quote._~23~25kernel%29._pair~3f%29%29) implies immutability.\nSee also [immutable-string?](#%28def._%28%28lib._racket%2Fmutability..rkt%29._immutable-string~3f%29%29), [mutable-string?](#%28def._%28%28lib._racket%2Fmutability..rkt%29._mutable-string~3f%29%29), etc.\nExamples:\n> ```racket\n> > ( immutable? ' hello )\n> #f\n> > ( immutable? \"a string\" )\n> #t\n> > ( immutable? ( box 5 ) )\n> #f\n> > ( immutable? # ( 0 1 2 3 ) )\n> #t\n> > ( immutable? ( make-hash ) )\n> #f\n> > ( immutable? ( make-immutable-hash ' ( [ a b ] ) ) )\n> #t\n> > ( immutable? #t )\n> #f\n> ```"} {"text": "#### 4.2.1 Boolean Aliases\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/bool](#%28mod-path._racket%2Fbool%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/bool](#%28mod-path._racket%2Fbool%29) and [racket](index.html) libraries, but not [racket/base](index.html).\n>
\n

value

\n

[true](#%28def._%28%28lib._racket%2Fbool..rkt%29._true%29%29) : [boolean?](#%28def._%28%28quote._~23~25kernel%29._boolean~3f%29%29)

\nAn alias for #t.\n>
\n

value

"} {"text": "# 4.2 Booleans\n

[false](#%28def._%28%28lib._racket%2Fbool..rkt%29._false%29%29) : [boolean?](#%28def._%28%28quote._~23~25kernel%29._boolean~3f%29%29)

\nAn alias for #f.\n> ```\n(parameter)\t→\n```\nReturns (equal? a b) (if a and b are symbols).\n\n> ```\n(boolean=? a b) → boolean?\n  a : boolean?\n  b : boolean?```\n\n\nReturns ([equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) a b) (if a and b are booleans).\n\n> ```\n(false? v)  →  boolean?\n  v : any/c\n```\nReturns (not v).\n>
\n

syntax

\n

(nand expr ...)

\nSame as (not (and expr ...)).\nExamples:\n> ```racket\n> > ( nand #f #t )\n> #t\n> > ( nand #f ( error ' ack \"we don't get here\" ) )\n> #t\n> ```\n>
\n

syntax

\n

(nor expr ...)

\nSame as (not (or expr ...)).\nIn the two argument case, returns #t if neither of the arguments is a true value.\nExamples:\n> ```racket\n> > ( nor #f #t )\n> #f\n> > ( nor #t ( error ' ack \"we don't get here\" ) )\n> #f\n> ```\n>
\n

syntax

\n

(implies expr1 expr2)

\nChecks to be sure that the first expression implies the second.\nSame as (if expr1 expr2 #t)."} {"text": "# 4.2 Booleans\nExamples:\n> ```racket\n> > ( implies #f #t )\n> #t\n> > ( implies #f #f )\n> #t\n> > ( implies #t #f )\n> #f\n> > ( implies #f ( error ' ack \"we don't get here\" ) )\n> #t\n> ```\n> ```\n(xor b1 b2) → any\n  b1 : any/c\n  b2 : any/c```\nReturns the exclusive or of b1 and b2.\nIf exactly one of b1 and b2 is not #f, then return it. Otherwise, returns #f.\nExamples:\n> ```racket\n> > ( xor 11 #f )\n> 11\n> > ( xor #f 22 )\n> 22\n> > ( xor 11 22 )\n> #f\n> > ( xor #f #f )\n> #f\n> ```"} {"text": "#### 4.2.2 Mutability Predicates\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/mutability](#%28mod-path._racket%2Fmutability%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/mutability](#%28mod-path._racket%2Fmutability%29) library, not [racket/base](index.html) or [racket](index.html).\nAdded in version 8.9.0.3 of package base.\n> ```\n(mutable-string? v)  →  boolean?\n  v : any/c\n(immutable-string? v)  →  boolean?\n  v : any/c\n(mutable-bytes? v)  →  boolean?\n  v : any/c\n(immutable-bytes? v)  →  boolean?\n  v : any/c\n(mutable-vector? v)  →  boolean?\n  v : any/c\n(immutable-vector? v)  →  boolean?\n  v : any/c\n(mutable-box? v)  →  boolean?\n  v : any/c\n(immutable-box? v)  →  boolean?\n  v : any/c\n(mutable-hash? v)  →  boolean?\n  v : any/c"} {"text": "# 4.2 Booleans\n(immutable-hash? v)  →  boolean?\n  v : any/c\n```\nPredicates that combine string?, bytes?, vector?, box?, and hash? with immutable? or its inverse. The predicates are potentially faster than using immutable? and other predicates separately.\n\n------------------------------------------------------------------------\n\n# 4.3 Numbers\n\n### 4.3 Numbers\n\n> > > \"+\"Numbers in The Racket Guide introduces numbers.\n\nAll numbers are complex numbers. Some of them are real numbers, and all of the real numbers that can be represented are also rational numbers, except for +inf.0 (positive infinity), +inf.f (single-precision variant, when enabled via read-single-flonum), -inf.0 (negative infinity), -inf.f (single-precision variant, when enabled), +nan.0 (not-a-number), and +nan.f (single-precision variant, when enabled). Among the rational numbers, some are integers, because round applied to the number produces the same number.\n\n> > > \"+\"See Reading Numbers for information on the syntax of number literals.\n\nOrthogonal to those categories, each number is also either an exact number or an inexact number. Unless otherwise specified, computations that involve an inexact number produce inexact results. Certain operations on inexact numbers, however, produce an exact number, such as multiplying an inexact number with an exact 0. Operations that mathematically produce irrational numbers for some rational arguments (e.g., sqrt) may produce inexact results even for exact arguments.\n\nIn the case of complex numbers, either the real and imaginary parts are both exact or inexact with the same precision, or the number has an exact zero real part and an inexact imaginary part; a complex number with an exact zero imaginary part is a real number.\n\nInexact real numbers are implemented as double-precision IEEE floating-point numbers, also known as flonums, or as single-precision IEEE floating-point numbers, also known as single-flonums. Single-flonums are supported only when (single-flonum-available?) reports #t. Although we write +inf.f, -inf.f, and +nan.f to mean single-flonums, those forms read as double-precision flonums by default, since read-single-flonum is #f by default. When single-flonums are supported, inexact numbers are still represented as flonums by default, and single precision is used only when a computation starts with single-flonums.\n\nInexact numbers can be coerced to exact form, except for the inexact numbers +inf.0, +inf.f, -inf.0, -inf.f, +nan.0, and +nan.f, which have no exact form. Dividing a number by exact zero raises an exception; dividing a non-zero number other than +nan.0 or +nan.f by an inexact zero returns +inf.0, +inf.f, -inf.0 or -inf.f, depending on the sign and precision of the dividend. The +nan.0 value is not = to itself, but +nan.0 is eqv? to itself, and +nan.f is similarly eqv? but not = to itself. Conversely, (= 0.0 -0.0) is #t, but (eqv? 0.0 -0.0) is #f, and the same for 0.0f0 and -0.0f0 (which are single-precision variants). The datum -nan.0 refers to the same constant as +nan.0, and -nan.f is the same as +nan.f.\n\nCalculations with infinities produce results consistent with IEEE double- or single-precision floating point where IEEE specifies the result; in cases where IEEE provides no specification, the result corresponds to the limit approaching infinity, or +nan.0 or +nan.f if no such limit exists.\n\nThe precision and size of exact numbers is limited only by available memory (and the precision of operations that can produce irrational numbers). In particular, adding, multiplying, subtracting, and dividing exact numbers always produces an exact result.\n\nA fixnum is an exact integer whose two’s complement representation fits into 30 or 31 bits (depending on the Racket variant) on a 32-bit platform or 61 or 63 bits (depending on the Racket variant) on a 64-bit platform. No allocation is required when computing with fixnums. See also the racket/fixnum module, below.\n\nTwo fixnums that are = are also the same according to eq?. Otherwise, the result of eq? applied to two numbers is undefined, except that numbers produced by the default reader in read-syntax mode are interned and therefore eq? when they are eqv?.\n\nTwo real numbers are eqv? when they are both inexact with the same precision or both exact, and when they are = (except for +nan.0, +nan.f, 0.0, +0.0f0, -0.0, and -0.0f0, as noted above). Two complex numbers are eqv? when their real and imaginary parts are eqv?. Two numbers are equal? when they are eqv?.\n\nSee Reading Numbers for information on reading numbers and Printing Numbers for information on printing numbers.\n\n| |\n|----------------------------------------------------------------------------------------------------------------------------------------------|\n|     4.3.1 Number Types |\n|     4.3.2 Generic Numerics |\n|       4.3.2.1 Arithmetic |\n|       4.3.2.2 Number Comparison |\n|       4.3.2.3 Powers and Roots |\n|       4.3.2.4 Trigonometric Functions |\n|       4.3.2.5 Complex Numbers |\n|       4.3.2.6 Bitwise Operations |\n|       4.3.2.7 Random Numbers |\n|       4.3.2.8 Other Randomness Utilities |\n|       4.3.2.9 Number–String Conversions |\n|       4.3.2.10 Extra Constants and Functions |\n|     4.3.3 Flonums |\n|       4.3.3.1 Flonum Arithmetic |\n|       4.3.3.2 Flonum Vectors |\n|     4.3.4 Fixnums |\n|       4.3.4.1 Fixnum Arithmetic |\n|       4.3.4.2 Fixnum Vectors |\n|       4.3.4.3 Fixnum Range |\n|     4.3.5 Extflonums |\n|       4.3.5.1 Extflonum Arithmetic |\n|       4.3.5.2 Extflonum Constants |\n|       4.3.5.3 Extflonum Vectors |\n|       4.3.5.4 Extflonum Byte Strings |\n\n------------------------------------------------------------------------\n\n# 4.3.1 Number Types\n\n#### 4.3.1 Number Types\n\n> ```\n(number? v) → boolean?\n  v : any/c```\n\n\nReturns #t if v is a number, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( number? 1 )\n> #t\n> > ( number? 2+3i )\n> #t\n> > ( number? \"hello\" )\n> #f\n> > ( number? +nan.0 )\n> #t\n> ```\n\n> ```\n(complex? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 4.2 Booleans\nReturns (number? v), because all numbers are complex numbers.\n> ```\n(real? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a [real number](numbers.html#%28tech._real._number%29), #f otherwise.\nExamples:\n> ```racket\n> > ( real? 1 )\n> #t\n> > ( real? +inf.0 )\n> #t\n> > ( real? 2+3i )\n> #f\n> > ( real? 2.0+0.0i )\n> #f\n> > ( real? \"hello\" )\n> #f\n> ```\n> ```\n(rational? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a rational number, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( rational? 1 )\n> #t\n> > ( rational? +inf.0 )\n> #f\n> > ( rational? \"hello\" )\n> #f\n> ```\n\n> ```\n(integer? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a number that is an [integer](numbers.html#%28tech._integer%29), #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( integer? 1 )\n> #t\n> > ( integer? 2.3 )\n> #f\n> > ( integer? 4.0 )\n> #t\n> > ( integer? +inf.0 )\n> #f\n> > ( integer? 2+3i )\n> #f\n> > ( integer? \"hello\" )\n> #f\n> ```\n\n> ```\n(exact-integer? v)  →  boolean?\n  v : any/c\n```\nReturns (and (integer? v) (exact? v)).\nExamples:\n> ```racket\n> > ( exact-integer? 1 )\n> #t\n> > ( exact-integer? 4.0 )\n> #f\n> ```\n> ```\n(exact-nonnegative-integer? v)  →  boolean?\n  v : any/c```\nReturns ([and](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29) ([exact-integer?](#%28def._%28%28quote._~23~25kernel%29._exact-integer~3f%29%29) v) ([not](booleans.html#%28def._%28%28quote._~23~25kernel%29._not%29%29) ([negative?](#%28def._%28%28quote._~23~25kernel%29._negative~3f%29%29) v))).\nExamples:"} {"text": "# 4.2 Booleans\n> ```racket\n> > ( exact-nonnegative-integer? 0 )\n> #t\n> > ( exact-nonnegative-integer? -1 )\n> #f\n> ```\n> ```\n(exact-positive-integer? v)  →  boolean?\n  v : any/c\n```\nReturns (and (exact-integer? v) (positive? v)).\n\nExamples:\n\n> ```racket\n> > ( exact-positive-integer? 1 )\n> #t\n> > ( exact-positive-integer? 0 )\n> #f\n> ```\n\n> ```\n(inexact-real? v)  →  boolean?\n  v : any/c```\n\n\nReturns ([and](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29) ([real?](#%28def._%28%28quote._~23~25kernel%29._real~3f%29%29) v) ([inexact?](#%28def._%28%28quote._~23~25kernel%29._inexact~3f%29%29) v)).\n\n> ```\n(fixnum? v)  →  boolean?\n  v : any/c\n```\nReturn #t if v is a fixnum, #f otherwise.\nNote: the result of this function is platform-dependent, so using it in syntax transformers can lead to platform-dependent bytecode files. See also fixnum-for-every-system?.\n> ```\n(flonum? v)  →  boolean?\n  v : any/c```\nReturn #t if v is a [flonum](numbers.html#%28tech._flonum%29), #f otherwise.\n> ```\n(double-flonum? v)  →  boolean?\n  v : any/c\n```\nIdentical to flonum?.\n\n> ```\n(single-flonum? v)  →  boolean?\n  v : any/c```\n\n\nReturn #t if v is a [single-flonum](numbers.html#%28tech._single._flonum%29) (i.e., a single-precision floating-point number), #f otherwise.\n\n> ```\n(single-flonum-available?)  →  boolean?\n```\nReturns #t if single-flonums are supported on the current platform, #f otherwise.\nCurrently, single-flonum-available? produces #t when (system-type 'vm) produces 'racket, and single-flonum-available? produces #f otherwise."} {"text": "# 4.2 Booleans\nIf the result is #f, then single-flonum? also produces #f for all arguments.\nAdded in version 7.3.0.5 of package base.\n> ```\n(zero? z)  →  boolean?\n  z : number?```\nReturns ([=](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._~3d%29%29) 0 z).\nExamples:\n> ```racket\n> > ( zero? 0 )\n> #t\n> > ( zero? -0 .0 )\n> #t\n> ```\n> ```\n(positive? x)  →  boolean?\n  x : real?\n```\nReturns (> x 0).\n\nExamples:\n\n> ```racket\n> > ( positive? 10 )\n> #t\n> > ( positive? -1 0 )\n> #f\n> > ( positive? 0.0 )\n> #f\n> ```\n\n> ```\n(negative? x)  →  boolean?\n  x : real?```\n\n\nReturns ([<](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._~3c%29%29) x 0).\n\nExamples:\n\n> ```racket\n> > ( negative? 10 )\n> #f\n> > ( negative? -1 0 )\n> #t\n> > ( negative? -0 .0 )\n> #f\n> ```\n\n> ```\n(even? n)  →  boolean?\n  n : integer?\n```\nReturns (zero? (modulo n 2)).\nExamples:\n> ```racket\n> > ( even? 10.0 )\n> #t\n> > ( even? 11 )\n> #f\n> > ( even? +inf.0 )\n> even?: contract violation\n> expected: integer?\n> given: +inf.0\n> ```\n> ```\n(odd? n)  →  boolean?\n  n : integer?```\nReturns ([not](booleans.html#%28def._%28%28quote._~23~25kernel%29._not%29%29) ([even?](#%28def._%28%28quote._~23~25kernel%29._even~3f%29%29) n)).\nExamples:\n> ```racket\n> > ( odd? 10.0 )\n> #f\n> > ( odd? 11 )\n> #t\n> > ( odd? +inf.0 )\n> odd?: contract violation\n> expected: integer?\n> given: +inf.0\n> ```\n> ```\n(exact? z)  →  boolean?\n  z : number?\n```\n\n\nReturns #t if z is an exact number, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( exact? 1 )\n> #t\n> > ( exact? 1.0 )\n> #f\n> ```\n\n> ```\n(inexact? z)  →  boolean?\n  z : number?\n```"} {"text": "# 4.2 Booleans\nReturns #t if z is an inexact number, #f otherwise.\nExamples:\n> ```racket\n> > ( inexact? 1 )\n> #f\n> > ( inexact? 1.0 )\n> #t\n> ```\n> ```\n(inexact → exact z)  →  exact?\n  z : number?\n```\nCoerces z to an exact number. If z is already exact, it is returned. If z is +inf.0, -inf.0, +nan.0, +inf.f, -inf.f, or +nan.f, then the exn:fail:contract exception is raised.\n\nExamples:\n\n> ```racket\n> > ( inexact → exact 1 )\n> 1\n> > ( inexact → exact 1.0 )\n> 1\n> ```\n\n> ```\n(exact → inexact z)  →  inexact?\n  z : number?```\n\n\nCoerces z to an inexact number. If z is already inexact, it is returned.\n\nExamples:\n\n> ```racket\n> > ( exact->inexact 1 )\n> 1.0\n> > ( exact->inexact 1.0 )\n> 1.0\n> ```\n\n> ```\n(real → single-flonum x)  →  single-flonum?\n  x : real?\n```\nCoerces x to a single-precision floating-point number. If x is already a single-precision floating-point number, it is returned.\n> ```\n(real → double-flonum x)  →  flonum?\n  x : real?\n```\n\n\nCoerces x to a double-precision floating-point number. If x is already a double-precision floating-point number, it is returned.\n\n------------------------------------------------------------------------\n\n# 4.3.2 Generic Numerics\n\n#### 4.3.2 Generic Numerics\n\nMost Racket numeric operations work on any kind of number.\n\n##### 4.3.2.1 Arithmetic\n\n> ```\n(+ z ...)  →  number?\n  z : number?\n```\nReturns the sum of the zs, adding pairwise from left to right. If no arguments are provided, the result is 0.\nExamples:\n> ```racket\n> > ( + 1 2 )\n> 3\n> > ( + 1.0 2+3i 5 )\n> 8.0+3.0i\n> > ( + )\n> 0\n> ```\n> ```"} {"text": "# 4.2 Booleans\n(- z)  →  number?\n  z : number?\n(- z w ...+)  →  number?\n  z : number?\n  w : number?\n```\n\n\nWhen no ws are supplied, returns ([-](#%28def._%28%28quote._~23~25kernel%29._-%29%29) 0 z). Otherwise, returns the subtraction of the ws from z working pairwise from left to right.\n\nExamples:\n\n> ```racket\n> > ( - 5 3.0 )\n> 2.0\n> > ( - 1 )\n> -1\n> > ( - 2+7i 1 3 )\n> -2+7i\n> ```\n\n> ```\n(* z ...)  →  number?\n  z : number?\n```\nReturns the product of the zs, multiplying pairwise from left to right. If no arguments are provided, the result is 1. Multiplying any number by exact 0 produces exact 0.\nExamples:\n> ```racket\n> > ( * 2 3 )\n> 6\n> > ( * 8.0 9 )\n> 72.0\n> > ( * 1+2i 3+4i )\n> -5+10i\n> ```\n> ```\n(/ z)  →  number?\n  z : number?\n(/ z w ...+)  →  number?\n  z : number?\n  w : number?\n```\n\n\nWhen no ws are supplied, returns ([/](#%28def._%28%28quote._~23~25kernel%29._%2F%29%29) 1 z). Otherwise, returns the division of z by the ws working pairwise from left to right.\n\nIf z is exact 0 and no w is exact 0, then the result is exact 0. If any w is exact 0, the [exn:fail:contract:divide-by-zero](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3adivide-by-zero%29%29) exception is raised.\n\nExamples:\n\n> ```racket\n> > ( / 3 4 )\n> 3/4\n> > ( / 81 3 3 )\n> 9\n> > ( / 10.0 )\n> 0.1\n> > ( / 1+2i 3+4i )\n> 11/25+2/25i\n> ```\n\n> ```\n(quotient n m)  →  integer?\n  n : integer?\n  m : integer?\n```\nReturns (truncate (/ n m)).\nExamples:"} {"text": "# 4.2 Booleans\n> ```racket\n> > ( quotient 10 3 )\n> 3\n> > ( quotient -1 0.0 3 )\n> -3.0\n> > ( quotient +inf.0 3 )\n> quotient: contract violation\n> expected: integer?\n> given: +inf.0\n> ```\n> ```\n(remainder n m)  →  integer?\n  n : integer?\n  m : integer?```\nReturns q with the same sign as n such that\n- ([abs](#%28def._%28%28quote._~23~25kernel%29._abs%29%29) q) is between 0 (inclusive) and ([abs](#%28def._%28%28quote._~23~25kernel%29._abs%29%29) m) (exclusive), and\n- ([+](#%28def._%28%28quote._~23~25kernel%29._%2B%29%29) q ([*](#%28def._%28%28quote._~23~25kernel%29._%2A%29%29) m ([quotient](#%28def._%28%28quote._~23~25kernel%29._quotient%29%29) n m))) equals n.\nIf m is exact 0, the [exn:fail:contract:divide-by-zero](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3adivide-by-zero%29%29) exception is raised.\nExamples:\n> ```racket\n> > ( remainder 10 3 )\n> 1\n> > ( remainder -1 0.0 3 )\n> -1.0\n> > ( remainder 10.0 -3 )\n> 1.0\n> > ( remainder -1 0 -3 )\n> -1\n> > ( remainder +inf.0 3 )\n> remainder: contract violation\n> expected: integer?\n> given: +inf.0\n> ```\n> ```\n(quotient/remainder n m)   →   integer?   integer?\n  n : integer?\n  m : integer?"} {"text": "# 4.2 Booleans\n```\nReturns (values (quotient n m) (remainder n m)), but the combination may be computed more efficiently than separate calls to quotient and remainder.\n\nExample:\n\n> ```racket\n> > ( quotient/remainder 10 3 )\n> 3 1\n> ```\n\n> ```\n(modulo n m)  →  integer?\n  n : integer?\n  m : integer?```\n\n\nReturns q with the same sign as m where\n\n- ([abs](#%28def._%28%28quote._~23~25kernel%29._abs%29%29) q) is between 0 (inclusive) and ([abs](#%28def._%28%28quote._~23~25kernel%29._abs%29%29) m) (exclusive), and\n\n- the difference between q and ([-](#%28def._%28%28quote._~23~25kernel%29._-%29%29) n ([*](#%28def._%28%28quote._~23~25kernel%29._%2A%29%29) m ([quotient](#%28def._%28%28quote._~23~25kernel%29._quotient%29%29) n m))) is a multiple of m.\n\nIf m is exact 0, the [exn:fail:contract:divide-by-zero](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3adivide-by-zero%29%29) exception is raised.\n\nExamples:\n\n> ```racket\n> > ( modulo 10 3 )\n> 1\n> > ( modulo -1 0.0 3 )\n> 2.0\n> > ( modulo 10.0 -3 )\n> -2.0\n> > ( modulo -1 0 -3 )\n> -1\n> > ( modulo +inf.0 3 )\n> modulo: contract violation\n> expected: integer?\n> given: +inf.0\n> ```\n\n> ```\n(add1 z)  →  number?\n  z : number?\n```\nReturns (+ z 1).\n> ```\n(sub1 z)  →  number?\n  z : number?```\nReturns ([-](#%28def._%28%28quote._~23~25kernel%29._-%29%29) z 1).\n> ```\n(abs x)  →  number?\n  x : real?"} {"text": "# 4.2 Booleans\n```\nReturns the absolute value of x.\n\nExamples:\n\n> ```racket\n> > ( abs 1.0 )\n> 1.0\n> > ( abs -1 )\n> 1\n> ```\n\n> ```\n(max x ...+) → real?\n  x : real?```\n\n\nReturns the largest of the xs, or +nan.0 if any x is +nan.0. If any x is inexact, the result is coerced to inexact. See also [argmax](pairs.html#%28def._%28%28lib._racket%2Flist..rkt%29._argmax%29%29).\n\nExamples:\n\n> ```racket\n> > ( max 1 3 2 )\n> 3\n> > ( max 1 3 2.0 )\n> 3.0\n> ```\n\n> ```\n(min x ...+) → real?\n  x : real?\n```\nReturns the smallest of the xs, or +nan.0 if any x is +nan.0. If any x is inexact, the result is coerced to inexact. See also argmin.\nExamples:\n> ```racket\n> > ( min 1 3 2 )\n> 1\n> > ( min 1 3 2.0 )\n> 1.0\n> ```\n> ```\n(gcd n ...) → rational?\n  n : rational?```\nReturns the greatest common divisor (a non-negative number) of the ns; for non-integer ns, the result is the [gcd](#%28def._%28%28quote._~23~25kernel%29._gcd%29%29) of the numerators divided by the [lcm](#%28def._%28%28quote._~23~25kernel%29._lcm%29%29) of the denominators. If no arguments are provided, the result is 0. If all arguments are zero, the result is zero.\nExamples:\n> ```racket\n> > ( gcd 10 )\n> 10\n> > ( gcd 12 81.0 )\n> 3.0\n> > ( gcd 1/2 1/3 )\n> 1/6\n> ```\n> ```\n(lcm n ...) → (or/c rational? +inf.0)\n  n : rational?"} {"text": "# 4.2 Booleans\n```\nReturns the least common multiple (a non-negative number) of the ns. For two non-integer ns, the result is the absolute value of the product divided by the gcd. If no arguments are provided, the result is 1. If any argument is zero, the result is zero; furthermore, if any argument is exact 0, the result is exact 0.\n\nExamples:\n\n> ```racket\n> > ( lcm 10 )\n> 10\n> > ( lcm 3 4.0 )\n> 12.0\n> > ( lcm 1/2 2/3 )\n> 2\n> ```\n\n> ```\n(round x)  →  (or/c integer? +inf.0 -inf.0 +nan.0)\n  x : real?```\n\n\nReturns the integer closest to x, resolving ties in favor of an even number, but +inf.0, -inf.0, and +nan.0 round to themselves.\n\nExamples:\n\n> ```racket\n> > ( round 17/4 )\n> 4\n> > ( round -1 7/4 )\n> -4\n> > ( round 2.5 )\n> 2.0\n> > ( round -2 .5 )\n> -2.0\n> > ( round +inf.0 )\n> +inf.0\n> ```\n\n> ```\n(floor x)  →  (or/c integer? +inf.0 -inf.0 +nan.0)\n  x : real?\n```\nReturns the largest integer that is no more than x, but +inf.0, -inf.0, and +nan.0 floor to themselves.\nExamples:\n> ```racket\n> > ( floor 17/4 )\n> 4\n> > ( floor -1 7/4 )\n> -5\n> > ( floor 2.5 )\n> 2.0\n> > ( floor -2 .5 )\n> -3.0\n> > ( floor +inf.0 )\n> +inf.0\n> ```\n> ```\n(ceiling x)  →  (or/c integer? +inf.0 -inf.0 +nan.0)\n  x : real?\n```\n\n\nReturns the smallest integer that is at least as large as x, but +inf.0, -inf.0, and +nan.0 ceiling to themselves.\n\nExamples:\n\n> ```racket\n> > ( ceiling 17/4 )\n> 5\n> > ( ceiling -1 7/4 )\n> -4\n> > ( ceiling 2.5 )\n> 3.0\n> > ( ceiling -2 .5 )\n> -2.0\n> > ( ceiling +inf.0 )\n> +inf.0\n> ```\n\n> ```\n(truncate x)  →  (or/c integer? +inf.0 -inf.0 +nan.0)\n  x : real?\n```"} {"text": "# 4.2 Booleans\nReturns the integer farthest from 0 that is not farther from 0 than x, but +inf.0, -inf.0, and +nan.0 truncate to themselves.\nExamples:\n> ```racket\n> > ( truncate 17/4 )\n> 4\n> > ( truncate -1 7/4 )\n> -4\n> > ( truncate 2.5 )\n> 2.0\n> > ( truncate -2 .5 )\n> -2.0\n> > ( truncate +inf.0 )\n> +inf.0\n> ```\n> ```\n(numerator q)  →  integer?\n  q : rational?\n```\n\n\nCoerces q to an exact number, finds the numerator of the number expressed in its simplest fractional form, and returns this number coerced to the exactness of q.\n\nExamples:\n\n> ```racket\n> > ( numerator 5 )\n> 5\n> > ( numerator 17/4 )\n> 17\n> > ( numerator 2.3 )\n> 2589569785738035.0\n> ```\n\n> ```\n(denominator q)  →  (and/c integer? positive?)\n  q : rational?\n```\nCoerces q to an exact number, finds the denominator of the number expressed in its simplest fractional form, and returns this number coerced to the exactness of q.\nExamples:\n> ```racket\n> > ( denominator 5 )\n> 1\n> > ( denominator 17/4 )\n> 4\n> > ( denominator 2.3 )\n> 1125899906842624.0\n> ```\n> ```\n(rationalize x tolerance)  →  real?\n  x : real?\n  tolerance : real?"} {"text": "# 4.2 Booleans\n```\n\n\nAmong the real numbers within ([abs](#%28def._%28%28quote._~23~25kernel%29._abs%29%29) tolerance) of x, returns the one corresponding to an exact number whose [denominator](#%28def._%28%28quote._~23~25kernel%29._denominator%29%29) is the smallest. If multiple integers are within tolerance of x, the one closest to 0 is used.\n\nExamples:\n\n> ```racket\n> > ( rationalize 1/4 1/10 )\n> 1/3\n> > ( rationalize -1 /4 1/10 )\n> -1/3\n> > ( rationalize 1/4 1/4 )\n> 0\n> > ( rationalize 11/40 1/4 )\n> 1/2\n> ```\n\n##### 4.3.2.2 Number Comparison\n\n> ```\n(= z w ...)  →  boolean?\n  z : number?\n  w : number?\n```\nReturns #t if all of the arguments are numerically equal, #f otherwise. An inexact number is numerically equal to an exact number when the exact coercion of the inexact number is the exact number. Also, 0.0 and -0.0 are numerically equal, but +nan.0 is not numerically equal to itself.\nExamples:\n> ```racket\n> > ( = 1 1.0 )\n> #t\n> > ( = 1 2 )\n> #f\n> > ( = 2+3i 2+3i 2+3i )\n> #t\n> > ( = 1 )\n> #t\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n>
\n

procedure

\n

(< x y ...)  →  boolean?

  x : real?
  y : real?
\nReturns #t if the arguments in the given order are strictly increasing, #f otherwise.\nExamples:"} {"text": "# 4.2 Booleans\n> ```racket\n> > ( < 1 1 )> #f\n> > ( < 1 2 3 )> #t\n> > ( < 1 )> #t\n> > ( < 1 +inf.0 )> #t\n> > ( < 1 +nan.0 )> #f\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n>
\n

procedure

\n

(<= x y ...)  →  boolean?

  x : real?
  y : real?
\nReturns #t if the arguments in the given order are non-decreasing, #f otherwise.\nExamples:\n> ```racket\n> > ( <= 1 1 )> #t\n> > ( <= 1 2 1 )> #f\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n> ```\n(> x y ...)  →  boolean?\n  x : real?\n  y : real?```\nReturns #t if the arguments in the given order are strictly decreasing, #f otherwise.\nExamples:\n> ```racket\n> > ( > 1 1 )\n> #f\n> > ( > 3 2 1 )\n> #t\n> > ( > +inf.0 1 )\n> #t\n> > ( > +nan.0 1 )\n> #f\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n> ```\n(>= x y ...)  →  boolean?\n  x : real?\n  y : real?"} {"text": "# 4.2 Booleans\n```\nReturns #t if the arguments in the given order are non-increasing, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( >= 1 1 )\n> #t\n> > ( >= 1 2 1 )\n> #f\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n##### 4.3.2.3 Powers and Roots\n\n> ```\n(sqrt z) → number?\n  z : number?```\n\n\nReturns the principal square root of z. The result is exact if z is exact and z’s square root is rational. See also [integer-sqrt](#%28def._%28%28quote._~23~25kernel%29._integer-sqrt%29%29).\n\nExamples:\n\n> ```racket\n> > ( sqrt 4/9 )\n> 2/3\n> > ( sqrt 2 )\n> 1.4142135623730951\n> > ( sqrt -1 )\n> 0+1i\n> ```\n\n> ```\n(integer-sqrt n)  →  complex?\n  n : integer?\n```\nReturns (floor (sqrt n)) for positive n. The result is exact if n is exact. For negative n, the result is (* (integer-sqrt (- n)) 0+1i).\nExamples:\n> ```racket\n> > ( integer-sqrt 4.0 )\n> 2.0\n> > ( integer-sqrt 5 )\n> 2\n> > ( integer-sqrt -4 .0 )\n> 0.0+2.0i\n> > ( integer-sqrt -4 )\n> 0+2i\n> ```\n> ```\n(integer-sqrt/remainder n)   →   complex?   integer?\n  n : integer?```\nReturns ([integer-sqrt](#%28def._%28%28quote._~23~25kernel%29._integer-sqrt%29%29) n) and ([-](#%28def._%28%28quote._~23~25kernel%29._-%29%29) n ([expt](#%28def._%28%28quote._~23~25kernel%29._expt%29%29) ([integer-sqrt](#%28def._%28%28quote._~23~25kernel%29._integer-sqrt%29%29) n) 2)).\nExamples:\n> ```racket\n> > ( integer-sqrt/remainder 4.0 )\n> 2.0 0.0\n> > ( integer-sqrt/remainder 5 )\n> 2 1\n> ```\n> ```\n(expt z w)  →  number?\n  z : number?\n  w : number?"} {"text": "# 4.2 Booleans\n```\nReturns z raised to the power of w.\n\nIf w is exact 0, the result is exact 1. If w is 0.0 or -0.0 and z is a real number other than exact 1 or 0, the result is 1.0 (even if z is +nan.0).\n\nIf z is exact 1, the result is exact 1. If z is 1.0 and w is a real number, the result is 1.0 (even if w is +nan.0).\n\nIf z is exact 0, the result is as follows:\n\n- w is exact 0 — result is 1\n\n- w is 0.0 or -0.0 — result is 1.0\n\n- real part of w is negative — the exn:fail:contract:divide-by-zero exception is raised\n\n- w is nonreal with a nonpositive real part — the exn:fail:contract:divide-by-zero exception is raised\n\n- w is +nan.0 — result is +nan.0\n\n- otherwise — result is 0\n\nIf w is exact 1/2, the result is the same as (sqrt z), which can be exact. Other fractional powers are not treated specially in this manner:\n\nExamples:\n\n> ```racket\n> > ( expt 9 1/2 )\n> 3\n> > ( expt 9 0.5 )\n> 3.0\n> > ( expt 16 1/4 )\n> 2.0\n> > ( expt 16 0.25 )\n> 2.0\n> ```\n\nFurther special cases when w is a real number: These special cases correspond to pow in C99 \\[C99\\], except when z is negative and w is a not an integer.\n\n- \n\n(expt 0.0 w):\n\n\n\n\n\n- w is negative — result is +inf.0\n\n- w is positive — result is 0.0\n\n\n\n- \n\n(expt -0.0 w):\n\n\n\n\n\n- \n\nw is negative:\n\n\n\n\n\n- w is an odd integer — result is -inf.0\n\n- w otherwise rational — result is +inf.0\n\n\n\n- \n\nw is positive:\n\n\n\n\n\n- w is an odd integer — result is -0.0\n\n- w otherwise rational — result is 0.0\n\n\n\n\n\n- \n\n(expt z -inf.0) for positive z:\n\n\n\n\n\n- z is less than 1.0 — result is +inf.0\n\n- z is greater than 1.0 — result is 0.0\n\n\n\n- \n\n(expt z +inf.0) for positive z:\n\n\n\n\n\n- z is less than 1.0 — result is 0.0\n\n- z is greater than 1.0 — result is +inf.0\n\n\n\n- \n\n(expt -inf.0 w) for integer w:\n\n\n\n\n\n- \n\nw is negative:\n\n\n\n\n\n- w is odd — result is -0.0\n\n- w is even — result is 0.0\n\n\n\n- \n\nw is positive:\n\n\n\n\n\n- w is odd — result is -inf.0\n\n- w is even — result is +inf.0\n\n\n\n\n\n- \n\n(expt +inf.0 w):\n\n\n\n\n\n- w is negative — result is 0.0\n\n- w is positive — result is +inf.0\n\n\n\nExamples:\n\n> ```racket\n> > ( expt 2 3 )\n> 8\n> > ( expt 4 0.5 )\n> 2.0\n> > ( expt +inf.0 0 )\n> 1\n> ```\n\n> ```\n(exp z) → number?\n  z : number?```\n\n\nReturns Euler’s number raised to the power of z. The result is normally inexact, but it is exact 1 when z is an exact 0. See also [expt](#%28def._%28%28quote._~23~25kernel%29._expt%29%29).\n\nExamples:\n\n> ```racket\n> > ( exp 1 )\n> 2.718281828459045\n> > ( exp 2+3i )\n> -7.315110094901103+1.0427436562359045i\n> > ( exp 0 )\n> 1\n> ```\n\n> ```\n(log z [b) → number?\n  z : number?\n  b : number? = (exp 1)\n```"} {"text": "# 4.2 Booleans\nReturns the natural logarithm of z. The result is normally inexact, but it is exact 0 when z is an exact 1. When z is exact 0, exn:fail:contract:divide-by-zero exception is raised.\nIf b is provided, it serves as an alternative base. It is equivalent to (/ (log z) (log b)), but can potentially run faster. If b is exact 1, exn:fail:contract:divide-by-zero exception is raised.\nConsider using fllogb from math/flonum instead when accuracy is important.\nExamples:\n> ```racket\n> > ( log ( exp 1 ) )\n> 1.0\n> > ( log 2+3i )\n> 1.2824746787307684+0.982793723247329i\n> > ( log 1 )\n> 0\n> > ( log 100 10 )\n> 2.0\n> > ( log 8 2 )\n> 3.0\n> > ( log 5 5 )\n> 1.0\n> ```\nChanged in version 6.9.0.1 of package base: Added second argument for arbitrary bases."} {"text": "##### 4.3.2.4 Trigonometric Functions\n> ```\n(sin z)  →  number?\n  z : number?```\nReturns the sine of z, where z is in radians. The result is normally inexact, but it is exact 0 if z is exact 0.\nExamples:\n> ```racket\n> > ( sin 3.14159 )\n> 2.65358979335273e-6\n> > ( sin 1.0+5.0i )\n> 62.44551846769654+40.0921657779984i\n> ```\n> ```\n(cos z)  →  number?\n  z : number?\n```\n\n\nReturns the cosine of z, where z is in radians.\n\nExamples:\n\n> ```racket\n> > ( cos 3.14159 )\n> -0.9999999999964793\n> > ( cos 1.0+5.0i )\n> 40.09580630629883-62.43984868079963i\n> ```\n\n> ```\n(tan z)  →  number?\n  z : number?\n```\nReturns the tangent of z, where z is in radians. The result is normally inexact, but it is exact 0 if z is exact 0.\nExamples:\n> ```racket\n> > ( tan 0.7854 )\n> 1.0000036732118494\n> > ( tan 1.0+5.0i )\n> 8.2567198342296e-5+1.0000377833796008i\n> ```\n> ```\n(asin z)  →  number?\n  z : number?\n```\n\n\nReturns the arcsine in radians of z. The result is normally inexact, but it is exact 0 if z is exact 0.\n\nExamples:\n\n> ```racket\n> > ( asin 0.25 )\n> 0.25268025514207865\n> > ( asin 1.0+5.0i )\n> 0.1937931365549322+2.3309746530493123i\n> ```\n\n> ```\n(acos z)  →  number?\n  z : number?\n```\nReturns the arccosine in radians of z.\nExamples:\n> ```racket\n> > ( acos 0.25 )\n> 1.318116071652818\n> > ( acos 1.0+5.0i )\n> 1.3770031902399644-2.3309746530493123i\n> ```\n> ```\n(atan z)  →  number?\n  z : number?\n(atan y x)  →  number?\n  y : real?\n  x : real?"} {"text": "# 4.2 Booleans\n```\nIn the one-argument case, returns the arctangent of the inexact approximation of z, except that the result is an exact 0 for z as 0, and the exn:fail:contract:divide-by-zero exception is raised for z as exact 0+1i or exact 0-1i.\n\nIn the two-argument case, the result is roughly the same as (atan (/ (exact → inexact y)) (exact → inexact x)), but the signs of y and x determine the quadrant of the result. Moreover, a suitable angle is returned when y divided by x produces +nan.0 in the case that neither y nor x is +nan.0. Finally, if y is exact 0 and x is a positive number, the result is exact 0. If both x and y are exact 0, the exn:fail:contract:divide-by-zero exception is raised.\n\nExamples:\n\n> ```racket\n> > ( atan 0.5 )\n> 0.46364760900080615\n> > ( atan 2 1 )\n> 1.1071487177940904\n> > ( atan -2 -1 )\n> -2.0344439357957027\n> > ( atan 1.0+5.0i )\n> 1.530881333938778+0.19442614214700213i\n> > ( atan +inf.0 -i nf.0 )\n> 2.356194490192345\n> ```\n\nChanged in version 7.2.0.2 of package base: Changed to raise exn:fail:contract:divide-by-zero for 0+1i and 0-1i and to produce exact 0 for any positive x (not just exact values) when y is 0.\n\n##### 4.3.2.5 Complex Numbers\n\n> ```\n(make-rectangular x y)  →  number?\n  x : real?\n  y : real?```\n\n\nCreates a complex number with x as the real part and y as the imaginary part. That is, returns ([+](#%28def._%28%28quote._~23~25kernel%29._%2B%29%29) x ([*](#%28def._%28%28quote._~23~25kernel%29._%2A%29%29) y 0+1i)).\n\nExample:\n\n> ```racket\n> > ( make-rectangular 3 4.0 )\n> 3.0+4.0i\n> ```\n\n> ```\n(make-polar magnitude angle)  →  number?\n  magnitude : real?\n  angle : real?\n```"} {"text": "# 4.2 Booleans\nCreates a complex number which, if thought of as a point, is magnitude away from the origin and is rotated angle radians counter clockwise from the positive x-axis. That is, returns (+ (* magnitude (cos angle)) (* magnitude (sin angle) 0+1i)).\nExamples:\n> ```racket\n> > ( make-polar 10 ( * pi 1/2 ) )\n> 6.123233995736766e-16+10.0i\n> > ( make-polar 10 ( * pi 1/4 ) )\n> 7.0710678118654755+7.071067811865475i\n> ```\n> ```\n(real-part z)  →  real?\n  z : number?```\nReturns the real part of the complex number z in rectangle coordinates.\nExamples:\n> ```racket\n> > ( real-part 3+4i )\n> 3\n> > ( real-part 5.0 )\n> 5.0\n> ```\n> ```\n(imag-part z)  →  real?\n  z : number?\n```\n\n\nReturns the imaginary part of the complex number z in rectangle coordinates.\n\nExamples:\n\n> ```racket\n> > ( imag-part 3+4i )\n> 4\n> > ( imag-part 5.0 )\n> 0\n> > ( imag-part 5.0+0.0i )\n> 0.0\n> ```\n\n> ```\n(magnitude z)  →  (and/c real? (not/c negative?))\n  z : number?\n```\nReturns the magnitude of the complex number z in polar coordinates. A complex number with +inf.0 or -inf.0 as a component has magnitude +inf.0, even if the other component is +nan.0.\nExamples:\n> ```racket\n> > ( magnitude -3 )\n> 3\n> > ( magnitude 3.0 )\n> 3.0\n> > ( magnitude 3+4i )\n> 5\n> ```\nChanged in version 7.2.0.2 of package base: Changed to always return +inf.0 for a complex number with a +inf.0 or -inf.0 component.\n> ```\n(angle z)  →  real?\n  z : number?"} {"text": "# 4.2 Booleans\n```\nReturns the angle of the complex number z in polar coordinates.\n\nThe result is guaranteed to be between (- pi) and pi, possibly equal to pi (but never equal to (- pi)).\n\nExamples:\n\n> ```racket\n> > ( angle -3 )\n> 3.141592653589793\n> > ( angle 3.0 )\n> 0\n> > ( angle 3+4i )\n> 0.9272952180016122\n> > ( angle +inf.0+inf.0i )\n> 0.7853981633974483\n> > ( angle -1 )\n> 3.141592653589793\n> ```\n\n##### 4.3.2.6 Bitwise Operations\n\n> ```\n(bitwise-ior n ...) → exact-integer?\n  n : exact-integer?```\n\n\nReturns the bitwise “inclusive or” of the ns in their (semi-infinite) two’s complement representation. If no arguments are provided, the result is 0.\n\nExamples:\n\n> ```racket\n> > ( bitwise-ior 1 2 )\n> 3\n> > ( bitwise-ior -3 2 1 )\n> -31\n> ```\n\n> ```\n(bitwise-and n ...) → exact-integer?\n  n : exact-integer?\n```\nReturns the bitwise “and” of the ns in their (semi-infinite) two’s complement representation. If no arguments are provided, the result is -1.\nExamples:\n> ```racket\n> > ( bitwise-and 1 2 )\n> 0\n> > ( bitwise-and -3 2 -1 )\n> -32\n> ```\n> ```\n(bitwise-xor n ...) → exact-integer?\n  n : exact-integer?```\nReturns the bitwise “exclusive or” of the ns in their (semi-infinite) two’s complement representation. If no arguments are provided, the result is 0.\nExamples:\n> ```racket\n> > ( bitwise-xor 1 5 )\n> 4\n> > ( bitwise-xor -3 2 -1 )\n> 31\n> ```\n> ```\n(bitwise-not n)  →  exact-integer?\n  n : exact-integer?"} {"text": "# 4.2 Booleans\n```\n\n\nReturns the bitwise “not” of n in its (semi-infinite) two’s complement representation.\n\nExamples:\n\n> ```racket\n> > ( bitwise-not 5 )\n> -6\n> > ( bitwise-not -1 )\n> 0\n> ```\n\n> ```\n(bitwise-bit-set? n m)  →  boolean?\n  n : exact-integer?\n  m : exact-nonnegative-integer?\n```\nReturns #t when the mth bit of n is set in n’s (semi-infinite) two’s complement representation.\nThis operation is equivalent to ([not](booleans.html#%28def._%28%28quote._~23~25kernel%29._not%29%29) ([zero?](number-types.html#%28def._%28%28quote._~23~25kernel%29._zero~3f%29%29) ([bitwise-and](#%28def._%28%28quote._~23~25kernel%29._bitwise-and%29%29) n ([arithmetic-shift](#%28def._%28%28quote._~23~25kernel%29._arithmetic-shift%29%29) 1 m)))), but it is faster and runs in constant time when n is positive.\nExamples:\n> ```racket\n> > ( bitwise-bit-set? 5 0 )\n> #t\n> > ( bitwise-bit-set? 5 2 )\n> #t\n> > ( bitwise-bit-set? -5 ( expt 2 700 ) )\n> #t\n> ```\n> ```\n(bitwise-first-bit-set n)  →  exact-integer?\n  n : exact-integer?"} {"text": "# 4.2 Booleans\n```\nReturns -1 if n is 0, otherwise returns the smallest m for which (bitwise-bit-set? n m) produces #t.\n\nExample:\n\n> ```racket\n> > ( bitwise-first-bit-set 128 )\n> 7\n> ```\n\nAdded in version 8.16.0.4 of package base.\n\nThis operation is equivalent to (not (zero? (bitwise-and n (arithmetic-shift 1 m)))), but it is faster and runs in constant time when n is positive.\n\nExamples:\n\n> ```racket\n> > ( bitwise-bit-set? 5 0 )\n> #t\n> > ( bitwise-bit-set? 5 2 )\n> #t\n> > ( bitwise-bit-set? -5 ( expt 2 700 ) )\n> #t\n> ```\n\n}\n\n> ```\n(bitwise-bit-field n start end) → exact-integer?\n  n : exact-integer?\n  start : exact-nonnegative-integer?\n   end   :   ( and/c exact-nonnegative-integer?\n> ( >=/c start ) )```\n\n\nExtracts the bits between position start and ([-](#%28def._%28%28quote._~23~25kernel%29._-%29%29) end 1) (inclusive) from n and shifts them down to the least significant portion of the number.\n\nThis operation is equivalent to the computation\n\n> ```racket\n> ( bitwise-and ( sub1 ( arithmetic-shift 1 ( - end start ) ) )\n> ( arithmetic-shift n ( - start ) ) )\n> ```\n\nbut it runs in constant time when n is positive, start and end are fixnums, and ([-](#%28def._%28%28quote._~23~25kernel%29._-%29%29) end start) is no more than the maximum width of a fixnum.\n\nEach pair of examples below uses the same numbers, showing the result both in binary and as integers.\n\nExamples:\n\n> ```racket\n> > ( format \"~b\" ( bitwise-bit-field ( string->number \"1101\" 2 ) 1 1 ) )\n> \"0\"\n> > ( bitwise-bit-field 13 1 1 )\n> 0\n> > ( format \"~b\" ( bitwise-bit-field ( string->number \"1101\" 2 ) 1 3 ) )\n> \"10\"\n> > ( bitwise-bit-field 13 1 3 )\n> 2\n> > ( format \"~b\" ( bitwise-bit-field ( string->number \"1101\" 2 ) 1 4 ) )\n> \"110\"\n> > ( bitwise-bit-field 13 1 4 )\n> 6\n> ```\n\n> ```\n(arithmetic-shift n m)  →  exact-integer?\n  n : exact-integer?\n  m : exact-integer?\n```"} {"text": "# 4.2 Booleans\nReturns the bitwise “shift” of n in its (semi-infinite) two’s complement representation. If m is non-negative, the integer n is shifted left by m bits; i.e., m new zeros are introduced as rightmost digits. If m is negative, n is shifted right by (- m) bits; i.e., the rightmost m digits are dropped.\nExamples:\n> ```racket\n> > ( arithmetic-shift 1 10 )\n> 1024\n> > ( arithmetic-shift 255 -3 )\n> 31\n> ```\n> ```\n(integer-length n)  →  exact-integer?\n  n : exact-integer?```\nReturns the number of bits in the (semi-infinite) two’s complement representation of n after removing all leading zeros (for non-negative n) or ones (for negative n).\nExamples:\n> ```racket\n> > ( integer-length 8 )\n> 4\n> > ( integer-length -8 )\n> 3\n> ```"} {"text": "##### 4.3.2.7 Random Numbers\n> ```\n(current-pseudo-random-generator)\t→\t\n(-> integer-in 1 4294967087)\n```\n(parameter)\t→\t\n(-> integer-in 0 (sub1 (expt 2 31)))```\n\n\nSeeds the current pseudo-random number generator with k. Seeding a generator sets its internal state deterministically; that is, seeding a generator with a particular number forces it to produce a sequence of pseudo-random numbers that is the same across runs and across platforms.\n\nThe [random-seed](#%28def._%28%28quote._~23~25kernel%29._random-seed%29%29) function is convenient for some purposes, but note that the space of states for a pseudo-random number generator is much larger that the space of allowed values for k. Use [vector->pseudo-random-generator!](#%28def._%28%28quote._~23~25kernel%29._vector-~3epseudo-random-generator%21%29%29) to set a pseudo-random number generator to any of its possible states.\n\n> ```\n(make-pseudo-random-generator)  →  pseudo-random-generator?\n```\n(current-milliseconds)\t→```\nReturns #t if v is a pseudo-random number generator, #f otherwise.\n> ```\n(current-pseudo-random-generator)\t→\t\n(-> current-pseudo-random-generator rand-gen)\n(current-pseudo-random-generator rand-gen) → void?\n rand-gen\t:\t\n(-> current-pseudo-random-generator rand-gen)"} {"text": "# 4.2 Booleans\n```\nA parameter that determines the pseudo-random number generator used by random.\n\n> ```\n(pseudo-random-generator → vector rand-gen)\n  →  pseudo-random-generator-vector?\n  rand-gen : pseudo-random-generator?```\n\n\nProduces a vector that represents the complete internal state of rand-gen. The vector is suitable as an argument to [vector->pseudo-random-generator](#%28def._%28%28quote._~23~25kernel%29._vector-~3epseudo-random-generator%29%29) to recreate the generator in its current state (across runs and across platforms).\n\n> ```\n(vector → pseudo-random-generator vec)\n  →  pseudo-random-generator?\n  vec : pseudo-random-generator-vector?\n```\n(parameter)\t→```\nLike [vector->pseudo-random-generator](#%28def._%28%28quote._~23~25kernel%29._vector-~3epseudo-random-generator%29%29), but changes rand-gen to the given state, instead of creating a new generator.\n> ```\n(pseudo-random-generator-vector? v)  →  boolean?\n  v : any/c"} {"text": "# 4.2 Booleans\n```\nReturns #t if v is a vector of six exact integers, where the first three integers are in the range 0 to 4294967086, inclusive; the last three integers are in the range 0 to 4294944442, inclusive; at least one of the first three integers is non-zero; and at least one of the last three integers is non-zero. Otherwise, the result is #f.\n\n##### 4.3.2.8 Other Randomness Utilities\n\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require racket/random) |  package: base |\n\n> ```\n(crypto-random-bytes n) → bytes?\n  n : exact-positive-integer?```\n\n\nProvides an interface to randomness from the underlying operating system. Use [crypto-random-bytes](#%28def._%28%28lib._racket%2Frandom..rkt%29._crypto-random-bytes%29%29) instead of [random](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._random%29%29) wherever security is a concern.\n\nReturns n random bytes. On Unix systems, the bytes are obtained from \"/dev/urandom\", while Windows uses the RtlGenRand system function.\n\nExample:\n\n> ```racket\n> > ( crypto-random-bytes 14 )\n> #\"\\0\\1\\1\\2\\3\\5\\b\\r\\25\\\"7Y\\220\\351\"\n> ```\n\nAdded in version 6.3 of package base.\n\n> ```\n(current-pseudo-random-generator)\t→\t\n(-> current-pseudo-random-generator)\n```\n(current-pseudo-random-generator)\t→\t\n(-> listof any/c)```"} {"text": "# 4.2 Booleans\nReturns a list of n elements of seq, picked at random, listed in any order. If replacement? is non-false, elements are drawn with replacement, which allows for duplicates.\nLike [sequence-length](sequences.html#%28def._%28%28lib._racket%2Fsequence..rkt%29._sequence-length%29%29), does not terminate on infinite sequences, and evaluates the entire sequence.\nAdded in version 6.4 of package base."} {"text": "##### 4.3.2.9 Number–String Conversions\n> ```\n(number → string z [radix) → string?\n  z : number?\n  radix : (or/c 2 8 10 16) = 10\n```\nReturns a string that is the printed form of z (see Printing Numbers) in the base specified by radix. If z is inexact, radix must be 10, otherwise the exn:fail:contract exception is raised.\n\nExamples:\n\n> ```racket\n> > ( number → string 3.0 )\n> \"3.0\"\n> > ( number → string 255 8 )\n> \"377\"\n> ```\n\n> ```\n(string → number s\n   [ radix  \n    convert-mode  \n    decimal-mode  \n    single-mode)  \n\n  →  (or/c number? #f string? extflonum?)\n  s : string?\n  radix : (integer-in 2 16) = 10\n   convert-mode   :   (or/c 'number-or-false 'read)\n      =   'number-or-false\n\n   decimal-mode   :   (or/c 'decimal-as-inexact 'decimal-as-exact)\n      =   ( if ( read-decimal-as-inexact )\n> ' decimal-as-inexact\n> ' decimal-as-exact )\n\n   single-mode   :   (or/c 'single 'double)\n      =   ( if ( read-single-flonum )\n> ' single\n> ' double )```\n\n\nReads and returns a number datum from s (see [Reading Numbers](reader.html#%28part._parse-number%29)). The optional radix argument specifies the default base for the number, which can be overridden by #b, #o, #d, or #x in the string.\n\nIf convert-mode is 'number-or-false, the result is #f if s does not parse exactly as a number datum (with no whitespace). If convert-mode is 'read, the result can be an [extflonum](extflonums.html#%28tech._extflonum%29), and it can be a string that contains an error message if [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) of s would report a reader exception (but the result can still be #f if [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) would report a symbol).\n\nThe decimal-mode argument controls number parsing the same way that the [read-decimal-as-inexact](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-decimal-as-inexact%29%29) parameter affects [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29).\n\nThe single-mode argument controls number parsing the same way that the [read-single-flonum](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-single-flonum%29%29) parameter affects [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29).\n\nExamples:\n\n> ```racket\n> > ( string->number \"3.0+2.5i\" )\n> 3.0+2.5i\n> > ( string->number \"hello\" )\n> #f\n> > ( string->number \"111\" 7 )\n> 57\n> > ( string->number \"#b111\" 7 )\n> 7\n> > ( string->number \"#e+inf.0\" 10 ' read )\n> \"no exact representation for +inf.0\"\n> > ( string->number \"10.3\" 10 ' read ' decimal-as-exact )\n> 103/10\n> ```\n\nChanged in version 6.8.0.2 of package base: Added the convert-mode and decimal-mode arguments. \nChanged in version 7.3.0.5: Added the single-mode argument.\n\n> ```\n(real → decimal-string n [decimal-digits) → string?\n  n : rational?\n  decimal-digits : exact-nonnegative-integer? = 2\n```"} {"text": "# 4.2 Booleans\nPrints n into a string and returns the string. The printed form of n shows exactly decimal-digits digits after the decimal point. The printed form uses a minus sign if n is negative, and it does not use a plus sign if n is positive.\nBefore printing, n is converted to an exact number, multiplied by (expt 10 decimal-digits), rounded, and then divided again by (expt 10 decimal-digits). The result of this process is an exact number whose decimal representation has no more than decimal-digits digits after the decimal (and it is padded with trailing zeros if necessary).\nIf n is a real number with no decimal representation (e.g. +nan.0, +inf.0), then the exn:fail:contract exception is raised. (Any real number that is convertible to decimal notation is rational, so n must be rational?, despite the name of the function.)\nExamples:\n> ```racket\n> > ( real → decimal-string pi )\n> \"3.14\"\n> > ( real → decimal-string pi 5 )\n> \"3.14159\"\n> ```\n> ```\n(integer-bytes → integer bstr\n    signed?        \n   [ big-endian?        \n    start        \n    end)   →   exact-integer?\n  bstr : bytes?\n  signed? : any/c\n  big-endian? : any/c = (system-big-endian?)\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (bytes-length bstr)```"} {"text": "# 4.2 Booleans\nConverts the machine-format number encoded in bstr to an exact integer. The start and end arguments specify the substring to decode, where ([-](#%28def._%28%28quote._~23~25kernel%29._-%29%29) end start) must be 1, 2, 4, or 8. If signed? is true, then the bytes are decoded as a two’s-complement number, otherwise it is decoded as an unsigned integer. If big-endian? is true, then the first byte’s value provides the most significant eight bits of the number, otherwise the first byte provides the least-significant eight bits, and so on.\nChanged in version 6.10.0.1 of package base: Added support for decoding a 1-byte string.\n> ```\n(integer → integer-bytes n\n    size-n        \n    signed?        \n   [ big-endian?        \n    dest-bstr        \n    start)   →   bytes?\n  n : exact-integer?\n  size-n : (or/c 1 2 4 8)\n  signed? : any/c\n  big-endian? : any/c = (system-big-endian?)\n   dest-bstr   :   (and/c bytes? (not/c immutable?))\n      =   (make-bytes size-n)\n  start : exact-nonnegative-integer? = 0"} {"text": "# 4.2 Booleans\n```\nConverts the exact integer n to a machine-format number encoded in a byte string of length size-n, which must be 1, 2, 4, or 8. If signed? is true, then the number is encoded as two’s complement, otherwise it is encoded as an unsigned bit stream. If big-endian? is true, then the most significant eight bits of the number are encoded in the first byte of the resulting byte string, otherwise the least-significant bits are encoded in the first byte, and so on.\n\nThe dest-bstr argument must be a mutable byte string of length size-n. The encoding of n is written into dest-bstr starting at offset start, and dest-bstr is returned as the result.\n\nIf n cannot be encoded in a byte string of the requested size and format, the exn:fail:contract exception is raised. If dest-bstr is not of length size-n, the exn:fail:contract exception is raised.\n\nChanged in version 6.10.0.1 of package base: Added support for encoding a 1-byte value.\n\n> ```\n(floating-point-bytes → real bstr\n   [ big-endian?        \n    start        \n    end)   →   flonum?\n\n  bstr : bytes?\n  big-endian? : any/c = (system-big-endian?)\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (bytes-length bstr)```\n\n\nConverts the IEEE floating-point number encoded in bstr from position start (inclusive) to end (exclusive) to an inexact real number. The difference between start an end must be either 4 or 8 bytes. If big-endian? is true, then the first byte’s ASCII value provides the most significant eight bits of the IEEE representation, otherwise the first byte provides the least-significant eight bits, and so on.\n\n> ```\n(real → floating-point-bytes x\n    size-n        \n   [ big-endian?        \n    dest-bstr        \n    start)   →   bytes?\n\n  x : real?\n  size-n : (or/c 4 8)\n  big-endian? : any/c = (system-big-endian?)\n   dest-bstr   :   (and/c bytes? (not/c immutable?))\n      =   (make-bytes size-n)\n\n  start : exact-nonnegative-integer? = 0\n```"} {"text": "# 4.2 Booleans\nConverts the real number x to its IEEE representation in a byte string of length size-n, which must be 4 or 8. If big-endian? is true, then the most significant eight bits of the number are encoded in the first byte of the resulting byte string, otherwise the least-significant bits are encoded in the first character, and so on.\nThe dest-bstr argument must be a mutable byte string of length size-n. The encoding of n is written into dest-bstr starting with byte start, and dest-bstr is returned as the result.\nIf dest-bstr is provided and it has less than start plus size-n bytes, the exn:fail:contract exception is raised.\n> ```\n(system-big-endian?)  →  boolean?```\nReturns #t if the native encoding of numbers is big-endian for the machine running Racket, #f if the native encoding is little-endian."} {"text": "##### 4.3.2.10 Extra Constants and Functions\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/math](#%28mod-path._racket%2Fmath%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/math](#%28mod-path._racket%2Fmath%29) and [racket](index.html) libraries, but not [racket/base](index.html).\n>
\n

value

\n

[pi](#%28def._%28%28lib._racket%2Fmath..rkt%29._pi%29%29) : [flonum?](number-types.html#%28def._%28%28quote._~23~25kernel%29._flonum~3f%29%29)

\nAn approximation of π, the ratio of a circle’s circumference to its diameter.\nExamples:"} {"text": "# 4.2 Booleans\n> ```racket\n> > pi\n> 3.141592653589793\n> > ( cos pi )\n> -1.0\n> ```\n>
\n

value

\n

[pi.f](#%28def._%28%28lib._racket%2Fmath..rkt%29._pi..f%29%29) : ([or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) [single-flonum?](number-types.html#%28def._%28%28quote._~23~25kernel%29._single-flonum~3f%29%29) [flonum?](number-types.html#%28def._%28%28quote._~23~25kernel%29._flonum~3f%29%29))

\nThe same value as [pi](#%28def._%28%28lib._racket%2Fmath..rkt%29._pi%29%29), but as a single-precision floating-point number if the current platform supports it.\nChanged in version 7.3.0.5 of package base: Allow value to be a double-precision flonum.\n> ```\n(degrees → radians x)  →  real?\n  x : real?\n```\n\n\nConverts an x-degree angle to radians.\n\nExamples:\n\n> ```racket\n> > ( degrees->radians 180 )\n> 3.141592653589793\n> > ( sin ( degrees->radians 45 ) )\n> 0.7071067811865475\n> ```\n\n> ```\n(radians → degrees x)  →  real?\n  x : real?\n```\nConverts x radians to degrees.\nExamples:\n> ```racket\n> > ( radians->degrees pi )\n> 180.0\n> > ( radians->degrees ( * 1/4 pi ) )\n> 45.0\n> ```\n> ```\n(sqr z)  →  number?\n  z : number?"} {"text": "# 4.2 Booleans\n```\nReturns (* z z).\n\n> ```\n(sgn x) → (or/c (=/c -1) (=/c 0) (=/c 1) +nan.0 +nan.f)\n  x : real?```\n\n\nReturns the sign of x as either -1, 0 (or a signed-zero variant, when inexact), 1, or not-a-number.\n\nExamples:\n\n> ```racket\n> > ( sgn 10 )\n> 1\n> > ( sgn -1 0.0 )\n> -1.0\n> > ( sgn 0 )\n> 0\n> > ( sgn -0 .0 )\n> -0.0\n> > ( sgn 0.0 )\n> 0.0\n> > ( sgn +nan.0 )\n> +nan.0\n> > ( sgn +inf.0 )\n> 1.0\n> > ( sgn -i nf.0 )\n> -1.0\n> ```\n\n> ```\n(conjugate z)  →  number?\n  z : number?\n```\nReturns the complex conjugate of z.\nExamples:\n> ```racket\n> > ( conjugate 1 )\n> 1\n> > ( conjugate 3+4i )\n> 3-4i\n> ```\n> ```\n(sinh z)  →  number?\n  z : number?\n```\n\n\nReturns the hyperbolic sine of z.\n\n> ```\n(cosh z)  →  number?\n  z : number?\n```\nReturns the hyperbolic cosine of z.\n> ```\n(tanh z)  →  number?\n  z : number?\n```\n\n\nReturns the hyperbolic tangent of z.\n\n> ```\n(exact-round x)  →  exact-integer?\n  x : rational?\n```\nEquivalent to (inexact → exact (round x)).\n> ```\n(exact-floor x)  →  exact-integer?\n  x : rational?```\nEquivalent to ([inexact->exact](number-types.html#%28def._%28%28quote._~23~25kernel%29._inexact-~3eexact%29%29) ([floor](#%28def._%28%28quote._~23~25kernel%29._floor%29%29) x)).\n> ```\n(exact-ceiling x)  →  exact-integer?\n  x : rational?"} {"text": "# 4.2 Booleans\n```\nEquivalent to (inexact → exact (ceiling x)).\n\n> ```\n(exact-truncate x)  →  exact-integer?\n  x : rational?```\n\n\nEquivalent to ([inexact->exact](number-types.html#%28def._%28%28quote._~23~25kernel%29._inexact-~3eexact%29%29) ([truncate](#%28def._%28%28quote._~23~25kernel%29._truncate%29%29) x)).\n\n> ```\n(order-of-magnitude r)  →  (and/c exact? integer?)\n  r : (and/c real? positive?)\n```\nComputes the greatest exact integer m such that:\n> ```racket\n> ( <= ( expt 10 m )> ( inexact → exact r ) )\n> ```\nHence also:\n> ```racket\n> ( < ( inexact → exact r )\n> ( expt 10 ( add1 m ) ) )\n> ```\nExamples:\n> ```racket\n> > ( order-of-magnitude 999 )\n> 2\n> > ( order-of-magnitude 1000 )\n> 3\n> > ( order-of-magnitude 1/100 )\n> -2\n> > ( order-of-magnitude 1/101 )\n> -3\n> ```\n> ```\n(nan? x) → boolean?\n  x : real?```\nReturns #t if x is [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29) to +nan.0 or +nan.f; otherwise #f.\n> ```\n(infinite? x)  →  boolean?\n  x : real?\n```\n\n\nReturns #t if x is +inf.0, -inf.0, +inf.f, -inf.f; otherwise #f.\n\n> ```\n(positive-integer? x)  →  boolean?\n  x : any/c\n```\nLike [exact-positive-integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-positive-integer~3f%29%29), but also returns #t for positive [inexact?](number-types.html#%28def._%28%28quote._~23~25kernel%29._inexact~3f%29%29) integers.\nAdded in version 6.8.0.2 of package base.\n> ```\n(negative-integer? x)  →  boolean?\n  x : any/c"} {"text": "# 4.2 Booleans\n```\nThe same as (and (integer? x) (negative? x)).\n\nAdded in version 6.8.0.2 of package base.\n\n> ```\n(nonpositive-integer? x)  →  boolean?\n  x : any/c```\n\n\nThe same as ([and](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29) ([integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._integer~3f%29%29) x) ([not](booleans.html#%28def._%28%28quote._~23~25kernel%29._not%29%29) ([positive?](number-types.html#%28def._%28%28quote._~23~25kernel%29._positive~3f%29%29) x))).\n\nAdded in version 6.8.0.2 of package base.\n\n> ```\n(nonnegative-integer? x)  →  boolean?\n  x : any/c\n```\nLike exact-nonnegative-integer?, but also returns #t for non-negative inexact? integers.\nAdded in version 6.8.0.2 of package base.\n> ```\n(natural? x)  →  boolean?\n  x : any/c```\nAn alias for [exact-nonnegative-integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-nonnegative-integer~3f%29%29).\nAdded in version 6.8.0.2 of package base.\n------------------------------------------------------------------------"} {"text": "# 4.3.3 Flonums"} {"text": "#### 4.3.3 Flonums\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/flonum]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe [racket/flonum]() library provides operations like [fl+](#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl%2B%29%29) that consume and produce only [flonums](numbers.html#%28tech._flonum%29). Flonum-specific operations can provide better performance when used consistently, and they are as safe as generic operations like [+](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._%2B%29%29)."} {"text": "# 4.3.3 Flonums\n> > > \"+\"See also [Fixnum and Flonum Optimizations](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=performance.html%23%2528part._fixnums%252Bflonums%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13)."} {"text": "##### 4.3.3.1 Flonum Arithmetic\n> ```\n(fl+ a ...) → flonum?\n  a : flonum?\n(fl- a b ...)  →  flonum?\n  a : flonum?\n  b : flonum?\n(fl* a ...)  →  flonum?\n  a : flonum?\n(fl/ a b ...)  →  flonum?\n  a : flonum?\n  b : flonum?\n(flabs a)  →  flonum?\n  a : flonum?\n```\nLike +, -, *, /, and abs, but constrained to consume flonums. The result is always a flonum.\n\nChanged in version 7.0.0.13 of package base: Allow zero or more arguments for fl+ and fl* and one or more arguments for fl- and fl/.\n\n> ```\n(fl= a b ...) → boolean?\n  a : flonum?\n  b : flonum?\n\n([fl\n\n(fl> a b ...)  →  boolean?\n  a : flonum?\n  b : flonum?\n\n([fl\n\n(fl>= a b ...)  →  boolean?\n  a : flonum?\n  b : flonum?\n\n(flmin a b ...)  →  flonum?\n  a : flonum?\n  b : flonum?\n\n(flmax a b ...)  →  flonum?\n  a : flonum?\n  b : flonum?```\n\n\nLike [=](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._~3d%29%29), [<](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._~3c%29%29), [>](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._~3e%29%29), [<=](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._~3c~3d%29%29), [>=](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._~3e~3d%29%29), [min](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._min%29%29), and [max](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._max%29%29), but constrained to consume [flonums](numbers.html#%28tech._flonum%29).\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n> ```\n(flround a)  →  flonum?\n  a : flonum?\n\n(flfloor a)  →  flonum?\n  a : flonum?\n\n(flceiling a)  →  flonum?\n  a : flonum?\n\n(fltruncate a)  →  flonum?\n  a : flonum?\n```"} {"text": "# 4.3.3 Flonums\nLike round, floor, ceiling, and truncate, but constrained to consume flonums.\n> ```\n(flsingle a)  →  flonum?\n  a : flonum?```\nReturns a value like a, but potentially discards precision and range so that the result can be represented as a single-precision IEEE floating-point number (even if [single-flonums](numbers.html#%28tech._single._flonum%29) are not supported).\nUsing [flsingle](#%28def._%28%28lib._racket%2Fflonum..rkt%29._flsingle%29%29) on the arguments and results of [fl+](#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl%2B%29%29), [fl-](#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl-%29%29), [fl*](#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl%2A%29%29), [fl/](#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl%2F%29%29), and [flsqrt](#%28def._%28%28lib._racket%2Fflonum..rkt%29._flsqrt%29%29)—that is, performing double-precision operations on values representable in single precision and then rounding the result to single precision—is always the same as performing the corresponding single-precision operation \\[[Roux14](doc-bibliography.html#%28cite._.Roux14%29)\\]. (For other operations, the IEEE floating-point specification does not make enough guarantees to say more about the interaction with [flsingle](#%28def._%28%28lib._racket%2Fflonum..rkt%29._flsingle%29%29).)\nAdded in version 7.8.0.7 of package base.\n> ```\n(flbit-field a start end)  →  exact-nonnegative-integer?\n  a : flonum?\n  start : (integer-in 0 64)\n  end : (integer-in 0 64)"} {"text": "# 4.3.3 Flonums\n```\n\n\nExtracts a range of bits from the 64-bit IEEE representation of a, returning the non-negative integer that has the same bits set in its (semi-infinite) two’s complement representation.\n\nExamples:\n\n> ```racket\n> > ( flbit-field -0 .0 63 64 )\n> 1\n> > ( format \"~x\" ( flbit-field 3.141579e+132 16 48 ) )\n> \"b43544f2\"\n> ```\n\nAdded in version 8.15.0.3 of package base.\n\n> ```\n(flsin a)  →  flonum?\n  a : flonum?\n\n(flcos a)  →  flonum?\n  a : flonum?\n\n(fltan a)  →  flonum?\n  a : flonum?\n\n(flasin a)  →  flonum?\n  a : flonum?\n\n(flacos a)  →  flonum?\n  a : flonum?\n\n(flatan a)  →  flonum?\n  a : flonum?\n\n(fllog a)  →  flonum?\n  a : flonum?\n\n(flexp a)  →  flonum?\n  a : flonum?\n\n(flsqrt a)  →  flonum?\n  a : flonum?\n```"} {"text": "# 4.3.3 Flonums\nLike [sin](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._sin%29%29), [cos](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._cos%29%29), [tan](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._tan%29%29), [asin](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._asin%29%29), [acos](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._acos%29%29), [atan](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._atan%29%29), [log](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._log%29%29), [exp](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._exp%29%29), and [sqrt](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._sqrt%29%29), but constrained to consume and produce [flonums](numbers.html#%28tech._flonum%29). The result is +nan.0 when a number outside the range -1.0 to 1.0 is given to [flasin](#%28def._%28%28lib._racket%2Fflonum..rkt%29._flasin%29%29) or [flacos](#%28def._%28%28lib._racket%2Fflonum..rkt%29._flacos%29%29), or when a negative number is given to [fllog](#%28def._%28%28lib._racket%2Fflonum..rkt%29._fllog%29%29) or [flsqrt](#%28def._%28%28lib._racket%2Fflonum..rkt%29._flsqrt%29%29).\n> ```\n(flexpt a b)  →  flonum?\n  a : flonum?\n  b : flonum?"} {"text": "# 4.3.3 Flonums\n```\n\n\nLike [expt](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._expt%29%29), but constrained to consume and produce [flonums](numbers.html#%28tech._flonum%29).\n\nDue to the result constraint, the results compared to [expt](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._expt%29%29) differ in the following cases: These special cases correspond to pow in C99 \\[[C99](doc-bibliography.html#%28cite._.C99%29)\\].\n\n- ([flexpt](#%28def._%28%28lib._racket%2Fflonum..rkt%29._flexpt%29%29) -1.0 +inf.0) — 1.0\n\n- ([flexpt](#%28def._%28%28lib._racket%2Fflonum..rkt%29._flexpt%29%29) a +inf.0) where a is negative — ([expt](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._expt%29%29) ([abs](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._abs%29%29) a) +inf.0)\n\n- ([flexpt](#%28def._%28%28lib._racket%2Fflonum..rkt%29._flexpt%29%29) a -inf.0) where a is negative — ([expt](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._expt%29%29) ([abs](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._abs%29%29) a) -inf.0)\n\n- \n\n ([expt](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._expt%29%29) -inf.0 b) where b is a non-integer:\n\n \n\n \n\n - b is negative — 0.0\n\n - b is positive — +inf.0\n\n \n\n- ([flexpt](#%28def._%28%28lib._racket%2Fflonum..rkt%29._flexpt%29%29) a b) where a is negative and b is not an integer — +nan.0\n\n> ```\n( → fl a)  →  flonum?\n  a : exact-integer?\n```"} {"text": "# 4.3.3 Flonums\nLike [exact->inexact](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-~3einexact%29%29), but constrained to consume exact integers, so the result is always a [flonum](numbers.html#%28tech._flonum%29).\n> ```\n(fl → exact-integer a)  →  exact-integer?\n  a : flonum?\n```\nLike inexact → exact, but constrained to consume an integer flonum, so the result is always an exact integer.\n\n> ```\n(make-flrectangular a b)\n  →   ( and/c complex?\n> ( lambda ( c ) ( flonum? ( real-part c ) ) )\n> ( lambda ( c ) ( flonum? ( imag-part c ) ) ) )\n\n  a : flonum?\n  b : flonum?\n\n(flreal-part a)  →  flonum?\n   a   :   ( and/c complex?\n> ( lambda ( c ) ( flonum? ( real-part c ) ) )\n> ( lambda ( c ) ( flonum? ( imag-part c ) ) ) )\n\n(flimag-part a)  →  flonum?\n   a   :   ( and/c complex?\n> ( lambda ( c ) ( flonum? ( real-part c ) ) )\n> ( lambda ( c ) ( flonum? ( imag-part c ) ) ) )```\n\n\nLike [make-rectangular](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._make-rectangular%29%29), [real-part](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._real-part%29%29), and [imag-part](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._imag-part%29%29), but both parts of the complex number must be inexact.\n\n> ```\n(flrandom rand-gen)  →  (and flonum? (>/c 0) ([\n```\nEquivalent to (random rand-gen)."} {"text": "##### 4.3.3.2 Flonum Vectors\nA flvector is like a vector, but it holds only inexact real numbers. This representation can be more compact, and unsafe operations on flvectors (see racket/unsafe/ops) can execute more efficiently than unsafe operations on vectors of inexact reals.\nAn f64vector as provided by ffi/vector stores the same kinds of values as a flvector, but with extra indirections that make f64vectors more convenient for working with foreign libraries. The lack of indirections makes unsafe flvector access more efficient.\nTwo flvectors are equal? if they have the same length, and if the values in corresponding slots of the flvectors are equal?.\nA printed flvector starts with #fl(, optionally with a number between the #fl and (. See Reading Vectors for information on reading flvectors and Printing Vectors for information on printing flvectors.\n> ```\n(flvector? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a [flvector](#%28tech._flvector%29), #f otherwise.\n> ```\n(flvector x ...) → flvector?\n  x : flonum?\n```\nCreates a flvector containing the given inexact real numbers.\n\nExample:\n\n> ```racket\n> > ( flvector 2.0 3.0 4.0 5.0 )\n> (flvector 2.0 3.0 4.0 5.0)\n> ```\n\n> ```\n(make-flvector size [x) → flvector?\n  size : exact-nonnegative-integer?\n  x : flonum? = 0.0```\n\n\nCreates a [flvector](#%28tech._flvector%29) with size elements, where every slot in the [flvector](#%28tech._flvector%29) is filled with x.\n\nExample:\n\n> ```racket\n> > ( make-flvector 4 3.0 )\n> (flvector 3.0 3.0 3.0 3.0)\n> ```\n\n> ```\n(flvector-length vec)  →  exact-nonnegative-integer?\n  vec : flvector?\n```"} {"text": "# 4.3.3 Flonums\nReturns the length of vec (i.e., the number of slots in the flvector).\n> ```\n(flvector-ref vec pos)  →  flonum?\n  vec : flvector?\n  pos : exact-nonnegative-integer?```\nReturns the inexact real number in slot pos of vec. The first slot is position 0, and the last slot is one less than ([flvector-length](#%28def._%28%28lib._racket%2Fflonum..rkt%29._flvector-length%29%29) vec).\n> ```\n(flvector-set! vec pos x)  →  flonum?\n  vec : flvector?\n  pos : exact-nonnegative-integer?\n  x : flonum?\n```\nSets the inexact real number in slot pos of vec. The first slot is position 0, and the last slot is one less than (flvector-length vec).\n\n> ```\n(flvector-copy vec [start end) → flvector?\n  vec : flvector?\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (vector-length v)```\n\n\nCreates a fresh [flvector](#%28tech._flvector%29) of size ([-](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._-%29%29) end start), with all of the elements of vec from start (inclusive) to end (exclusive).\n\n> ```\n(in-flvector vec [start stop step) → sequence?\n  vec : flvector?\n  start : exact-nonnegative-integer? = 0\n  stop : (or/c exact-integer? #f) = #f\n  step : (and/c exact-integer? (not/c zero?)) = 1\n```\nReturns a sequence equivalent to vec when no optional arguments are supplied.\nThe optional arguments start, stop, and step are as in in-vector.\nA in-flvector application can provide better performance for flvector iteration when it appears directly in a for clause."} {"text": "# 4.3.3 Flonums\n>
\n

syntax

\n

(for/flvector maybe-length (for-clause ...) body ...)

\n

syntax

\n

(for*/flvector maybe-length (for-clause ...) body ...)

 
maybe-length = 
  | #:length length-expr
  | #:length length-expr #:fill fill-expr
 
  length-expr : exact-nonnegative-integer?
  fill-expr : flonum?
"} {"text": "# 4.3.3 Flonums\nLike for/vector or for*/vector, but for flvectors. The default fill-expr produces 0.0.\n> ```\n(shared-flvector x ...) → flvector?\n  x : flonum?```\nCreates a [flvector](#%28tech._flvector%29) containing the given inexact real numbers. For communication among [places](places.html#%28tech._place%29), the new [flvector](#%28tech._flvector%29) is allocated in the [shared memory space](places.html#%28tech._shared._memory._space%29).\nExample:\n> ```racket\n> > ( shared-flvector 2.0 3.0 4.0 5.0 )\n> (flvector 2.0 3.0 4.0 5.0)\n> ```\n> ```\n(make-shared-flvector size [x) → flvector?\n  size : exact-nonnegative-integer?\n  x : flonum? = 0.0"} {"text": "# 4.3.3 Flonums\n```\nCreates a flvector with size elements, where every slot in the flvector is filled with x. For communication among places, the new flvector is allocated in the shared memory space.\n\nExample:\n\n> ```racket\n> > ( make-shared-flvector 4 3.0 )\n> (flvector 3.0 3.0 3.0 3.0)\n> ```\n\n------------------------------------------------------------------------\n\n# 4.3.4 Fixnums\n\n#### 4.3.4 Fixnums\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/fixnum]()) |  package: base |\n\nThe [racket/fixnum]() library provides operations like fx+ that consume and produce only fixnums. The operations in this library are meant to be safe versions of unsafe operations like unsafe-fx+. These safe operations are generally no faster than using generic primitives like +.\n\nThe expected use of the [racket/fixnum]() library is for code where the require of [racket/fixnum]() is replaced with\n\n> > > See the documentation of filtered-in for use with #lang racket/base.\n\n> ```racket\n> ( require ( filtered-in\n> ( λ ( name )\n> ( and ( regexp-match #rx\"^unsafe-fx\" name )\n> ( regexp-replace #rx\"unsafe-\" name \"\" ) ) )\n> racket/unsafe/ops ) )\n> ```\n\nto drop in unsafe versions of the library. Alternately, when encountering crashes with code that uses unsafe fixnum operations, use the [racket/fixnum]() library to help debug the problems.\n\n##### 4.3.4.1 Fixnum Arithmetic\n\n> ```\n(fx+ a ...) → fixnum?\n  a : fixnum?\n\n(fx- a b ...)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n\n(fx* a ...)  →  fixnum?\n  a : fixnum?\n\n(fxquotient a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n\n(fxremainder a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n\n(fxmodulo a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n\n(fxabs a)  →  fixnum?\n  a : fixnum?```\n\n\nSafe versions of [unsafe-fx+](unsafe.html#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fx%2B%29%29), [unsafe-fx-](unsafe.html#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fx-%29%29), [unsafe-fx*](unsafe.html#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fx%2A%29%29), [unsafe-fxquotient](unsafe.html#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fxquotient%29%29), [unsafe-fxremainder](unsafe.html#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fxremainder%29%29), [unsafe-fxmodulo](unsafe.html#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fxmodulo%29%29), and [unsafe-fxabs](unsafe.html#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fxabs%29%29). The [exn:fail:contract:non-fixnum-result](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3anon-fixnum-result%29%29) exception is raised if the arithmetic result would not be a fixnum.\n\nChanged in version 7.0.0.13 of package base: Allow zero or more arguments for [fx+](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fx%2B%29%29) and [fx*](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fx%2A%29%29) and one or more arguments for [fx-](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fx-%29%29).\n\n> ```\n(fxand a ...) → fixnum?\n  a : fixnum?\n\n(fxior a ...)  →  fixnum?\n  a : fixnum?\n\n(fxxor a ...)  →  fixnum?\n  a : fixnum?\n\n(fxnot a)  →  fixnum?\n  a : fixnum?\n\n(fxlshift a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n\n(fxrshift a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n```"} {"text": "# 4.3.3 Flonums\nLike bitwise-and, bitwise-ior, bitwise-xor, bitwise-not, and arithmetic-shift, but constrained to consume fixnums; the result is always a fixnum. The unsafe-fxlshift and unsafe-fxrshift operations correspond to arithmetic-shift, but require non-negative arguments; unsafe-fxlshift is a positive (i.e., left) shift, and unsafe-fxrshift is a negative (i.e., right) shift, where the number of bits to shift must be no more than the number of bits used to represent a fixnum. The exn:fail:contract:non-fixnum-result exception is raised if the arithmetic result would not be a fixnum.\nChanged in version 7.0.0.13 of package base: Allow any number of arguments for fxand, fxior, and fxxor.\n> ```\n(fxpopcount a)  →  fixnum?\n  a : (and/c fixnum? (not/c negative?))\n(fxpopcount32 a)  →  fixnum?\n  a : (and/c fixnum? (integer-in 0 #xFFFFFFFF))\n(fxpopcount16 a)  →  fixnum?\n  a : (and/c fixnum? (integer-in 0 #xFFFF))```\nCounts the number of bits in the two’s complement representation of a. Depending on the platform, the [fxpopcount32](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxpopcount32%29%29) and [fxpopcount16](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxpopcount16%29%29) operations can be faster when the result is known to be no more than 32 or 16, respectively.\nAdded in version 8.5.0.7 of package base.\n> ```\n(fx+/wraparound a b) → fixnum?\n  a : fixnum?\n  b : fixnum?\n(fx-/wraparound [a] b)  →  fixnum?\n  a : fixnum? = 0\n  b : fixnum?\n(fx*/wraparound a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n(fxlshift/wraparound a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?"} {"text": "# 4.3.3 Flonums\n```\nLike fx+, fx-, fx*, and fxlshift, but a fixnum result is produced for any allowed arguments (i.e., for any fixnum argument, except that the second fxlshift/wraparound argument must be between 0 and the number of bits in a fixnum, inclusive). The result is produced by simply discarding bits that do not fit in a fixnum representation. The result is negative if the highest of the retained bits is set—even, for example, if the value was produced by adding two positive fixnums.\n\nAdded in version 7.9.0.6 of package base. \nChanged in version 8.15.0.12: Changed fx-/wraparound to accept a single argument.\n\n> ```\n(fxrshift/logical a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?```\n\n\nShifts the bits in a to the right by b, filling in with zeros. With the sign bit treated as just another bit, a logical right-shift of a negative-signed fixnum can produce a large positive fixnum. For example, ([fxrshift/logical](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxrshift%2Flogical%29%29) -1 1) produces ([most-positive-fixnum](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._most-positive-fixnum%29%29)), illustrating that logical right-shift results are platform-dependent.\n\nExamples:\n\n> ```racket\n> > ( fxrshift/logical 128 2 )\n> 32\n> > ( fxrshift/logical 255 4 )\n> 15\n> > ( = ( fxrshift/logical -1 1 ) ( most-positive-fixnum ) )\n> #t\n> ```\n\nAdded in version 8.8.0.5 of package base.\n\n> ```\n(fx= a b ...) → boolean?\n  a : fixnum?\n  b : fixnum?\n\n([fx\n\n(fx> a b ...)  →  boolean?\n  a : fixnum?\n  b : fixnum?\n\n([fx\n\n(fx>= a b ...)  →  boolean?\n  a : fixnum?\n  b : fixnum?\n\n(fxmin a b ...)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n\n(fxmax a b ...)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n```"} {"text": "# 4.3.3 Flonums\nLike =, <, >, <=, >=, min, and max, but constrained to consume fixnums.\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n> ```\n(fx → fl a) → flonum?\n  a : fixnum?\n(fl → fx fl)  →  fixnum?\n  fl : flonum?```\nConversion between [fixnums](numbers.html#%28tech._fixnum%29) and [flonums](numbers.html#%28tech._flonum%29) with truncation in the case of converting a [flonum](numbers.html#%28tech._flonum%29) to a [fixnum](numbers.html#%28tech._fixnum%29).\nThe [fx->fl](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fx-~3efl%29%29) function is the same as [exact->inexact](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-~3einexact%29%29) or [->fl](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._-~3efl%29%29) constrained to a fixnum argument.\nThe [fl->fx](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fl-~3efx%29%29) function is the same as [truncate](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._truncate%29%29) followed by [inexact->exact](number-types.html#%28def._%28%28quote._~23~25kernel%29._inexact-~3eexact%29%29) or [fl->exact-integer](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl-~3eexact-integer%29%29) constrained to returning a fixnum. If the truncated flonum does not fit into a fixnum, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nChanged in version 7.7.0.8 of package base: Changed [fl->fx](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fl-~3efx%29%29) to truncate.\n> ```"} {"text": "# 4.3.3 Flonums\n(fixnum-for-every-system? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a fixnum and is represented by fixnum by every Racket implementation, #f otherwise.\n\nAdded in version 7.3.0.11 of package base.\n\n##### 4.3.4.2 Fixnum Vectors\n\nA fxvector is like a vector, but it holds only fixnums. The only advantage of a fxvector over a vector is that a shared version can be created with functions like shared-fxvector.\n\nTwo fxvectors are equal? if they have the same length, and if the values in corresponding slots of the fxvectors are equal?.\n\nA printed fxvector starts with #fx(, optionally with a number between the #fx and (. See Reading Vectors for information on reading fxvectors and Printing Vectors for information on printing fxvectors.\n\n> ```\n(fxvector? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a [fxvector](#%28tech._fxvector%29), #f otherwise.\n\n> ```\n(fxvector x ...) → fxvector?\n  x : fixnum?\n```\nCreates a fxvector containing the given fixnums.\nExample:\n> ```racket\n> > ( fxvector 2 3 4 5 )\n> (fxvector 2 3 4 5)\n> ```\n> ```\n(make-fxvector size [x) → fxvector?\n  size : exact-nonnegative-integer?\n  x : fixnum? = 0```\nCreates a [fxvector](#%28tech._fxvector%29) with size elements, where every slot in the [fxvector](#%28tech._fxvector%29) is filled with x.\nExample:\n> ```racket\n> > ( make-fxvector 4 3 )\n> (fxvector 3 3 3 3)\n> ```\n> ```\n(fxvector-length vec)  →  exact-nonnegative-integer?\n  vec : fxvector?"} {"text": "# 4.3.3 Flonums\n```\nReturns the length of vec (i.e., the number of slots in the fxvector).\n\n> ```\n(fxvector-ref vec pos)  →  fixnum?\n  vec : fxvector?\n  pos : exact-nonnegative-integer?```\n\n\nReturns the [fixnum](numbers.html#%28tech._fixnum%29) in slot pos of vec. The first slot is position 0, and the last slot is one less than ([fxvector-length](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxvector-length%29%29) vec).\n\n> ```\n(fxvector-set! vec pos x)  →  fixnum?\n  vec : fxvector?\n  pos : exact-nonnegative-integer?\n  x : fixnum?\n```\nSets the fixnum in slot pos of vec. The first slot is position 0, and the last slot is one less than (fxvector-length vec).\n> ```\n(fxvector-copy vec [start end) → fxvector?\n  vec : fxvector?\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (vector-length v)```\nCreates a fresh [fxvector](#%28tech._fxvector%29) of size ([-](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._-%29%29) end start), with all of the elements of vec from start (inclusive) to end (exclusive).\n> ```\n(in-fxvector vec [start stop step) → sequence?\n  vec : fxvector?\n  start : exact-nonnegative-integer? = 0\n  stop : (or/c exact-integer? #f) = #f\n  step : (and/c exact-integer? (not/c zero?)) = 1"} {"text": "# 4.3.3 Flonums\n```\nReturns a sequence equivalent to vec when no optional arguments are supplied.\n\nThe optional arguments start, stop, and step are as in in-vector.\n\nAn in-fxvector application can provide better performance for fxvector iteration when it appears directly in a for clause.\n\n>
\n\n

syntax

\n\n

(for/fxvector maybe-length (for-clause ...) body ...)

\n\n

syntax

\n\n

(for*/fxvector maybe-length (for-clause ...) body ...)

 
maybe-length = 
  | #:length length-expr
  | #:length length-expr #:fill fill-expr
 
  length-expr : exact-nonnegative-integer?
  fill-expr : fixnum?
\n\nLike for/vector or for*/vector, but for fxvectors. The default fill-expr produces 0.\n\n> ```\n(shared-fxvector x ...) → fxvector?\n  x : fixnum?```\n\n\nCreates a [fxvector](#%28tech._fxvector%29) containing the given [fixnums](numbers.html#%28tech._fixnum%29). For communication among [places](places.html#%28tech._place%29), the new [fxvector](#%28tech._fxvector%29) is allocated in the [shared memory space](places.html#%28tech._shared._memory._space%29).\n\nExample:\n\n> ```racket\n> > ( shared-fxvector 2 3 4 5 )\n> (fxvector 2 3 4 5)\n> ```\n\n> ```\n(make-shared-fxvector size [x) → fxvector?\n  size : exact-nonnegative-integer?\n  x : fixnum? = 0\n```"} {"text": "# 4.3.3 Flonums\nCreates a fxvector with size elements, where every slot in the fxvector is filled with x. For communication among places, the new fxvector is allocated in the shared memory space.\nExample:\n> ```racket\n> > ( make-shared-fxvector 4 3 )\n> (fxvector 3 3 3 3)\n> ```"} {"text": "##### 4.3.4.3 Fixnum Range\n> ```\n(most-positive-fixnum)  →  fixnum?\n(most-negative-fixnum)  →  fixnum?```\nReturns the largest-magnitude positive and negative [fixnums](numbers.html#%28tech._fixnum%29). The values of ([most-positive-fixnum](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._most-positive-fixnum%29%29)) and ([most-negative-fixnum](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._most-negative-fixnum%29%29)) depend on the platform and virtual machine, but all fixnums are in the range ([most-negative-fixnum](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._most-negative-fixnum%29%29)) to ([most-positive-fixnum](#%28def._%28%28lib._racket%2Ffixnum..rkt%29._most-positive-fixnum%29%29)) inclusive, and all exact integers in that range are fixnums.\nAdded in version 8.1.0.7 of package base.\n------------------------------------------------------------------------"} {"text": "# 4.3.5 Extflonums"} {"text": "#### 4.3.5 Extflonums\n| | |\n|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/extflonum]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nAn extflonum is an extended-precision (80-bit) floating-point number. Extflonum arithmetic is supported on platforms with extended-precision hardware and where the extflonum implementation does not conflict with normal double-precision arithmetic (i.e., on x86 and x86_64 platforms when Racket is compiled to use SSE instructions for floating-point operations, and on Windows when \"longdouble.dll\" is available).\nA extflonum is not a [number](numbers.html#%28tech._number%29) in the sense of [number?](number-types.html#%28def._%28%28quote._~23~25kernel%29._number~3f%29%29). Only extflonum-specific operations such as [extfl+](#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extfl%2B%29%29) perform extflonum arithmetic."} {"text": "# 4.3.5 Extflonums\nA literal extflonum is written like an [inexact number](numbers.html#%28tech._inexact._number%29), but using an explicit t or T exponent marker (see [Reading Extflonums](reader.html#%28part._parse-extflonum%29)). For example, 3.5t0 is an extflonum. The extflonum values for infinity are +inf.t and -inf.t. The extflonum value for not-a-number is +nan.t or -nan.t.\nIf ([extflonum-available?](#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extflonum-available~3f%29%29)) produces #f, then all operations exported by [racket/extflonum]() raise [exn:fail:unsupported](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aunsupported%29%29), except for [extflonum?](#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extflonum~3f%29%29), [extflonum-available?](#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extflonum-available~3f%29%29), and [extflvector?](#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extflvector~3f%29%29) (which always work). The reader (see [The Reader](reader.html)) always accepts extflonum input; when extflonum operations are not supported, printing an extflonum from the reader uses its source notation (as opposed to normalizing the format)."} {"text": "# 4.3.5 Extflonums\nTwo extflonums are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) along the same lines as [flonums](numbers.html#%28tech._flonum%29): when they are [extfl=](#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extfl~3d%29%29) and have the same sign (which matters for -0.0t0 and +0.0t0), or when they are both +nan.t. If extflonums are not supported on a platform, extflonums are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) only if they are [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29).\n> ```\n(extflonum? v)  →  boolean?\n  v : any/c\n```\n\n\nReturns #t if v is an extflonum, #f otherwise.\n\n> ```\n(extflonum-available?)  →  boolean?\n```\nReturns #t if [extflonum](#%28tech._extflonum%29) operations are supported on the current platform, #f otherwise."} {"text": "##### 4.3.5.1 Extflonum Arithmetic\n> ```\n(extfl+ a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?\n(extfl- a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?\n(extfl* a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?\n(extfl/ a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?\n(extflabs a)  →  extflonum?\n  a : extflonum?\n```\nLike fl+, fl-, fl*, fl/, and flabs, but for extflonums.\n\n> ```\n(extfl= a b) → boolean?\n  a : extflonum?\n  b : extflonum?\n\n([extfl\n\n(extfl> a b)  →  boolean?\n  a : extflonum?\n  b : extflonum?\n\n([extfl\n\n(extfl>= a b)  →  boolean?\n  a : extflonum?\n  b : extflonum?\n\n(extflmin a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?\n\n(extflmax a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?```\n\n\nLike [fl=](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl~3d%29%29), [fl<](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl~3c%29%29), [fl>](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl~3e%29%29), [fl<=](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl~3c~3d%29%29), [fl>=](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl~3e~3d%29%29), [flmin](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flmin%29%29), and [flmax](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flmax%29%29), but for [extflonums](#%28tech._extflonum%29).\n\n> ```\n(extflround a)  →  extflonum?\n  a : extflonum?\n\n(extflfloor a)  →  extflonum?\n  a : extflonum?\n\n(extflceiling a)  →  extflonum?\n  a : extflonum?\n\n(extfltruncate a)  →  extflonum?\n  a : extflonum?\n```"} {"text": "# 4.3.5 Extflonums\nLike flround, flfloor, flceiling, and fltruncate, but for extflonums.\n> ```\n(extflsin a)  →  extflonum?\n  a : extflonum?\n(extflcos a)  →  extflonum?\n  a : extflonum?\n(extfltan a)  →  extflonum?\n  a : extflonum?\n(extflasin a)  →  extflonum?\n  a : extflonum?\n(extflacos a)  →  extflonum?\n  a : extflonum?\n(extflatan a)  →  extflonum?\n  a : extflonum?\n(extfllog a)  →  extflonum?\n  a : extflonum?\n(extflexp a)  →  extflonum?\n  a : extflonum?\n(extflsqrt a)  →  extflonum?\n  a : extflonum?\n(extflexpt a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?```\nLike [flsin](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flsin%29%29), [flcos](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flcos%29%29), [fltan](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fltan%29%29), [flasin](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flasin%29%29), [flacos](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flacos%29%29), [flatan](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flatan%29%29), [fllog](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fllog%29%29), [flexp](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flexp%29%29), and [flsqrt](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flsqrt%29%29), and [flexpt](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flexpt%29%29), but for [extflonums](#%28tech._extflonum%29).\n> ```\n( → extfl a)  →  extflonum?\n  a : exact-integer?\n(extfl → exact-integer a)  →  exact-integer?\n  a : extflonum?"} {"text": "# 4.3.5 Extflonums\n(real → extfl a)  →  extflonum?\n  a : real?\n(extfl → exact a)  →  (and/c real? exact?)\n  a : extflonum?\n(extfl → fx a)  →  fixnum?\n  a : extflonum?\n(fx → extfl a)  →  extflonum?\n  a : fixnum?\n(extfl → inexact a)  →  flonum?\n  a : extflonum?\n```\nThe first six are like → fl, fl → exact-integer, real → double-flonum, inexact → exact, fl → fx, and fx → fl, but for extflonums. The extfl → inexact function converts a extflonum to its closest flonum approximation.\n\nChanged in version 7.7.0.8 of package base: Changed extfl → fx to truncate.\n\n##### 4.3.5.2 Extflonum Constants\n\n>
\n\n

value

\n\n

pi.t : extflonum?

\n\nLike pi, but with 80 bits precision.\n\n##### 4.3.5.3 Extflonum Vectors\n\nAn extflvector is like an flvector, but it holds only extflonums. See also Unsafe Extflonum Operations.\n\nTwo extflvectors are equal? if they have the same length, and if the values in corresponding slots of the extflvectors are equal?.\n\n> ```\n(extflvector? v) → boolean?\n  v : any/c\n\n(extflvector x ...)  →  extflvector?\n  x : extflonum?\n\n(make-extflvector size [x)  →  extflvector?\n  size : exact-nonnegative-integer?\n  x : extflonum? = 0.0t0\n\n(extflvector-length vec)  →  exact-nonnegative-integer?\n  vec : extflvector?\n\n(extflvector-ref vec pos)  →  extflonum?\n  vec : extflvector?\n  pos : exact-nonnegative-integer?\n\n(extflvector-set! vec pos x)  →  extflonum?\n  vec : extflvector?\n  pos : exact-nonnegative-integer?\n  x : extflonum?\n\n(extflvector-copy vec [start end)  →  extflvector?\n  vec : extflvector?\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (vector-length v)```\n\n\nLike [flvector?](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flvector~3f%29%29), [flvector](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flvector%29%29), [make-flvector](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._make-flvector%29%29), [flvector-length](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flvector-length%29%29), [flvector-ref](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flvector-ref%29%29), flvector-set, and [flvector-copy](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flvector-copy%29%29), but for [extflvectors](#%28tech._extflvector%29).\n\n> ```\n(in-extflvector vec [start stop step) → sequence?\n  vec : extflvector?\n  start : exact-nonnegative-integer? = 0\n  stop : (or/c exact-integer? #f) = #f\n  step : (and/c exact-integer? (not/c zero?)) = 1\n\nsyntax\n\n(for/extflvector maybe-length (for-clause ...) body ...)\n\nsyntax\n\n(for*/extflvector maybe-length (for-clause ...) body ...)\n \nmaybe-length   =  \n    |   #:length length-expr\n    |   #:length length-expr #:fill fill-expr\n\n \n   length-expr   :   exact-nonnegative-integer?\n   fill-expr   :   extflonum?\n```"} {"text": "# 4.3.5 Extflonums\nLike in-flvector, for/flvector, and for*/flvector, but for extflvectors.\n> ```\n(shared-extflvector x ...) → extflvector?\n  x : extflonum?\n(make-shared-extflvector size [x)  →  extflvector?\n  size : exact-nonnegative-integer?\n  x : extflonum? = 0.0t0```\nLike [shared-flvector](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._shared-flvector%29%29) and [make-shared-flvector](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._make-shared-flvector%29%29), but for [extflvectors](#%28tech._extflvector%29)."} {"text": "##### 4.3.5.4 Extflonum Byte Strings\n> ```\n(floating-point-bytes → extfl bstr\n   [ big-endian?        \n    start        \n    end)   →   extflonum?\n  bstr : bytes?\n  big-endian? : any/c = (system-big-endian?)\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (bytes-length bstr)\n```\nLike floating-point-bytes → real, but for extflonums: Converts the extended-precision floating-point number encoded in bstr from position start (inclusive) to end (exclusive) to an extflonum. The difference between start an end must be 10 bytes.\n\n> ```\n(extfl → floating-point-bytes x\n   [ big-endian?        \n    dest-bstr        \n    start)   →   bytes?\n\n  x : extflonum?\n  big-endian? : any/c = (system-big-endian?)\n   dest-bstr   :   (and/c bytes? (not/c immutable?))\n      =   (make-bytes 10)\n\n  start : exact-nonnegative-integer? = 0```\n\n\nLike [real->floating-point-bytes](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._real-~3efloating-point-bytes%29%29), but for [extflonums](#%28tech._extflonum%29): Converts x to its representation in a byte string of length 10.\n\n------------------------------------------------------------------------\n\n# 4.4 Strings\n\n### 4.4 Strings\n\n> > > \"+\"[Strings (Unicode)](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=strings.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces strings.\n\nA string is a fixed-length array of [characters](characters.html).\n\nA string can be mutable or immutable. When an immutable string is provided to a procedure like [string-set!](#%28def._%28%28quote._~23~25kernel%29._string-set%21%29%29), the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. String constants generated by the default reader (see [Reading Strings](reader.html#%28part._parse-string%29)) are immutable, and they are [interned](reader.html#%28tech._interned%29) in [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29) mode. Use [immutable?](booleans.html#%28def._%28%28quote._~23~25kernel%29._immutable~3f%29%29) to check whether a string is immutable.\n\nTwo strings are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) when they have the same length and contain the same sequence of characters.\n\nA string can be used as a single-valued sequence (see [Sequences](sequences.html)). The characters of the string serve as elements of the sequence. See also [in-string](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-string%29%29).\n\nSee [Reading Strings](reader.html#%28part._parse-string%29) for information on [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29)ing strings and [Printing Strings](printing.html#%28part._print-string%29) for information on [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29)ing strings.\n\nSee also: [immutable?](booleans.html#%28def._%28%28quote._~23~25kernel%29._immutable~3f%29%29), [symbol->string](symbols.html#%28def._%28%28quote._~23~25kernel%29._symbol-~3estring%29%29), [bytes->string/utf-8](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._bytes-~3estring%2Futf-8%29%29).\n\n#### 4.4.1 String Constructors, Selectors, and Mutators\n\n> ```\n(string? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 4.3.5 Extflonums\nReturns #t if v is a string, #f otherwise.\nSee also immutable-string? and mutable-string?.\nExamples:\n> ```racket\n> > ( string? \"Apple\" )\n> #t\n> > ( string? ' apple )\n> #f\n> ```\n> ```\n(make-string k [char) → string?\n  k : exact-nonnegative-integer?\n  char : char? = #\\nul```\nReturns a new mutable string of length k where each position in the string is initialized with the character char.\nExample:\n> ```racket\n> > ( make-string 5 #\\z )\n> \"zzzzz\"\n> ```\n> ```\n(string char ...) → string?\n  char : char?\n```\n\n\nReturns a new mutable string whose length is the number of provided chars, and whose positions are initialized with the given chars.\n\nExample:\n\n> ```racket\n> > ( string #\\A #\\p #\\p #\\l #\\e )\n> \"Apple\"\n> ```\n\n> ```\n(string → immutable-string str)  →  (and/c string? immutable?)\n  str : string?\n```\nReturns an immutable string with the same content as str, returning str itself if str is immutable.\nExamples:\n> ```racket\n> > ( immutable? ( string #\\H #\\e #\\l #\\l #\\o ) )\n> #f\n> > ( immutable? ( string->immutable-string ( string #\\H #\\e #\\l #\\l #\\o ) ) )\n> #t\n> ```\n> ```\n(string-length str)  →  exact-nonnegative-integer?\n  str : string?\n```\n\n\nReturns the length of str.\n\nExample:\n\n> ```racket\n> > ( string-length \"Apple\" )\n> 5\n> ```\n\n> ```\n(string-ref str k)  →  char?\n  str : string?\n  k : exact-nonnegative-integer?\n```"} {"text": "# 4.3.5 Extflonums\nReturns the character at position k in str. The first position in the string corresponds to 0, so the position k must be less than the length of the string, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nExample:\n> ```racket\n> > ( string-ref \"Apple\" 0 )\n> #\\A\n> ```\n> ```\n(parameter)\t→\t\n(-> and/c string? (not/c immutable?))\n```\nChanges the character position k in str to char. The first position in the string corresponds to 0, so the position k must be less than the length of the string, otherwise the exn:fail:contract exception is raised.\n\nExamples:\n\n> ```racket\n> > ( define s ( string #\\A #\\p #\\p #\\l #\\e ) )\n> > ( string-set! s 4 #\\y )\n> > s\n> \"Apply\"\n> ```\n\n> ```\n(substring str start [end) → string?\n  str : string?\n  start : exact-nonnegative-integer?\n  end : exact-nonnegative-integer? = (string-length str)```\n\n\nReturns a new mutable string that is ([-](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._-%29%29) end start) characters long, and that contains the same characters as str from start inclusive to end exclusive. The first position in a string corresponds to 0, so the start and end arguments must be less than or equal to the length of str, and end must be greater than or equal to start, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nExamples:\n\n> ```racket\n> > ( substring \"Apple\" 1 3 )\n> \"pp\"\n> > ( substring \"Apple\" 1 )\n> \"pple\"\n> ```\n\n> ```\n(string-copy str)  →  string?\n  str : string?\n```"} {"text": "# 4.3.5 Extflonums\n(parameter)\t→\t\n(-> and/c string? (not/c immutable?))```\nChanges the characters of dest starting at position dest-start to match the characters in src from src-start (inclusive) to src-end (exclusive), where the first position in a string corresponds to 0. The strings dest and src can be the same string, and in that case the destination region can overlap with the source region; the destination characters after the copy match the source characters from before the copy. If any of dest-start, src-start, or src-end are out of range (taking into account the sizes of the strings and the source and destination regions), the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nExamples:\n> ```racket\n> > ( define s ( string #\\A #\\p #\\p #\\l #\\e ) )\n> > ( string-copy! s 4 \"y\" )\n> > ( string-copy! s 0 s 3 4 )\n> > s\n> \"lpply\"\n> ```\n> ```\n(parameter)\t→\t\n(-> and/c string? (not/c immutable?))"} {"text": "# 4.3.5 Extflonums\n```\nChanges dest so that every position in the string is filled with char.\n\nExamples:\n\n> ```racket\n> > ( define s ( string #\\A #\\p #\\p #\\l #\\e ) )\n> > ( string-fill! s #\\q )\n> > s\n> \"qqqqq\"\n> ```\n\n> ```\n(string-append str ...) → string?\n  str : string?```\n\n\nReturns a new mutable string that is as long as the sum of the given strs’ lengths, and that contains the concatenated characters of the given strs. If no strs are provided, the result is a zero-length string.\n\nExample:\n\n> ```racket\n> > ( string-append \"Apple\" \"Banana\" )\n> \"AppleBanana\"\n> ```\n\n> ```\n(string-append-immutable str ...) → (and/c string? immutable?)\n  str : string?\n```\nThe same as string-append, but the result is an immutable string.\nExamples:\n> ```racket\n> > ( string-append-immutable \"Apple\" \"Banana\" )\n> \"AppleBanana\"\n> > ( immutable? ( string-append-immutable \"A\" \"B\" ) )\n> #t\n> ```\nAdded in version 7.5.0.14 of package base.\n> ```\n(string → list str)  →  (listof char?)\n  str : string?```\nReturns a new list of characters corresponding to the content of str. That is, the length of the list is ([string-length](#%28def._%28%28quote._~23~25kernel%29._string-length%29%29) str), and the sequence of characters in str is the same sequence in the result list.\nExample:\n> ```racket\n> > ( string->list \"Apple\" )\n> '(#\\A #\\p #\\p #\\l #\\e)\n> ```\n> ```\n(list → string lst)  →  string?\n  lst : (listof char?)"} {"text": "# 4.3.5 Extflonums\n```\nReturns a new mutable string whose content is the list of characters in lst. That is, the length of the string is (length lst), and the sequence of characters in lst is the same sequence in the result string.\n\nExample:\n\n> ```racket\n> > ( list → string ( list #\\A #\\p #\\p #\\l #\\e ) )\n> \"Apple\"\n> ```\n\n> ```\n(build-string n proc)  →  string?\n  n : exact-nonnegative-integer?\n  proc : (exact-nonnegative-integer? . → . char?)```\n\n\nCreates a string of n characters by applying proc to the integers from 0 to ([sub1](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._sub1%29%29) n) in order. If str is the resulting string, then ([string-ref](#%28def._%28%28quote._~23~25kernel%29._string-ref%29%29) str i) is the character produced by (proc i).\n\nExample:\n\n> ```racket\n> > ( build-string 5 ( lambda ( i ) ( integer->char ( + i 97 ) ) ) )\n> \"abcde\"\n> ```\n\n#### 4.4.2 String Comparisons\n\n> ```\n(string=? str1 str2 ...) → boolean?\n  str1 : string?\n  str2 : string?\n```\nReturns #t if all of the arguments are equal?.\nExamples:\n> ```racket\n> > ( string=? \"Apple\" \"apple\" )\n> #f\n> > ( string=? \"a\" \"as\" \"a\" )\n> #f\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n>
\n

procedure

\n

(string

  str1 : string?
  str2 : string?
"} {"text": "# 4.3.5 Extflonums\nReturns #t if the arguments are lexicographically sorted increasing, where individual characters are ordered by char ```racket\n> > ( string #t\n> > ( string #f\n> > ( string #t\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n>
\n

procedure

\n

(string<=? str1 str2 ...)  →  boolean?

  str1 : string?
  str2 : string?
\nLike string ```racket\n> > ( string<=? \"Apple\" \"apple\" )> #t\n> > ( string<=? \"apple\" \"Apple\" )> #f\n> > ( string<=? \"a\" \"b\" \"b\" )> #t\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n> ```\n(string>? str1 str2 ...) → boolean?\n  str1 : string?\n  str2 : string?```\nLike [string ```racket\n> > ( string>? \"Apple\" \"apple\" )\n> #f\n> > ( string>? \"apple\" \"Apple\" )\n> #t\n> > ( string>? \"c\" \"b\" \"a\" )\n> #t\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n> ```\n(string>=? str1 str2 ...) → boolean?\n  str1 : string?\n  str2 : string?"} {"text": "# 4.3.5 Extflonums\n```\nLike string ```racket\n> > ( string>=? \"Apple\" \"apple\" )\n> #f\n> > ( string>=? \"apple\" \"Apple\" )\n> #t\n> > ( string>=? \"c\" \"b\" \"b\" )\n> #t\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n> ```\n(string-ci=? str1 str2 ...) → boolean?\n  str1 : string?\n  str2 : string?```\n\n\nReturns #t if all of the arguments are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) after locale-insensitive case-folding via [string-foldcase](#%28def._%28%28quote._~23~25kernel%29._string-foldcase%29%29).\n\nExamples:\n\n> ```racket\n> > ( string-ci=? \"Apple\" \"apple\" )\n> #t\n> > ( string-ci=? \"a\" \"a\" \"a\" )\n> #t\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n>
\n\n

procedure

\n\n

([string-ci

  str1 : [string?](#%28def._%28%28quote._~23~25kernel%29._string~3f%29%29)
  str2 : [string?](#%28def._%28%28quote._~23~25kernel%29._string~3f%29%29)
\n\nLike [string ```racket\n> > ( string-ci #f\n> > ( string-ci #t\n> > ( string-ci #t\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n>
\n\n

procedure

\n\n

([string-ci<=?](#%28def._%28%28quote._~23~25kernel%29._string-ci~3c~3d~3f%29%29) str1 str2 ...) → [boolean?](booleans.html#%28def._%28%28quote._~23~25kernel%29._boolean~3f%29%29)

  str1 : [string?](#%28def._%28%28quote._~23~25kernel%29._string~3f%29%29)
  str2 : [string?](#%28def._%28%28quote._~23~25kernel%29._string~3f%29%29)
\n\nLike [string-ci ```racket\n> > ( string-ci<=? \"Apple\" \"apple\" )> #t\n> > ( string-ci<=? \"apple\" \"Apple\" )> #t\n> > ( string-ci<=? \"a\" \"b\" \"b\" )> #t\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n> ```\n(string-ci>? str1 str2 ...) → boolean?\n  str1 : string?\n  str2 : string?\n```"} {"text": "# 4.3.5 Extflonums\nLike string-ci ```racket\n> > ( string-ci>? \"Apple\" \"apple\" )\n> #f\n> > ( string-ci>? \"banana\" \"Apple\" )\n> #t\n> > ( string-ci>? \"c\" \"b\" \"a\" )\n> #t\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n> ```\n(string-ci>=? str1 str2 ...) → boolean?\n  str1 : string?\n  str2 : string?```\nLike [string-ci ```racket\n> > ( string-ci>=? \"Apple\" \"apple\" )\n> #t\n> > ( string-ci>=? \"apple\" \"Apple\" )\n> #t\n> > ( string-ci>=? \"c\" \"b\" \"b\" )\n> #t\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more."} {"text": "#### 4.4.3 String Conversions\n> ```\n(string-upcase str)  →  string?\n  str : string?\n```\n\n\nReturns a string whose characters are the upcase conversion of the characters in str. The conversion uses Unicode’s locale-independent conversion rules that map code-point sequences to code-point sequences (instead of simply mapping a 1-to-1 function on code points over the string), so the string produced by the conversion can be longer than the input string.\n\nExamples:\n\n> ```racket\n> > ( string-upcase \"abc!\" )\n> \"ABC!\"\n> > ( string-upcase \"Straße\" )\n> \"STRASSE\"\n> ```\n\n> ```\n(string-downcase string)  →  string?\n  string : string?\n```\nLike [string-upcase](#%28def._%28%28quote._~23~25kernel%29._string-upcase%29%29), but the downcase conversion.\nExamples:\n> ```racket\n> > ( string-downcase \"aBC!\" )\n> \"abc!\"\n> > ( string-downcase \"Straße\" )\n> \"straße\"\n> > ( string-downcase \"ΚΑΟΣ\" )\n> \"καος\"\n> > ( string-downcase \"Σ\" )\n> \"σ\"\n> ```\n> ```\n(string-titlecase string)  →  string?\n  string : string?"} {"text": "# 4.3.5 Extflonums\n```\nLike string-upcase, but the titlecase conversion only for the first character in each sequence of cased characters in str (ignoring case-ignorable characters).\n\nExamples:\n\n> ```racket\n> > ( string-titlecase \"aBC twO\" )\n> \"Abc Two\"\n> > ( string-titlecase \"y2k\" )\n> \"Y2k\"\n> > ( string-titlecase \"main straße\" )\n> \"Main Straße\"\n> > ( string-titlecase \"stra ße\" )\n> \"Stra Sse\"\n> ```\n\n> ```\n(string-foldcase string)  →  string?\n  string : string?```\n\n\nLike [string-upcase](#%28def._%28%28quote._~23~25kernel%29._string-upcase%29%29), but the case-folding conversion.\n\nExamples:\n\n> ```racket\n> > ( string-foldcase \"aBC!\" )\n> \"abc!\"\n> > ( string-foldcase \"Straße\" )\n> \"strasse\"\n> > ( string-foldcase \"ΚΑΟΣ\" )\n> \"καοσ\"\n> ```\n\n> ```\n(string-normalize-nfd string)  →  string?\n  string : string?\n```\nReturns a string that is the Unicode normalized form D of string. If the given string is already in the corresponding Unicode normal form, the string may be returned directly as the result (instead of a newly allocated string).\nExample:\n> ```racket\n> > ( equal? ( string-normalize-nfd \"Ç\" ) \"Ç\" )\n> #t\n> ```\n> ```\n(string-normalize-nfkd string)  →  string?\n  string : string?\n```\n\n\nLike [string-normalize-nfd](#%28def._%28%28quote._~23~25kernel%29._string-normalize-nfd%29%29), but for normalized form KD.\n\nExample:\n\n> ```racket\n> > ( equal? ( string-normalize-nfkd \"ℌ\" ) \"H\" )\n> #t\n> ```\n\n> ```\n(string-normalize-nfc string)  →  string?\n  string : string?\n```\nLike string-normalize-nfd, but for normalized form C.\nExample:"} {"text": "# 4.3.5 Extflonums\n> ```racket\n> > ( equal? ( string-normalize-nfc \"Ç\" ) \"Ç\" )\n> #t\n> ```\n> ```\n(string-normalize-nfkc string)  →  string?\n  string : string?```\nLike [string-normalize-nfd](#%28def._%28%28quote._~23~25kernel%29._string-normalize-nfd%29%29), but for normalized form KC.\nExample:\n> ```racket\n> > ( equal? ( string-normalize-nfkc \"ℋ̧\" ) \"Ḩ\" )\n> #t\n> ```"} {"text": "#### 4.4.4 Locale-Specific String Operations\n> ```\n(string-locale=? str1 str2 ...) → boolean?\n  str1 : string?\n  str2 : string?\n```\n(parameter)\t→\t\n(-> string-locale>? str1 str2 ...)```\n\n\nLike [string>?](#%28def._%28%28quote._~23~25kernel%29._string~3e~3f%29%29), but locale-specific like [string-locale ```\n(string-locale-ci=? str1 str2 ...) → boolean?\n  str1 : string?\n  str2 : string?\n```\nLike string-locale=?, but strings are compared using rules that are both locale-specific and case-insensitive (depending on what “case-insensitive” means for the current locale).\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n>
\n

procedure

\n

(string-locale-ci

  str1 : string?
  str2 : string?
\nLike string ```\n(string-locale-ci>? str1 str2 ...) → boolean?\n  str1 : string?\n  str2 : string?```"} {"text": "# 4.3.5 Extflonums\nLike [string>?](#%28def._%28%28quote._~23~25kernel%29._string~3e~3f%29%29), but both locale-sensitive and case-insensitive like [string-locale-ci=?](#%28def._%28%28quote._~23~25kernel%29._string-locale-ci~3d~3f%29%29).\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n> ```\n(string-locale-upcase string)  →  string?\n  string : string?\n```\n(parameter)\t→```\n\n\nLike [string-downcase](#%28def._%28%28quote._~23~25kernel%29._string-downcase%29%29), but using locale-specific case-conversion rules based on the value of [current-locale](encodings.html#%28def._%28%28quote._~23~25kernel%29._current-locale%29%29).\n\n#### 4.4.5 String Grapheme Clusters\n\n> ```\n(string-grapheme-span str start [end) → exact-nonnegative-integer?\n  str : string?\n  start : exact-nonnegative-integer?\n  end : exact-nonnegative-integer? = (string-length str)\n```\nReturns the number of characters (i.e., code points) in the string that form a Unicode grapheme cluster starting at start, assuming that start is the start of a grapheme cluster and extending no further than the character before end. The result is 0 if start equals end.\nThe start and end arguments must be valid indices as for substring, otherwise the exn:fail:contract exception is raised.\nSee also char-grapheme-cluster-step.\nExamples:"} {"text": "# 4.3.5 Extflonums\n> ```racket\n> > ( string-grapheme-span \"\" 0 )\n> 0\n> > ( string-grapheme-span \"a\" 0 )\n> 1\n> > ( string-grapheme-span \"ab\" 0 )\n> 1\n> > ( string-grapheme-span \"\\r\\n\" 0 )\n> 2\n> > ( string-grapheme-span \"\\r\\nx\" 0 )\n> 2\n> > ( string-grapheme-span \"\\r\\nx\" 2 )\n> 1\n> > ( string-grapheme-span \"\\r\\nx\" 0 1 )\n> 1\n> ```\nAdded in version 8.6.0.2 of package base.\n> ```\n(string-grapheme-count str start [end)\n  →  exact-nonnegative-integer?\n  str : string?\n  start : exact-nonnegative-integer?\n  end : exact-nonnegative-integer? = (string-length str)```\nReturns the number of grapheme clusters in ([substring](#%28def._%28%28quote._~23~25kernel%29._substring%29%29) str start end).\nThe start and end arguments must be valid indices as for [substring](#%28def._%28%28quote._~23~25kernel%29._substring%29%29), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nExamples:\n> ```racket\n> > ( string-grapheme-count \"\" )\n> 0\n> > ( string-grapheme-count \"a\" )\n> 1\n> > ( string-grapheme-count \"ab\" )\n> 2\n> > ( string-grapheme-count \"ab\" 0 2 )\n> 2\n> > ( string-grapheme-count \"ab\" 0 1 )\n> 1\n> > ( string-grapheme-count \"\\r\\n\" )\n> 1\n> > ( string-grapheme-count \"a\\r\\nb\" )\n> 3\n> ```\nAdded in version 8.6.0.2 of package base."} {"text": "#### 4.4.6 Additional String Functions\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/string](#%28mod-path._racket%2Fstring%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/string](#%28mod-path._racket%2Fstring%29) and [racket](index.html) libraries, but not [racket/base](index.html).\n> ```\n(string-append* str ... strs) → string?\n  str : string?\n  strs : (listof string?)"} {"text": "# 4.3.5 Extflonums\n```\nLike string-append, but the last argument is used as a list of arguments for string-append, so (string-append* str ... strs) is the same as (apply string-append str ... strs). In other words, the relationship between string-append and string-append* is similar to the one between list and list*.\n\nExamples:\n\n> ```racket\n> > ( string-append* \"a\" \"b\" ' ( \"c\" \"d\" ) )\n> \"abcd\"\n> > ( string-append* ( cdr ( append* ( map ( lambda ( x ) ( list \", \" x ) ) ' ( \"Alpha\" \"Beta\" \"Gamma\" ) ) ) ) )\n> \"Alpha, Beta, Gamma\"\n> ```\n\n> ```\n(string-join strs\n   [ sep        \n    #:before-first before-first        \n    #:before-last before-last        \n    #:after-last after-last)   →   string?\n\n  strs : (listof string?)\n  sep : string? = \" \"\n  before-first : string? = \"\"\n  before-last : string? = sep\n  after-last : string? = \"\"```\n\n\nAppends the strings in strs, inserting sep between each pair of strings in strs. before-last, before-first, and after-last are analogous to the inputs of [add-between](pairs.html#%28def._%28%28lib._racket%2Flist..rkt%29._add-between%29%29): they specify an alternate separator between the last two strings, a prefix string, and a suffix string respectively.\n\nExamples:\n\n> ```racket\n> > ( string-join ' ( \"one\" \"two\" \"three\" \"four\" ) )\n> \"one two three four\"\n> > ( string-join ' ( \"one\" \"two\" \"three\" \"four\" ) \", \" )\n> \"one, two, three, four\"\n> > ( string-join ' ( \"one\" \"two\" \"three\" \"four\" ) \" potato \" )\n> \"one potato two potato three potato four\"\n> > ( string-join ' ( \"x\" \"y\" \"z\" ) \", \" #:before-first \"Todo: \" #:before-last \" and \" #:after-last \".\" )\n> \"Todo: x, y and z.\"\n> ```\n\n> ```\n(string-normalize-spaces str\n   [ sep        \n    space        \n    #:trim? trim?        \n    #:repeat? repeat?)   →   string?\n\n  str : string?\n  sep : (or/c string? regexp?) = #px\"\\\\s+\"\n  space : string? = \" \"\n  trim? : any/c = #t\n  repeat? : any/c = #f\n```"} {"text": "# 4.3.5 Extflonums\nNormalizes spaces in the input str by trimming it (using string-trim and sep) and replacing all whitespace sequences in the result with space, which defaults to a single space.\nExample:\n> ```racket\n> > ( string-normalize-spaces \" foo bar baz \\r\\n\\t\" )\n> \"foo bar baz\"\n> ```\nThe result of (string-normalize-spaces str sep space) is the same as (string-join (string-split str sep ....) space).\n> ```\n(string-replace str from to [#:all? all?) → string?\n  str : string?\n  from : (or/c string? regexp?)\n  to : string?\n  all? : any/c = #t```\nReturns str with all occurrences of from replaced with by to. If from is a string, it is matched literally (as opposed to being used as a [regular expression](regexp.html#%28tech._regular._expression%29)).\nBy default, all occurrences are replaced, but only the first match is replaced if all? is #f.\nExample:\n> ```racket\n> > ( string-replace \"foo bar baz\" \"bar\" \"blah\" )\n> \"foo blah baz\"\n> ```\n> ```\n(string-split str\n   [ sep        \n    #:trim? trim?        \n    #:repeat? repeat?)   →   (listof string?)\n  str : string?\n  sep : (or/c string? regexp?) = #px\"\\\\s+\"\n  trim? : any/c = #t\n  repeat? : any/c = #f"} {"text": "# 4.3.5 Extflonums\n```\nSplits the input str on sep, returning a list of substrings of str that are separated by sep, defaulting to splitting the input on whitespaces. The input is first trimmed using sep (see string-trim), unless trim? is #f. Empty matches are handled in the same way as for regexp-split. As a special case, if str is the empty string after trimming, the result is '() instead of '(\"\").\n\nLike string-trim, provide sep to use a different separator, and repeat? controls matching repeated sequences.\n\nExamples:\n\n> ```racket\n> > ( string-split \" foo bar baz \\r\\n\\t\" )\n> '(\"foo\" \"bar\" \"baz\")\n> > ( string-split \" \" )\n> '()\n> > ( string-split \" \" #:trim? #f )\n> '(\"\" \"\")\n> ```\n\n> ```\n(string-trim str\n   [ sep        \n    #:left? left?        \n    #:right? right?        \n    #:repeat? repeat?)   →   string?\n\n  str : string?\n  sep : (or/c string? regexp?) = #px\"\\\\s+\"\n  left? : any/c = #t\n  right? : any/c = #t\n  repeat? : any/c = #f```\n\n\nTrims the input str by removing prefix and suffix sep, which defaults to whitespace. A string sep is matched literally (as opposed to being used as a [regular expression](regexp.html#%28tech._regular._expression%29)).\n\nUse #:left? #f or #:right? #f to suppress trimming the corresponding side. When repeat? is #f (the default), only one match is removed from each side; when repeat? is true, all initial or trailing matches are trimmed (which is an alternative to using a [regular expression](regexp.html#%28tech._regular._expression%29) sep that contains +).\n\nExamples:\n\n> ```racket\n> > ( string-trim \" foo bar baz \\r\\n\\t\" )\n> \"foo bar baz\"\n> > ( string-trim \" foo bar baz \\r\\n\\t\" \" \" #:repeat? #t )\n> \"foo bar baz \\r\\n\\t\"\n> > ( string-trim \"aaaxaayaa\" \"aa\" )\n> \"axaay\"\n> ```\n\n> ```\n(non-empty-string? x)  →  boolean?\n  x : any/c\n```"} {"text": "# 4.3.5 Extflonums\nReturns #t if x is a string and is not empty; returns #f otherwise.\nAdded in version 6.3 of package base.\n> ```\n(string-find s contained)  →  (or/c exact-nonnegative-integer? #f)\n  s : string?\n  contained : string?\n(string-contains? s contained)  →  boolean?\n  s : string?\n  contained : string?\n(string-prefix? s prefix)  →  boolean?\n  s : string?\n  prefix : string?\n(string-suffix? s suffix)  →  boolean?\n  s : string?\n  suffix : string?\n```\n\n\nChecks whether s includes at any location, starts with, or ends with the second argument, respectively. The [string-find](#%28def._%28%28lib._racket%2Fstring..rkt%29._string-find%29%29) function returns the first position within s where contained is found, if any, while [string-contains?](#%28def._%28%28lib._racket%2Fstring..rkt%29._string-contains~3f%29%29) reports only whether it was found.\n\nExamples:\n\n> ```racket\n> > ( string-prefix? \"Racket\" \"R\" )\n> #t\n> > ( string-prefix? \"Jacket\" \"R\" )\n> #f\n> > ( string-suffix? \"Racket\" \"et\" )\n> #t\n> > ( string-find \"Racket\" \"ack\" )\n> 1\n> > ( string-contains? \"Racket\" \"ack\" )\n> #t\n> ```\n\nAdded in version 6.3 of package base. \nChanged in version 8.15.0.7: Added [string-find](#%28def._%28%28lib._racket%2Fstring..rkt%29._string-find%29%29).\n\n#### 4.4.7 Converting Values to Strings\n\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/format](#%28mod-path._racket%2Fformat%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/format](#%28mod-path._racket%2Fformat%29) and [racket](index.html) libraries, but not [racket/base](index.html).\n\nThe [racket/format](#%28mod-path._racket%2Fformat%29) library provides functions for converting Racket values to strings. In addition to features like padding and numeric formatting, the functions have the virtue of being shorter than [format](Writing.html#%28def._%28%28quote._~23~25kernel%29._format%29%29) (with format string), [number->string](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._number-~3estring%29%29), or [string-append](#%28def._%28%28quote._~23~25kernel%29._string-append%29%29).\n\n> ```\n(~a   v        \n    ...        \n   [ #:separator separator        \n    #:width width        \n    #:max-width max-width        \n    #:min-width min-width        \n    #:limit-marker limit-marker        \n    #:limit-prefix? limit-prefix?        \n    #:align align        \n    #:pad-string pad-string        \n    #:left-pad-string left-pad-string        \n    #:right-pad-string right-pad-string)   →   string?\n\n  v : any/c\n  separator : string? = \"\"\n  width : (or/c exact-nonnegative-integer? #f) = #f\n   max-width   :   (or/c exact-nonnegative-integer? +inf.0)\n      =   (or width +inf.0)\n\n  min-width : exact-nonnegative-integer? = (or width 0)\n  limit-marker : string? = \"\"\n  limit-prefix? : boolean? = #f\n  align : (or/c 'left 'center 'right) = 'left\n  pad-string : non-empty-string? = \" \"\n  left-pad-string : non-empty-string? = pad-string\n  right-pad-string : non-empty-string? = pad-string\n```"} {"text": "# 4.3.5 Extflonums\nConverts each v to a string in [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29) mode—that is, like ([format](Writing.html#%28def._%28%28quote._~23~25kernel%29._format%29%29) \"\\~a\" v)—then concatenates the results with separator between consecutive items, and then pads or truncates the string to be at least min-width characters and at most max-width characters.\nExamples:\n> ```racket\n> > ( ~a \"north\" )\n> \"north\"\n> > ( ~a ' south )\n> \"south\"\n> > ( ~a #\"east\" )\n> \"east\"\n> > ( ~a #\\w \"e\" ' st )\n> \"west\"\n> > ( ~a ( list \"red\" ' green #\"blue\" ) )\n> \"(red green blue)\"\n> > ( ~a 17 )\n> \"17\"\n> > ( ~a #e1e20 )\n> \"100000000000000000000\"\n> > ( ~a pi )\n> \"3.141592653589793\"\n> > ( ~a ( expt 6.1 87 ) )\n> \"2.1071509386211452e+68\"\n> ```\nThe [~a](#%28def._%28%28lib._racket%2Fformat..rkt%29._~7ea%29%29) function is primarily useful for strings, numbers, and other atomic data. The [~v](#%28def._%28%28lib._racket%2Fformat..rkt%29._~7ev%29%29) and [~s](#%28def._%28%28lib._racket%2Fformat..rkt%29._~7es%29%29) functions are better suited to compound data.\nLet s be the concatenated string forms of the vs plus separators. If s is longer than max-width characters, it is truncated to exactly max-width characters. If s is shorter than min-width characters, it is padded to exactly min-width characters. Otherwise s is returned unchanged. If min-width is greater than max-width, an exception is raised."} {"text": "# 4.3.5 Extflonums\nIf s is longer than max-width characters, it is truncated and the end of the string is replaced with limit-marker. If limit-marker is longer than max-width, an exception is raised. If limit-prefix? is #t, the beginning of the string is truncated instead of the end.\nExamples:\n> ```racket\n> > ( ~a \"abcde\" #:max-width 5 )\n> \"abcde\"\n> > ( ~a \"abcde\" #:max-width 4 )\n> \"abcd\"\n> > ( ~a \"abcde\" #:max-width 4 #:limit-marker \"*\" )\n> \"abc*\"\n> > ( ~a \"abcde\" #:max-width 4 #:limit-marker \"...\" )\n> \"a...\"\n> > ( ~a \"The quick brown fox\" #:max-width 15 #:limit-marker \"\" )\n> \"The quick brown\"\n> > ( ~a \"The quick brown fox\" #:max-width 15 #:limit-marker \"...\" )\n> \"The quick br...\"\n> > ( ~a \"The quick brown fox\" #:max-width 15 #:limit-marker \"...\" #:limit-prefix? #f )\n> \"The quick br...\"\n> ```\nIf s is shorter than min-width, it is padded to at least min-width characters. If align is 'left, then only right padding is added; if align is 'right, then only left padding is added; and if align is 'center, then roughly equal amounts of left padding and right padding are added.\nPadding is specified as a non-empty string. Left padding consists of left-pad-string repeated in its entirety as many times as possible followed by a prefix of left-pad-string to fill the remaining space. In contrast, right padding consists of a suffix of right-pad-string followed by a number of copies of right-pad-string in its entirety. Thus left padding starts with the start of left-pad-string and right padding ends with the end of right-pad-string.\nExamples:"} {"text": "# 4.3.5 Extflonums\n> ```racket\n> > ( ~a \"apple\" #:min-width 20 #:align ' left )\n> \"apple \"\n> > ( ~a \"pear\" #:min-width 20 #:align ' left #:right-pad-string \" .\" )\n> \"pear . . . . . . . .\"\n> > ( ~a \"plum\" #:min-width 20 #:align ' right #:left-pad-string \". \" )\n> \". . . . . . . . plum\"\n> > ( ~a \"orange\" #:min-width 20 #:align ' center #:left-pad-string \"- \" #:right-pad-string \" -\" )\n> \"- - - -orange- - - -\"\n> ```\nUse width to set both max-width and min-width simultaneously, ensuring that the resulting string is exactly width characters long:\n> ```racket\n> > ( ~a \"terse\" #:width 6 )\n> \"terse \"\n> > ( ~a \"loquacious\" #:width 6 )\n> \"loquac\"\n> ```\n> ```\n(~v   v        \n    ...        \n   [ #:separator separator        \n    #:width width        \n    #:max-width max-width        \n    #:min-width min-width        \n    #:limit-marker limit-marker        \n    #:limit-prefix? limit-prefix?        \n    #:align align        \n    #:pad-string pad-string        \n    #:left-pad-string left-pad-string        \n    #:right-pad-string right-pad-string)   →   string?\n  v : any/c\n  separator : string? = \" \"\n  width : (or/c exact-nonnegative-integer? #f) = #f\n   max-width   :   (or/c exact-nonnegative-integer? +inf.0)\n      =   (or width +inf.0)\n  min-width : exact-nonnegative-integer? = (or width 0)\n  limit-marker : string? = \"...\"\n  limit-prefix? : boolean? = #f\n  align : (or/c 'left 'center 'right) = 'left\n  pad-string : non-empty-string? = \" \"\n  left-pad-string : non-empty-string? = pad-string\n  right-pad-string : non-empty-string? = pad-string"} {"text": "# 4.3.5 Extflonums\n```\n\n\nLike [~a](#%28def._%28%28lib._racket%2Fformat..rkt%29._~7ea%29%29), but each value is converted like ([format](Writing.html#%28def._%28%28quote._~23~25kernel%29._format%29%29) \"\\~v\" v), the default separator is \" \", and the default limit marker is \"...\".\n\nExamples:\n\n> ```racket\n> > ( ~v \"north\" )\n> \"\\\"north\\\"\"\n> > ( ~v ' south )\n> \"'south\"\n> > ( ~v #\"east\" )\n> \"#\\\"east\\\"\"\n> > ( ~v #\\w )\n> \"#\\\\w\"\n> > ( ~v ( list \"red\" ' green #\"blue\" ) )\n> \"'(\\\"red\\\" green #\\\"blue\\\")\"\n> ```\n\nUse [~v](#%28def._%28%28lib._racket%2Fformat..rkt%29._~7ev%29%29) to produce text that talks about Racket values.\n\nExample:\n\n> ```racket\n> > ( let ( [ nums ( for/list ( [ i 10 ] ) i ) ] ) ( ~a \"The even numbers in \" ( ~v nums ) \" are \" ( ~v ( filter even? nums ) ) \".\" ) )\n> \"The even numbers in '(0 1 2 3 4 5 6 7 8 9) are '(0 2 4 6 8).\"\n> ```\n\n> ```\n(~s   v        \n    ...        \n   [ #:separator separator        \n    #:width width        \n    #:max-width max-width        \n    #:min-width min-width        \n    #:limit-marker limit-marker        \n    #:limit-prefix? limit-prefix?        \n    #:align align        \n    #:pad-string pad-string        \n    #:left-pad-string left-pad-string        \n    #:right-pad-string right-pad-string)   →   string?\n\n  v : any/c\n  separator : string? = \" \"\n  width : (or/c exact-nonnegative-integer? #f) = #f\n   max-width   :   (or/c exact-nonnegative-integer? +inf.0)\n      =   (or width +inf.0)\n\n  min-width : exact-nonnegative-integer? = (or width 0)\n  limit-marker : string? = \"...\"\n  limit-prefix? : boolean? = #f\n  align : (or/c 'left 'center 'right) = 'left\n  pad-string : non-empty-string? = \" \"\n  left-pad-string : non-empty-string? = pad-string\n  right-pad-string : non-empty-string? = pad-string\n```"} {"text": "# 4.3.5 Extflonums\nLike [~a](#%28def._%28%28lib._racket%2Fformat..rkt%29._~7ea%29%29), but each value is converted like ([format](Writing.html#%28def._%28%28quote._~23~25kernel%29._format%29%29) \"\\~s\" v), the default separator is \" \", and the default limit marker is \"...\".\nExamples:\n> ```racket\n> > ( ~s \"north\" )\n> \"\\\"north\\\"\"\n> > ( ~s ' south )\n> \"south\"\n> > ( ~s #\"east\" )\n> \"#\\\"east\\\"\"\n> > ( ~s #\\w )\n> \"#\\\\w\"\n> > ( ~s ( list \"red\" ' green #\"blue\" ) )\n> \"(\\\"red\\\" green #\\\"blue\\\")\"\n> ```\n> ```\n(~e   v        \n    ...        \n   [ #:separator separator        \n    #:width width        \n    #:max-width max-width        \n    #:min-width min-width        \n    #:limit-marker limit-marker        \n    #:limit-prefix? limit-prefix?        \n    #:align align        \n    #:pad-string pad-string        \n    #:left-pad-string left-pad-string        \n    #:right-pad-string right-pad-string)   →   string?\n  v : any/c\n  separator : string? = \" \"\n  width : (or/c exact-nonnegative-integer? #f) = #f\n   max-width   :   (or/c exact-nonnegative-integer? +inf.0)\n      =   (or width +inf.0)\n  min-width : exact-nonnegative-integer? = (or width 0)\n  limit-marker : string? = \"...\"\n  limit-prefix? : boolean? = #f\n  align : (or/c 'left 'center 'right) = 'left\n  pad-string : non-empty-string? = \" \"\n  left-pad-string : non-empty-string? = pad-string\n  right-pad-string : non-empty-string? = pad-string"} {"text": "# 4.3.5 Extflonums\n```\n\n\nLike [~a](#%28def._%28%28lib._racket%2Fformat..rkt%29._~7ea%29%29), but each value is converted like ([format](Writing.html#%28def._%28%28quote._~23~25kernel%29._format%29%29) \"\\~e\" v), the default separator is \" \", and the default limit marker is \"...\".\n\nExamples:\n\n> ```racket\n> > ( ~e \"north\" )\n> \"\\\"north\\\"\"\n> > ( ~e ' south )\n> \"'south\"\n> > ( ~e #\"east\" )\n> \"#\\\"east\\\"\"\n> > ( ~e #\\w )\n> \"#\\\\w\"\n> > ( ~e ( list \"red\" ' green #\"blue\" ) )\n> \"'(\\\"red\\\" green #\\\"blue\\\")\"\n> ```\n\n> ```\n(~r   x        \n   [ #:sign sign        \n    #:base base        \n    #:precision precision        \n    #:notation notation        \n    #:format-exponent format-exponent        \n    #:min-width min-width        \n    #:pad-string pad-string        \n    #:groups groups        \n    #:group-sep group-sep        \n    #:decimal-sep decimal-sep)   →   string?\n\n  x : rational?\n   sign   :   ( or/c #f ' + ' ++ ' parens\n> ( let ( [ ind ( or/c string? ( list/c string? string? ) ) ] )\n> ( list/c ind ind ind ) ) )\n      =   #f\n\n   base   :   (or/c (integer-in 2 36) (list/c 'up (integer-in 2 36)))\n      =   10\n\n   precision   :   ( or/c exact-nonnegative-integer?\n> ( list/c ' = exact-nonnegative-integer? ) )   =   6\n\n   notation   :   ( or/c ' positional ' exponential\n> ( → rational? ( or/c ' positional ' exponential ) ) )\n      =   'positional\n\n   format-exponent   :   (or/c #f string? ( →  exact-integer? string?))\n      =   #f\n\n  min-width : exact-positive-integer? = 1\n  pad-string : non-empty-string? = \" \"\n  groups : (non-empty-listof exact-positive-integer?) = '(3)\n  group-sep : string? = \"\"\n  decimal-sep : string? = \".\"\n```"} {"text": "# 4.3.5 Extflonums\nConverts the rational number x to a string in either positional or exponential notation, depending on notation. The exactness or inexactness of x does not affect its formatting.\nThe optional arguments control number formatting:\n- notation — determines whether the number is printed in positional or exponential notation. If notation is a function, it is applied to x to get the notation to be used.\nExamples:\n> ```racket\n> > ( ~r 12345 )\n> \"12345\"\n> > ( ~r 12345 #:notation ' exponential )\n> \"1.2345e+04\"\n> > ( let ( [ pick-notation ( lambda ( x ) ( if ( or ( < ( abs x ) 0.001 ) (> ( abs x ) 1000 ) ) ' exponential ' positional ) ) ] ) ( for/list ( [ i ( in-range 1 5 ) ] ) ( ~r ( expt 17 i ) #:notation pick-notation ) ) )\n> '(\"17\" \"289\" \"4.913e+03\" \"8.3521e+04\")\n> ```\n- precision — controls the number of digits after the decimal point (or more accurately, the radix point). When x is formatted in exponential form, precision applies to the significand.\nIf precision is a natural number, then up to precision digits are displayed, but trailing zeroes are dropped, and if all digits after the decimal point are dropped the decimal point is also dropped. If precision is (list '= digits), then exactly digits digits after the decimal point are used, and the decimal point is never dropped.\nExamples:"} {"text": "# 4.3.5 Extflonums\n> ```racket\n> > ( ~r pi )\n> \"3.141593\"\n> > ( ~r pi #:precision 4 )\n> \"3.1416\"\n> > ( ~r pi #:precision 0 )\n> \"3\"\n> > ( ~r 1.5 #:precision 4 )\n> \"1.5\"\n> > ( ~r 1.5 #:precision ' ( = 4 ) )\n> \"1.5000\"\n> > ( ~r 50 #:precision 2 )\n> \"50\"\n> > ( ~r 50 #:precision ' ( = 2 ) )\n> \"50.00\"\n> > ( ~r 50 #:precision ' ( = 0 ) )\n> \"50.\"\n> ```\n- decimal-sep specifies what decimal separator is printed.\nExamples:\n> ```racket\n> > ( ~r 123.456 )\n> \"123.456\"\n> > ( ~r 123.456 #:decimal-sep \",\" )\n> \"123,456\"\n> ```\n- groups controls how digits of the integral part of the number are separated into groups. Rightmost numbers of groups are used to group rightmost digits of the integral part. The leftmost number of groups is used repeatedly to group leftmost digits. The group-sep argument specifies which separator to use between digit groups.\nExamples:\n> ```racket\n> > ( ~r 1234567890 #:groups ' ( 3 ) #:group-sep \",\" )\n> \"1,234,567,890\"\n> > ( ~r 1234567890 #:groups ' ( 3 2 ) #:group-sep \",\" )\n> \"12,345,678,90\"\n> > ( ~r 1234567890 #:groups ' ( 1 3 2 ) #:group-sep \"_\" )\n> \"1_2_3_4_5_678_90\"\n> ```\n- min-width — if x would normally be printed with fewer than min-width digits (including the decimal point but not including the sign indicator), the digits are left-padded using pad-string.\nExamples:"} {"text": "# 4.3.5 Extflonums\n> ```racket\n> > ( ~r 17 )\n> \"17\"\n> > ( ~r 17 #:min-width 4 )\n> \" 17\"\n> > ( ~r -4 2 #:min-width 4 )\n> \"- 42\"\n> > ( ~r 1.5 #:min-width 4 )\n> \" 1.5\"\n> > ( ~r 1.5 #:precision 4 #:min-width 10 )\n> \" 1.5\"\n> > ( ~r 1.5 #:precision ' ( = 4 ) #:min-width 10 )\n> \" 1.5000\"\n> > ( ~r #e1e10 #:min-width 6 )\n> \"10000000000\"\n> ```\n- pad-string — specifies the string used to pad the number to at least min-width characters (not including the sign indicator). The padding is placed between the sign and the normal digits of x.\nExamples:\n> ```racket\n> > ( ~r 17 #:min-width 4 #:pad-string \"0\" )\n> \"0017\"\n> > ( ~r -4 2 #:min-width 4 #:pad-string \"0\" )\n> \"-0042\"\n> ```\n- \nsign — controls how the sign of the number is indicated:\n- If sign is #f (the default), no sign output is generated if x is either positive or zero, and a minus sign is prefixed if x is negative.\nExample:\n> ```racket\n> > ( for/list ( [ x ' ( 17 0 -4 2 ) ] ) ( ~r x ) )\n> '(\"17\" \"0\" \"-42\")\n> ```\n- If sign is '+, no sign output is generated if x is zero, a plus sign is prefixed if x is positive, and a minus sign is prefixed if x is negative.\nExample:\n> ```racket\n> > ( for/list ( [ x ' ( 17 0 -4 2 ) ] ) ( ~r x #:sign ' + ) )\n> '(\"+17\" \"0\" \"-42\")\n> ```\n- If sign is '++, a plus sign is prefixed if x is zero or positive, and a minus sign is prefixed if x is negative.\nExample:\n> ```racket\n> > ( for/list ( [ x ' ( 17 0 -4 2 ) ] ) ( ~r x #:sign ' ++ ) )\n> '(\"+17\" \"+0\" \"-42\")\n> ```\n- If sign is 'parens, no sign output is generated if x is zero or positive, and the number is enclosed in parentheses if x is negative."} {"text": "# 4.3.5 Extflonums\nExample:\n> ```racket\n> > ( for/list ( [ x ' ( 17 0 -4 2 ) ] ) ( ~r x #:sign ' parens ) )\n> '(\"17\" \"0\" \"(42)\")\n> ```\n- If sign is (list pos-ind zero-ind neg-ind), then pos-ind, zero-ind, and neg-ind are used to indicate positive, zero, and negative numbers, respectively. Each indicator is either a string to be used as a prefix or a list containing two strings: a prefix and a suffix.\nExample:\n> ```racket\n> > ( let ( [ sign-table ' ( ( \"\" \" up\" ) \"an even \" ( \"\" \" down\" ) ) ] ) ( for/list ( [ x ' ( 17 0 -4 2 ) ] ) ( ~r x #:sign sign-table ) ) )\n> '(\"17 up\" \"an even 0\" \"42 down\")\n> ```\nThe default behavior is equivalent to '(\"\" \"\" \"-\"); the 'parens mode is equivalent to '(\"\" \"\" (\"(\" \")\")).\n- base — controls the base that x is formatted in. If base is a number greater than 10, then lower-case letters are used. If base is (list 'up base\\*) and base\\* is greater than 10, then upper-case letters are used.\nExamples:\n> ```racket\n> > ( ~r 100 #:base 7 )\n> \"202\"\n> > ( ~r 4.5 #:base 2 )\n> \"100.1\"\n> > ( ~r 3735928559 #:base 16 )\n> \"deadbeef\"\n> > ( ~r 3735928559 #:base ' ( up 16 ) )\n> \"DEADBEEF\"\n> > ( ~r 3735928559 #:base ' ( up 16 ) #:notation ' exponential )\n> \"D.EADBEF*16^+07\"\n> ```\n- format-exponent — determines how the exponent is displayed.\nIf format-exponent is a string, the exponent is displayed with an explicit sign (as with a sign of '++) and at least two digits, separated from the significand by the “exponent marker” format-exponent:\n> ```racket\n> > ( ~r 1234 #:notation ' exponential #:format-exponent \"E\" )\n> \"1.234E+03\"\n> ```"} {"text": "# 4.3.5 Extflonums\nIf format-exponent is #f, the “exponent marker” is \"e\" if base is 10 and a string involving base otherwise:\n> ```racket\n> > ( ~r 1234 #:notation ' exponential )\n> \"1.234e+03\"\n> > ( ~r 1234 #:notation ' exponential #:base 8 )\n> \"2.322*8^+03\"\n> ```\nIf format-exponent is a procedure, it is applied to the exponent and the resulting string is appended to the significand:\n> ```racket\n> > ( ~r 1234 #:notation ' exponential #:format-exponent ( lambda ( e ) ( format \"E~a\" e ) ) )\n> \"1.234E3\"\n> ```\nChanged in version 8.5.0.5 of package base: Added #:groups, #:group-sep and #:decimal-sep.\n> ```\n(~.a   v        \n    ...        \n   [ #:separator separator        \n    #:width width        \n    #:max-width max-width        \n    #:min-width min-width        \n    #:limit-marker limit-marker        \n    #:limit-prefix? limit-prefix?        \n    #:align align        \n    #:pad-string pad-string        \n    #:left-pad-string left-pad-string        \n    #:right-pad-string right-pad-string)   →   string?\n  v : any/c\n  separator : string? = \"\"\n  width : (or/c exact-nonnegative-integer? #f) = #f\n   max-width   :   (or/c exact-nonnegative-integer? +inf.0)\n      =   (or width +inf.0)\n  min-width : exact-nonnegative-integer? = (or width 0)\n  limit-marker : string? = \"\"\n  limit-prefix? : boolean? = #f\n  align : (or/c 'left 'center 'right) = 'left\n  pad-string : non-empty-string? = \" \"\n  left-pad-string : non-empty-string? = pad-string\n  right-pad-string : non-empty-string? = pad-string"} {"text": "# 4.3.5 Extflonums\n(~.v   v        \n    ...        \n   [ #:separator separator        \n    #:width width        \n    #:max-width max-width        \n    #:min-width min-width        \n    #:limit-marker limit-marker        \n    #:limit-prefix? limit-prefix?        \n    #:align align        \n    #:pad-string pad-string        \n    #:left-pad-string left-pad-string        \n    #:right-pad-string right-pad-string)   →   string?\n  v : any/c\n  separator : string? = \" \"\n  width : (or/c exact-nonnegative-integer? #f) = #f\n   max-width   :   (or/c exact-nonnegative-integer? +inf.0)\n      =   (or width +inf.0)\n  min-width : exact-nonnegative-integer? = (or width 0)\n  limit-marker : string? = \"...\"\n  limit-prefix? : boolean? = #f\n  align : (or/c 'left 'center 'right) = 'left\n  pad-string : non-empty-string? = \" \"\n  left-pad-string : non-empty-string? = pad-string\n  right-pad-string : non-empty-string? = pad-string\n(~.s   v        \n    ...        \n   [ #:separator separator        \n    #:width width        \n    #:max-width max-width        \n    #:min-width min-width        \n    #:limit-marker limit-marker        \n    #:limit-prefix? limit-prefix?        \n    #:align align        \n    #:pad-string pad-string        \n    #:left-pad-string left-pad-string        \n    #:right-pad-string right-pad-string)   →   string?\n  v : any/c\n  separator : string? = \" \"\n  width : (or/c exact-nonnegative-integer? #f) = #f\n   max-width   :   (or/c exact-nonnegative-integer? +inf.0)\n      =   (or width +inf.0)"} {"text": "# 4.3.5 Extflonums\n  min-width : exact-nonnegative-integer? = (or width 0)\n  limit-marker : string? = \"...\"\n  limit-prefix? : boolean? = #f\n  align : (or/c 'left 'center 'right) = 'left\n  pad-string : non-empty-string? = \" \"\n  left-pad-string : non-empty-string? = pad-string\n  right-pad-string : non-empty-string? = pad-string```\nLike [~a](#%28def._%28%28lib._racket%2Fformat..rkt%29._~7ea%29%29), [~v](#%28def._%28%28lib._racket%2Fformat..rkt%29._~7ev%29%29), and [~s](#%28def._%28%28lib._racket%2Fformat..rkt%29._~7es%29%29), but each v is formatted like ([format](Writing.html#%28def._%28%28quote._~23~25kernel%29._format%29%29) \"\\~.a\" v), ([format](Writing.html#%28def._%28%28quote._~23~25kernel%29._format%29%29) \"\\~.v\" v), and ([format](Writing.html#%28def._%28%28quote._~23~25kernel%29._format%29%29) \"\\~.s\" v), respectively.\n------------------------------------------------------------------------"} {"text": "# 4.5 Byte Strings"} {"text": "### 4.5 Byte Strings\n> > > \"+\"[Bytes and Byte Strings](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=bytestrings.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces byte strings.\nA byte string is a fixed-length array of bytes. A byte is an exact integer between 0 and 255 inclusive.\nA byte string can be mutable or immutable. When an immutable byte string is provided to a procedure like [bytes-set!](#%28def._%28%28quote._~23~25kernel%29._bytes-set%21%29%29), the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. Byte-string constants generated by the default reader (see [Reading Strings](reader.html#%28part._parse-string%29)) are immutable, and they are [interned](reader.html#%28tech._interned%29) in [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29) mode. Use [immutable?](booleans.html#%28def._%28%28quote._~23~25kernel%29._immutable~3f%29%29) to check whether a byte string is immutable.\nTwo byte strings are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) when they have the same length and contain the same sequence of bytes."} {"text": "# 4.5 Byte Strings\nA byte string can be used as a single-valued sequence (see [Sequences](sequences.html)). The bytes of the string serve as elements of the sequence. See also [in-bytes](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-bytes%29%29).\nSee [Reading Strings](reader.html#%28part._parse-string%29) for information on [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29)ing byte strings and [Printing Strings](printing.html#%28part._print-string%29) for information on [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29)ing byte strings.\nSee also: [immutable?](booleans.html#%28def._%28%28quote._~23~25kernel%29._immutable~3f%29%29)."} {"text": "#### 4.5.1 Byte String Constructors, Selectors, and Mutators\n> ```\n(bytes? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a byte string, #f otherwise.\n\nSee also immutable-bytes? and mutable-bytes?.\n\nExamples:\n\n> ```racket\n> > ( bytes? #\"Apple\" )\n> #t\n> > ( bytes? \"Apple\" )\n> #f\n> ```\n\n> ```\n(make-bytes k [b) → bytes?\n  k : exact-nonnegative-integer?\n  b : byte? = 0```\n\n\nReturns a new mutable byte string of length k where each position in the byte string is initialized with the byte b.\n\nExample:\n\n> ```racket\n> > ( make-bytes 5 65 )\n> #\"AAAAA\"\n> ```\n\n> ```\n(bytes b ...) → bytes?\n  b : byte?\n```\nReturns a new mutable byte string whose length is the number of provided bs, and whose positions are initialized with the given bs.\nExample:\n> ```racket\n> > ( bytes 65 112 112 108 101 )\n> #\"Apple\"\n> ```\n> ```\n(bytes → immutable-bytes bstr)  →  (and/c bytes? immutable?)\n  bstr : bytes?\n```\n\n\nReturns an immutable byte string with the same content as bstr, returning bstr itself if bstr is immutable.\n\nExamples:\n\n> ```racket\n> > ( bytes->immutable-bytes ( bytes 65 65 65 ) )\n> #\"AAA\"\n> > ( define b ( bytes->immutable-bytes ( make-bytes 5 65 ) ) )\n> > ( bytes->immutable-bytes b )\n> #\"AAAAA\"\n> > ( eq? ( bytes->immutable-bytes b ) b )\n> #t\n> ```\n\n> ```\n(byte? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a byte (i.e., an exact integer between 0 and 255 inclusive), #f otherwise.\nExamples:\n> ```racket\n> > ( byte? 65 )\n> #t\n> > ( byte? 0 )\n> #t\n> > ( byte? 256 )\n> #f\n> > ( byte? -1 )\n> #f\n> ```\n> ```\n(bytes-length bstr)  →  exact-nonnegative-integer?\n  bstr : bytes?"} {"text": "# 4.5 Byte Strings\n```\n\n\nReturns the length of bstr.\n\nExample:\n\n> ```racket\n> > ( bytes-length #\"Apple\" )\n> 5\n> ```\n\n> ```\n(bytes-ref bstr k)  →  byte?\n  bstr : bytes?\n  k : exact-nonnegative-integer?\n```\n(parameter)\t→\t\n(-> and/c bytes? (not/c immutable?))```\nChanges the byte at position k in bstr to b. The first position in the byte string corresponds to 0, so the position k must be less than the length of the bytes, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nExamples:\n> ```racket\n> > ( define s ( bytes 65 112 112 108 101 ) )\n> > ( bytes-set! s 4 121 )\n> > s\n> #\"Apply\"\n> ```\n> ```\n(subbytes bstr start [end) → bytes?\n  bstr : bytes?\n  start : exact-nonnegative-integer?\n  end : exact-nonnegative-integer? = (bytes-length str)\n```\nReturns a new mutable byte string that is (- end start) bytes long, and that contains the same bytes as bstr from start inclusive to end exclusive. The start and end arguments must be less than or equal to the length of bstr, and end must be greater than or equal to start, otherwise the exn:fail:contract exception is raised.\n\nExamples:\n\n> ```racket\n> > ( subbytes #\"Apple\" 1 3 )\n> #\"pp\"\n> > ( subbytes #\"Apple\" 1 )\n> #\"pple\"\n> ```\n\n> ```\n(bytes-copy bstr)  →  bytes?\n  bstr : bytes?```\n\n\nReturns ([subbytes](#%28def._%28%28quote._~23~25kernel%29._subbytes%29%29) str 0).\n\n> ```\n(parameter)\t→\t\n(-> and/c bytes? (not/c immutable?))\n```\n(inclusive)\t→\t\n(-> and/c bytes? (not/c immutable?))```"} {"text": "# 4.5 Byte Strings\nChanges dest so that every position in the bytes is filled with b.\nExamples:\n> ```racket\n> > ( define s ( bytes 65 112 112 108 101 ) )\n> > ( bytes-fill! s 113 )\n> > s\n> #\"qqqqq\"\n> ```\n> ```\n(bytes-append bstr ...) → bytes?\n  bstr : bytes?\n```\n\n\nReturns a new mutable byte string that is as long as the sum of the given bstrs’ lengths, and that contains the concatenated bytes of the given bstrs. If no bstrs are provided, the result is a zero-length byte string.\n\nExample:\n\n> ```racket\n> > ( bytes-append #\"Apple\" #\"Banana\" )\n> #\"AppleBanana\"\n> ```\n\n> ```\n(bytes → list bstr)  →  (listof byte?)\n  bstr : bytes?\n```\nReturns a new list of bytes corresponding to the content of bstr. That is, the length of the list is ([bytes-length](#%28def._%28%28quote._~23~25kernel%29._bytes-length%29%29) bstr), and the sequence of bytes in bstr is the same sequence in the result list.\nExample:\n> ```racket\n> > ( bytes->list #\"Apple\" )\n> '(65 112 112 108 101)\n> ```\n> ```\n(list → bytes lst)  →  bytes?\n  lst : (listof byte?)"} {"text": "# 4.5 Byte Strings\n```\nReturns a new mutable byte string whose content is the list of bytes in lst. That is, the length of the byte string is (length lst), and the sequence of bytes in lst is the same sequence in the result byte string.\n\nExample:\n\n> ```racket\n> > ( list → bytes ( list 65 112 112 108 101 ) )\n> #\"Apple\"\n> ```\n\n> ```\n(make-shared-bytes k [b) → bytes?\n  k : exact-nonnegative-integer?\n  b : byte? = 0```\n\n\nReturns a new mutable byte string of length k where each position in the byte string is initialized with the byte b. For communication among [places](places.html#%28tech._place%29), the new byte string is allocated in the [shared memory space](places.html#%28tech._shared._memory._space%29).\n\nExample:\n\n> ```racket\n> > ( make-shared-bytes 5 65 )\n> #\"AAAAA\"\n> ```\n\n> ```\n(shared-bytes b ...) → bytes?\n  b : byte?\n```\nReturns a new mutable byte string whose length is the number of provided bs, and whose positions are initialized with the given bs. For communication among places, the new byte string is allocated in the shared memory space.\nExample:\n> ```racket\n> > ( shared-bytes 65 112 112 108 101 )\n> #\"Apple\"\n> ```"} {"text": "#### 4.5.2 Byte String Comparisons\n> ```\n(bytes=? bstr1 bstr2 ...) → boolean?\n  bstr1 : bytes?\n  bstr2 : bytes?```\nReturns #t if all of the arguments are [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29).\nExamples:\n> ```racket\n> > ( bytes=? #\"Apple\" #\"apple\" )\n> #f\n> > ( bytes=? #\"a\" #\"as\" #\"a\" )\n> #f\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n>
\n

procedure

\n

([bytes

  bstr1 : [bytes?](#%28def._%28%28quote._~23~25kernel%29._bytes~3f%29%29)
  bstr2 : [bytes?](#%28def._%28%28quote._~23~25kernel%29._bytes~3f%29%29)
\nReturns #t if the arguments are lexicographically sorted increasing, where individual bytes are ordered by [<](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._~3c%29%29), #f otherwise.\nExamples:\n> ```racket\n> > ( bytes #t\n> > ( bytes #f\n> > ( bytes #t\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n> ```\n(bytes>? bstr1 bstr2 ...) → boolean?\n  bstr1 : bytes?\n  bstr2 : bytes?"} {"text": "# 4.5 Byte Strings\n```\nLike bytes ```racket\n> > ( bytes>? #\"Apple\" #\"apple\" )\n> #f\n> > ( bytes>? #\"apple\" #\"Apple\" )\n> #t\n> > ( bytes>? #\"c\" #\"b\" #\"a\" )\n> #t\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n#### 4.5.3 Bytes to/from Characters, Decoding and Encoding\n\n> ```\n(bytes → string/utf-8 bstr [err-char start end) → string?\n  bstr : bytes?\n  err-char : (or/c #f char?) = #f\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (bytes-length bstr)```\n\n\nProduces a string by decoding the start to end substring of bstr as a UTF-8 encoding of Unicode code points. If err-char is not #f, then it is used for bytes that fall in the range 128 to 255 but are not part of a valid encoding sequence. (This rule is consistent with reading characters from a port; see [Encodings and Locales](encodings.html) for more details.) If err-char is #f, and if the start to end substring of bstr is not a valid UTF-8 encoding overall, then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nExample:\n\n> ```racket\n> > ( bytes->string/utf-8 ( bytes 195 167 195 176 195 182 194 163 ) )\n> \"çðö£\"\n> ```\n\n> ```\n(bytes → string/locale bstr\n   [ err-char        \n    start        \n    end)   →   string?\n\n  bstr : bytes?\n  err-char : (or/c #f char?) = #f\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (bytes-length bstr)\n```"} {"text": "# 4.5 Byte Strings\nProduces a string by decoding the start to end substring of bstr using the current locale’s encoding (see also Encodings and Locales). If err-char is not #f, it is used for each byte in bstr that is not part of a valid encoding; if err-char is #f, and if the start to end substring of bstr is not a valid encoding overall, then the exn:fail:contract exception is raised.\n> ```\n(bytes → string/latin-1 bstr\n   [ err-char        \n    start        \n    end)   →   string?\n  bstr : bytes?\n  err-char : (or/c #f char?) = #f\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (bytes-length bstr)```\nProduces a string by decoding the start to end substring of bstr as a Latin-1 encoding of Unicode code points; i.e., each byte is translated directly to a character using [integer->char](characters.html#%28def._%28%28quote._~23~25kernel%29._integer-~3echar%29%29), so the decoding always succeeds. The err-char argument is ignored, but present for consistency with the other operations.\nExample:\n> ```racket\n> > ( bytes->string/latin-1 ( bytes 254 211 209 165 ) )\n> \"þÓÑ¥\"\n> ```\n> ```\n(string → bytes/utf-8 str [err-byte start end) → bytes?\n  str : string?\n  err-byte : (or/c #f byte?) = #f\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (string-length str)"} {"text": "# 4.5 Byte Strings\n```\nProduces a byte string by encoding the start to end substring of str via UTF-8 (always succeeding). The err-byte argument is ignored, but included for consistency with the other operations.\n\nExamples:\n\n> ```racket\n> > ( define b ( bytes → string/utf-8 ( bytes 195 167 195 176 195 182 194 163 ) ) )\n> > ( string → bytes/utf-8 b )\n> #\"\\303\\247\\303\\260\\303\\266\\302\\243\"\n> > ( bytes → string/utf-8 ( string → bytes/utf-8 b ) )\n> \"çðö£\"\n> ```\n\n> ```\n(string → bytes/locale str [err-byte start end) → bytes?\n  str : string?\n  err-byte : (or/c #f byte?) = #f\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (string-length str)```\n\n\nProduces a string by encoding the start to end substring of str using the current locale’s encoding (see also [Encodings and Locales](encodings.html)). If err-byte is not #f, it is used for each character in str that cannot be encoded for the current locale; if err-byte is #f, and if the start to end substring of str cannot be encoded, then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\n> ```\n(string → bytes/latin-1 str\n   [ err-byte        \n    start        \n    end)   →   bytes?\n\n  str : string?\n  err-byte : (or/c #f byte?) = #f\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (string-length str)\n```"} {"text": "# 4.5 Byte Strings\nProduces a string by encoding the start to end substring of str using Latin-1; i.e., each character is translated directly to a byte using char → integer. If err-byte is not #f, it is used for each character in str whose value is greater than 255. If err-byte is #f, and if the start to end substring of str has a character with a value greater than 255, then the exn:fail:contract exception is raised.\nExamples:\n> ```racket\n> > ( define b ( bytes → string/latin-1 ( bytes 254 211 209 165 ) ) )\n> > ( string → bytes/latin-1 b )\n> #\"\\376\\323\\321\\245\"\n> > ( bytes → string/latin-1 ( string → bytes/latin-1 b ) )\n> \"þÓÑ¥\"\n> ```\n> ```\n(string-utf-8-length str [start end) → exact-nonnegative-integer?\n  str : string?\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (string-length str)```\nReturns the length in bytes of the UTF-8 encoding of str’s substring from start to end, but without actually generating the encoded bytes.\nExamples:\n> ```racket\n> > ( string-utf-8-length ( bytes->string/utf-8 ( bytes 195 167 195 176 195 182 194 163 ) ) )\n> 8\n> > ( string-utf-8-length \"hello\" )\n> 5\n> ```\n> ```\n(bytes-utf-8-length bstr [err-char start end)\n  →  (or/c exact-nonnegative-integer? #f)\n  bstr : bytes?\n  err-char : (or/c #f char?) = #f\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (bytes-length bstr)"} {"text": "# 4.5 Byte Strings\n```\nReturns the length in characters of the UTF-8 decoding of bstr’s substring from start to end, but without actually generating the decoded characters. If err-char is #f and the substring is not a UTF-8 encoding overall, the result is #f. Otherwise, err-char is used to resolve decoding errors as in bytes → string/utf-8.\n\nExamples:\n\n> ```racket\n> > ( bytes-utf-8-length ( bytes 195 167 195 176 195 182 194 163 ) )\n> 4\n> > ( bytes-utf-8-length ( make-bytes 5 65 ) )\n> 5\n> ```\n\n> ```\n(bytes-utf-8-ref bstr [skip err-char start end) → (or/c char? #f)\n  bstr : bytes?\n  skip : exact-nonnegative-integer? = 0\n  err-char : (or/c #f char?) = #f\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (bytes-length bstr)```\n\n\nReturns the skipth character in the UTF-8 decoding of bstr’s substring from start to end, but without actually generating the other decoded characters. If the substring is not a UTF-8 encoding up to the skipth character (when err-char is #f), or if the substring decoding produces fewer than skip characters, the result is #f. If err-char is not #f, it is used to resolve decoding errors as in [bytes->string/utf-8](#%28def._%28%28quote._~23~25kernel%29._bytes-~3estring%2Futf-8%29%29).\n\nExamples:\n\n> ```racket\n> > ( bytes-utf-8-ref ( bytes 195 167 195 176 195 182 194 163 ) 0 )\n> #\\ç\n> > ( bytes-utf-8-ref ( bytes 195 167 195 176 195 182 194 163 ) 1 )\n> #\\ð\n> > ( bytes-utf-8-ref ( bytes 195 167 195 176 195 182 194 163 ) 2 )\n> #\\ö\n> > ( bytes-utf-8-ref ( bytes 65 66 67 68 ) 0 )\n> #\\A\n> > ( bytes-utf-8-ref ( bytes 65 66 67 68 ) 1 )\n> #\\B\n> > ( bytes-utf-8-ref ( bytes 65 66 67 68 ) 2 )\n> #\\C\n> ```\n\n> ```\n(bytes-utf-8-index bstr\n    skip  \n   [ err-char  \n    start  \n    end)  \n\n  →  (or/c exact-nonnegative-integer? #f)\n  bstr : bytes?\n  skip : exact-nonnegative-integer?\n  err-char : (or/c #f char?) = #f\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (bytes-length bstr)\n```"} {"text": "# 4.5 Byte Strings\nReturns the offset in bytes into bstr at which the skipth character’s encoding starts in the UTF-8 decoding of bstr’s substring from start to end (but without actually generating the other decoded characters). The result is relative to the start of bstr, not to start. If the substring is not a UTF-8 encoding up to the skipth character (when err-char is #f), or if the substring decoding produces fewer than skip characters, the result is #f. If err-char is not #f, it is used to resolve decoding errors as in bytes → string/utf-8.\nExamples:\n> ```racket\n> > ( bytes-utf-8-index ( bytes 195 167 195 176 195 182 194 163 ) 0 )\n> 0\n> > ( bytes-utf-8-index ( bytes 195 167 195 176 195 182 194 163 ) 1 )\n> 2\n> > ( bytes-utf-8-index ( bytes 195 167 195 176 195 182 194 163 ) 2 )\n> 4\n> > ( bytes-utf-8-index ( bytes 65 66 67 68 ) 0 )\n> 0\n> > ( bytes-utf-8-index ( bytes 65 66 67 68 ) 1 )\n> 1\n> > ( bytes-utf-8-index ( bytes 65 66 67 68 ) 2 )\n> 2\n> ```"} {"text": "#### 4.5.4 Bytes to Bytes Encoding Conversion\n> ```\n(bytes-open-converter from-name to-name)\n  →  (or/c bytes-converter? #f)\n  from-name : string?\n  to-name : string?```\nProduces a byte converter to go from the encoding named by from-name to the encoding named by to-name. If the requested conversion pair is not available, #f is returned instead of a converter.\nCertain encoding combinations are always available:\n- ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"UTF-8\" \"UTF-8\") — the identity conversion, except that encoding errors in the input lead to a decoding failure.\n- ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"UTF-8-permissive\" \"UTF-8\") — the identity conversion, except that any input byte that is not part of a valid encoding sequence is effectively replaced by the UTF-8 encoding sequence for #\\\\uFFFD. (This handling of invalid sequences is consistent with the interpretation of port bytes streams into characters; see [Ports](ports.html).)\n- ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"\" \"UTF-8\") — converts from the current locale’s default encoding (see [Encodings and Locales](encodings.html)) to UTF-8.\n- ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"UTF-8\" \"\") — converts from UTF-8 to the current locale’s default encoding (see [Encodings and Locales](encodings.html))."} {"text": "# 4.5 Byte Strings\n- ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"platform-UTF-8\" \"platform-UTF-16\") — converts UTF-8 to UTF-16 on Unix and Mac OS, where each UTF-16 code unit is a sequence of two bytes ordered by the current platform’s endianness. On Windows, the conversion is the same as ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"WTF-8\" \"WTF-16\") to support unpaired surrogate code units.\n- ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"platform-UTF-8-permissive\" \"platform-UTF-16\") — like ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"platform-UTF-8\" \"platform-UTF-16\"), but an input byte that is not part of a valid UTF-8 encoding sequence (or valid for the unpaired-surrogate extension on Windows) is effectively replaced with #\\\\uFFFD."} {"text": "# 4.5 Byte Strings\n- ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"platform-UTF-16\" \"platform-UTF-8\") — converts UTF-16 (bytes ordered by the current platform’s endianness) to UTF-8 on Unix and Mac OS. On Windows, the conversion is the same as ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"WTF-16\" \"WTF-8\") to support unpaired surrogates. On Unix and Mac OS, surrogates are assumed to be paired: a pair of bytes with the bits #xD800 starts a surrogate pair, and the #x03FF bits are used from the pair and following pair (independent of the value of the #xDC00 bits). On all platforms, performance may be poor when decoding from an odd offset within an input byte string.\n- ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"WTF-8\" \"WTF-16\") — converts the WTF-8 \\[[Sapin18](doc-bibliography.html#%28cite._.Sapin18%29)\\] superset of UTF-8 to a superset of UTF-16 to support unpaired surrogate code units, where each UTF-16 code unit is a sequence of two bytes ordered by the current platform’s endianness.\n- ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"WTF-8-permissive\" \"WTF-16\") — like ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"WTF-8\" \"WTF-16\"), but an input byte that is not part of a valid WTF-8 encoding sequence is effectively replaced with #\\\\uFFFD."} {"text": "# 4.5 Byte Strings\n- ([bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"WTF-16\" \"WTF-8\") — converts the WTF-16 \\[[Sapin18](doc-bibliography.html#%28cite._.Sapin18%29)\\] superset of UTF-16 to the WTF-8 superset of UTF-8. The input can include UTF-16 code units that are unpaired surrogates, and the corresponding output includes an encoding of each surrogate in a natural extension of UTF-8.\nA newly opened byte converter is registered with the current custodian (see [Custodians](custodians.html)), so that the converter is closed when the custodian is shut down. A converter is not registered with a custodian (and does not need to be closed) if it is one of the guaranteed combinations not involving \"\" on Unix, or if it is any of the guaranteed combinations (including \"\") on Windows and Mac OS.\n> > > In the Racket software distributions for Windows, a suitable \"iconv.dll\" is included with \"libmzschVERS.dll\".\nThe set of available encodings and combinations varies by platform, depending on the iconv library that is installed; the from-name and to-name arguments are passed on to iconv_open. On Windows, \"iconv.dll\" or \"libiconv.dll\" must be in the same directory as \"libmzschVERS.dll\" (where VERS is a version number), in the user’s path, in the system directory, or in the current executable’s directory at run time, and the DLL must either supply \\_errno or link to \"msvcrt.dll\" for \\_errno; otherwise, only the guaranteed combinations are available."} {"text": "# 4.5 Byte Strings\nUse [bytes-convert](#%28def._%28%28quote._~23~25kernel%29._bytes-convert%29%29) with the result to convert byte strings.\nChanged in version 7.9.0.17 of package base: Added built-in converters for \"WTF-8\", \"WTF-8-permissive\", and \"WTF-16\".\n> ```\n(bytes-close-converter converter)  →  void\n  converter : bytes-converter?\n```\nCloses the given converter, so that it can no longer be used with bytes-convert or bytes-convert-end.\n\n> ```\n(bytes-convert converter\n    src-bstr  \n   [ src-start-pos  \n    src-end-pos  \n    dest-bstr  \n    dest-start-pos  \n    dest-end-pos)  \n\n  →   (or/c bytes? exact-nonnegative-integer?)\nexact-nonnegative-integer?\n(or/c 'complete 'continues 'aborts 'error)\n\n  converter : bytes-converter?\n  src-bstr : bytes?\n  src-start-pos : exact-nonnegative-integer? = 0\n   src-end-pos   :   exact-nonnegative-integer?\n      =   (bytes-length src-bstr)\n\n  dest-bstr : (or/c bytes? #f) = #f\n  dest-start-pos : exact-nonnegative-integer? = 0\n   dest-end-pos   :   (or/c exact-nonnegative-integer? #f)\n      =   ( and dest-bstr\n> ( bytes-length dest-bstr ) )```\n\n\nConverts the bytes from src-start-pos to src-end-pos in src-bstr.\n\nIf dest-bstr is not #f, the converted bytes are written into dest-bstr from dest-start-pos to dest-end-pos. If dest-bstr is #f, then a newly allocated byte string holds the conversion results, and if dest-end-pos is not #f, the size of the result byte string is no more than ([-](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._-%29%29) dest-end-pos dest-start-pos).\n\nThe result of [bytes-convert](#%28def._%28%28quote._~23~25kernel%29._bytes-convert%29%29) is three values:\n\n- result-bstr or dest-wrote-amt — a byte string if dest-bstr is #f or not provided, or the number of bytes written into dest-bstr otherwise.\n\n- src-read-amt — the number of bytes successfully converted from src-bstr.\n\n- 'complete, 'continues, 'aborts, or 'error — indicates how conversion terminated:\n\n - 'complete: The entire input was processed, and src-read-amt will be equal to ([-](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._-%29%29) src-end-pos src-start-pos).\n\n - 'continues: Conversion stopped due to the limit on the result size or the space in dest-bstr; in this case, fewer than ([-](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._-%29%29) dest-end-pos dest-start-pos) bytes may be returned if more space is needed to process the next complete encoding sequence in src-bstr.\n\n - 'aborts: The input stopped part-way through an encoding sequence, and more input bytes are necessary to continue. For example, if the last byte of input is 195 for a \"UTF-8-permissive\" decoding, the result is 'aborts, because another byte is needed to determine how to use the 195 byte.\n\n - 'error: The bytes starting at ([+](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._%2B%29%29) src-start-pos src-read-amt) bytes in src-bstr do not form a legal encoding sequence. This result is never produced for some encodings, where all byte sequences are valid encodings. For example, since \"UTF-8-permissive\" handles an invalid UTF-8 sequence by dropping characters or generating “?,” every byte sequence is effectively valid.\n\nApplying a converter accumulates state in the converter (even when the third result of [bytes-convert](#%28def._%28%28quote._~23~25kernel%29._bytes-convert%29%29) is 'complete). This state can affect both further processing of input and further generation of output, but only for conversions that involve “shift sequences” to change modes within a stream. To terminate an input sequence and reset the converter, use [bytes-convert-end](#%28def._%28%28quote._~23~25kernel%29._bytes-convert-end%29%29).\n\nExamples:\n\n> ```racket\n> > ( define convert ( bytes-open-converter \"UTF-8\" \"UTF-16\" ) )\n> > ( bytes-convert convert ( bytes 65 66 67 68 ) )\n> #\"\\376\\377\\0A\\0B\\0C\\0D\" 4 'complete\n> > ( bytes 195 167 195 176 195 182 194 163 )\n> #\"\\303\\247\\303\\260\\303\\266\\302\\243\"\n> > ( bytes-convert convert ( bytes 195 167 195 176 195 182 194 163 ) )\n> #\"\\0\\347\\0\\360\\0\\366\\0\\243\" 8 'complete\n> > ( bytes-close-converter convert )\n> ```\n\n> ```\n(bytes-convert-end converter\n   [ dest-bstr  \n    dest-start-pos  \n    dest-end-pos)  \n\n  →   (or/c bytes? exact-nonnegative-integer?)\n(or/c 'complete 'continues)\n\n  converter : bytes-converter?\n  dest-bstr : (or/c bytes? #f) = #f\n  dest-start-pos : exact-nonnegative-integer? = 0\n   dest-end-pos   :   (or/c exact-nonnegative-integer? #f)\n      =   ( and dest-bstr\n> ( bytes-length dest-bstr ) )\n```"} {"text": "# 4.5 Byte Strings\nLike bytes-convert, but instead of converting bytes, this procedure generates an ending sequence for the conversion (sometimes called a “shift sequence”), if any. Few encodings use shift sequences, so this function will succeed with no output for most encodings. In any case, successful output of a (possibly empty) shift sequence resets the converter to its initial state.\nThe result of bytes-convert-end is two values:\n- result-bstr or dest-wrote-amt — a byte string if dest-bstr is #f or not provided, or the number of bytes written into dest-bstr otherwise.\n- 'complete or 'continues — indicates whether conversion completed. If 'complete, then an entire ending sequence was produced. If 'continues, then the conversion could not complete due to the limit on the result size or the space in dest-bstr, and the first result is either an empty byte string or 0.\n> ```\n(bytes-converter? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a [byte converter](#%28tech._byte._converter%29) produced by [bytes-open-converter](#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29), #f otherwise.\nExamples:\n> ```racket\n> > ( bytes-converter? ( bytes-open-converter \"UTF-8\" \"UTF-16\" ) )\n> #t\n> > ( bytes-converter? ( bytes-open-converter \"whacky\" \"not likely\" ) )\n> #f\n> > ( define b ( bytes-open-converter \"UTF-8\" \"UTF-16\" ) )\n> > ( bytes-close-converter b )\n> > ( bytes-converter? b )\n> #t\n> ```\n> ```\n(locale-string-encoding)  →  any"} {"text": "# 4.5 Byte Strings\n```\nReturns a string for the current locale’s encoding (i.e., the encoding normally identified by \"\"). See also system-language+country.\n\n#### 4.5.5 Additional Byte String Functions\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require racket/bytes) |  package: base |\n\nThe bindings documented in this section are provided by the racket/bytes and racket libraries, but not racket/base.\n\n> ```\n(bytes-append* str ... strs) → bytes?\n  str : bytes?\n  strs : (listof bytes?)```\n\n\nLike [bytes-append](#%28def._%28%28quote._~23~25kernel%29._bytes-append%29%29), but the last argument is used as a list of arguments for [bytes-append](#%28def._%28%28quote._~23~25kernel%29._bytes-append%29%29), so ([bytes-append*](#%28def._%28%28lib._racket%2Fbytes..rkt%29._bytes-append%2A%29%29) str [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) strs) is the same as ([apply](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._apply%29%29) [bytes-append](#%28def._%28%28quote._~23~25kernel%29._bytes-append%29%29) str [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) strs). In other words, the relationship between [bytes-append](#%28def._%28%28quote._~23~25kernel%29._bytes-append%29%29) and [bytes-append*](#%28def._%28%28lib._racket%2Fbytes..rkt%29._bytes-append%2A%29%29) is similar to the one between [list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) and [list*](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%2A%29%29).\n\nExamples:\n\n> ```racket\n> > ( bytes-append* #\"a\" #\"b\" ' ( #\"c\" #\"d\" ) )\n> #\"abcd\"\n> > ( bytes-append* ( cdr ( append* ( map ( lambda ( x ) ( list #\", \" x ) ) ' ( #\"Alpha\" #\"Beta\" #\"Gamma\" ) ) ) ) )\n> #\"Alpha, Beta, Gamma\"\n> ```\n\n> ```\n(bytes-join strs sep)  →  bytes?\n  strs : (listof bytes?)\n  sep : bytes?\n```"} {"text": "# 4.5 Byte Strings\nAppends the byte strings in strs, inserting sep between each pair of bytes in strs. A new mutable byte string is returned.\nExample:\n> ```racket\n> > ( bytes-join ' ( #\"one\" #\"two\" #\"three\" #\"four\" ) #\" potato \" )\n> #\"one potato two potato three potato four\"\n> ```\n------------------------------------------------------------------------"} {"text": "# 4.6 Characters"} {"text": "### 4.6 Characters\n> > > \"+\"Characters in The Racket Guide introduces characters.\nCharacters range over Unicode scalar values, which includes characters whose values range from #x0 to #x10FFFF, but not including #xD800 to #xDFFF. The scalar values are a subset of the Unicode code points.\nTwo characters are eqv? if they correspond to the same scalar value. For each scalar value less than 256, character values that are eqv? are also eq?. Characters produced by the default reader are interned in read-syntax mode.\nSee Reading Characters for information on reading characters and Printing Characters for information on printing characters.\nChanged in version 6.1.1.8 of package base: Updated from Unicode 5.0.1 to Unicode 7.0.0."} {"text": "#### 4.6.1 Characters and Scalar Values\n> ```\n(char? v) → boolean?\n  v : any/c```\nReturn #t if v is a character, #f otherwise.\n> ```\n(char → integer char)  →  exact-integer?\n  char : char?\n```\n\n\nReturns a character’s code-point number.\n\nExample:\n\n> ```racket\n> > ( char->integer #\\A )\n> 65\n> ```\n\n> ```\n(integer → char k)  →  char?\n   k   :   ( and/c exact-integer?\n> ( or/c ( integer-in 0 #xD7FF )\n> ( integer-in #xE000 #x10FFFF ) ) )\n```\nReturn the character whose code-point number is k. For k less than 256, the result is the same object for the same k.\nExample:\n> ```racket\n> > ( integer->char 65 )\n> #\\A\n> ```\n> ```\n(char-utf-8-length char)  →  (integer-in 1 6)\n  char : char?"} {"text": "# 4.6 Characters\n```\nProduces the same result as (bytes-length (string → bytes/utf-8 (string char))).\n\n#### 4.6.2 Character Comparisons\n\n> ```\n(char=? char1 char2 ...) → boolean?\n  char1 : char?\n  char2 : char?```\n\n\nReturns #t if all of the arguments are [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29).\n\nExamples:\n\n> ```racket\n> > ( char=? #\\a #\\a )\n> #t\n> > ( char=? #\\a #\\A #\\a )\n> #f\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n>
\n\n

procedure

\n\n

([char

  char1 : [char?](#%28def._%28%28quote._~23~25kernel%29._char~3f%29%29)
  char2 : [char?](#%28def._%28%28quote._~23~25kernel%29._char~3f%29%29)
\n\nReturns #t if the arguments are sorted increasing, where two characters are ordered by their scalar values, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( char #t\n> > ( char #f\n> > ( char #t\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n>
\n\n

procedure

\n\n

([char<=?](#%28def._%28%28quote._~23~25kernel%29._char~3c~3d~3f%29%29) char1 char2 ...) → [boolean?](booleans.html#%28def._%28%28quote._~23~25kernel%29._boolean~3f%29%29)

  char1 : [char?](#%28def._%28%28quote._~23~25kernel%29._char~3f%29%29)
  char2 : [char?](#%28def._%28%28quote._~23~25kernel%29._char~3f%29%29)
\n\nLike [char ```racket\n> > ( char<=? #\\A #\\a )> #t\n> > ( char<=? #\\a #\\A )> #f\n> > ( char<=? #\\a #\\b #\\b )> #t\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n> ```\n(char>? char1 char2 ...) → boolean?\n  char1 : char?\n  char2 : char?\n```"} {"text": "# 4.6 Characters\nLike char ```racket\n> > ( char>? #\\A #\\a )\n> #f\n> > ( char>? #\\a #\\A )\n> #t\n> > ( char>? #\\c #\\b #\\a )\n> #t\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n> ```\n(char>=? char1 char2 ...) → boolean?\n  char1 : char?\n  char2 : char?```\nLike [char ```racket\n> > ( char>=? #\\A #\\a )\n> #f\n> > ( char>=? #\\a #\\A )\n> #t\n> > ( char>=? #\\c #\\b #\\b )\n> #t\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n> ```\n(char-ci=? char1 char2 ...) → boolean?\n  char1 : char?\n  char2 : char?"} {"text": "# 4.6 Characters\n```\nReturns #t if all of the arguments are eqv? after locale-insensitive case-folding via char-foldcase.\n\nExamples:\n\n> ```racket\n> > ( char-ci=? #\\A #\\a )\n> #t\n> > ( char-ci=? #\\a #\\a #\\a )\n> #t\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n>
\n\n

procedure

\n\n

(char-ci

  char1 : char?
  char2 : char?
\n\nLike char ```racket\n> > ( char-ci #f\n> > ( char-ci #t\n> > ( char-ci #t\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n>
\n\n

procedure

\n\n

(char-ci<=? char1 char2 ...)  →  boolean?

  char1 : char?
  char2 : char?
\n\nLike char-ci ```racket\n> > ( char-ci<=? #\\A #\\a )> #t\n> > ( char-ci<=? #\\a #\\A )> #t\n> > ( char-ci<=? #\\a #\\b #\\b )> #t\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n> ```\n(char-ci>? char1 char2 ...) → boolean?\n  char1 : char?\n  char2 : char?```\n\n\nLike [char-ci ```racket\n> > ( char-ci>? #\\A #\\a )\n> #f\n> > ( char-ci>? #\\b #\\A )\n> #t\n> > ( char-ci>? #\\c #\\b #\\a )\n> #t\n> ```\n\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more.\n\n> ```\n(char-ci>=? char1 char2 ...) → boolean?\n  char1 : char?\n  char2 : char?\n```"} {"text": "# 4.6 Characters\nLike char-ci ```racket\n> > ( char-ci>=? #\\A #\\a )\n> #t\n> > ( char-ci>=? #\\a #\\A )\n> #t\n> > ( char-ci>=? #\\c #\\b #\\b )\n> #t\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more."} {"text": "#### 4.6.3 Classifications\n> ```\n(char-alphabetic? char) → boolean?\n  char : char?```\nReturns #t if char has the Unicode “Alphabetic” property.\n> ```\n(char-lower-case? char)  →  boolean?\n  char : char?\n```\n\n\nReturns #t if char has the Unicode “Lowercase” property.\n\n> ```\n(char-upper-case? char)  →  boolean?\n  char : char?\n```\nReturns #t if char has the Unicode “Uppercase” property.\n> ```\n(char-title-case? char)  →  boolean?\n  char : char?\n```\n\n\nReturns #t if char’s Unicode general category is Lt, #f otherwise.\n\n> ```\n(char-numeric? char)  →  boolean?\n  char : char?\n```\nReturns #t if char has a Unicode “Numeric_Type” property value that is not None.\n> ```\n(char-symbolic? char)  →  boolean?\n  char : char?\n```\n\n\nReturns #t if char’s Unicode general category is Sm, Sc, Sk, or So, #f otherwise.\n\n> ```\n(char-punctuation? char)  →  boolean?\n  char : char?\n```\nReturns #t if char’s Unicode general category is Pc, Pd, Ps, Pe, Pi, Pf, or Po, #f otherwise.\n> ```\n(char-graphic? char)  →  boolean?\n  char : char?\n```\nReturns #t if char’s Unicode general category is Ll, Lm, Lo, Lt, Lu, Nd, Nl, No, Mn, Mc, or Me, or if one of the following produces #t when applied to char: char-alphabetic?, char-numeric?, char-symbolic?, or char-punctuation?.\n\n> ```\n(char-whitespace? char)  →  boolean?\n  char : char?```\n\n\nReturns #t if char has the Unicode “White_Space” property.\n\n> ```\n(char-blank? char)  →  boolean?\n  char : char?\n```\nReturns #t if char’s Unicode general category is Zs or if char is #\\\\tab. (These correspond to horizontal whitespace.)\n> ```"} {"text": "# 4.6 Characters\n(char-iso-control? char)  →  boolean?\n  char : char?\n```\n\n\nReturn #t if char is between #\\\\nul and #\\\\u001F inclusive or #\\\\rubout and #\\\\u009F inclusive.\n\n> ```\n(char-extended-pictographic? char)  →  boolean?\n  char : char?\n```\n(parameter)\t→```\nReturns a symbol representing the character’s Unicode general category, which is 'lu, 'll, 'lt, 'lm, 'lo, 'mn, 'mc, 'me, 'nd, 'nl, 'no, 'ps, 'pe, 'pi, 'pf, 'pd, 'pc, 'po, 'sc, 'sm, 'sk, 'so, 'zs, 'zp, 'zl, 'cc, 'cf, 'cs, 'co, or 'cn.\n> ```\n(char-grapheme-break-property char)  →  ?\n  char : char?\n```\n\n\nReturns the Unicode graheme-break property for char, which is 'Other, 'CR, 'LF, 'Control, 'Extend, 'ZWJ, 'Regional_Indicator, 'Prepend, 'SpacingMark, 'L, 'V, 'T, 'LV, or 'LVT.\n\nAdded in version 8.6.0.1 of package base.\n\n> ```\n(make-known-char-range-list)\n  →   ( listof ( list/c exact-nonnegative-integer?\n> exact-nonnegative-integer?\n> boolean? ) )\n```"} {"text": "# 4.6 Characters\nProduces a list of three-element lists, where each three-element list represents a set of consecutive code points for which the Unicode standard specifies character properties. Each three-element list contains two integers and a boolean; the first integer is a starting code-point value (inclusive), the second integer is an ending code-point value (inclusive), and the boolean is #t when all characters in the code-point range have identical results for all of the character predicates above, have analogous transformations (shifting by the same amount, if any, in code-point space) for [char-downcase](#%28def._%28%28quote._~23~25kernel%29._char-downcase%29%29), [char-upcase](#%28def._%28%28quote._~23~25kernel%29._char-upcase%29%29), and [char-titlecase](#%28def._%28%28quote._~23~25kernel%29._char-titlecase%29%29), and have the same decomposition–normalization behavior. The three-element lists are ordered in the overall result list such that later lists represent larger code-point values, and all three-element lists are separated from every other by at least one code-point value that is not specified by Unicode."} {"text": "#### 4.6.4 Character Conversions\n> ```\n(char-upcase char)  →  char?\n  char : char?\n```\nProduces a character consistent with the 1-to-1 code point mapping defined by Unicode. If char has no upcase mapping, char-upcase produces char.\n\n> > > String procedures, such as string-upcase, handle the case where Unicode defines a locale-independent mapping from the code point to a code-point sequence (in addition to the 1-1 mapping on scalar values).\n\nExamples:\n\n> ```racket\n> > ( char-upcase #\\a )\n> #\\A\n> > ( char-upcase #\\λ )\n> #\\Λ\n> > ( char-upcase #\\space )\n> #\\space\n> ```\n\n> ```\n(char-downcase char)  →  char?\n  char : char?```\n\n\nLike [char-upcase](#%28def._%28%28quote._~23~25kernel%29._char-upcase%29%29), but for the Unicode downcase mapping.\n\nExamples:\n\n> ```racket\n> > ( char-downcase #\\A )\n> #\\a\n> > ( char-downcase #\\Λ )\n> #\\λ\n> > ( char-downcase #\\space )\n> #\\space\n> ```\n\n> ```\n(char-titlecase char)  →  char?\n  char : char?\n```\nLike char-upcase, but for the Unicode titlecase mapping.\nExamples:\n> ```racket\n> > ( char-upcase #\\a )\n> #\\A\n> > ( char-upcase #\\λ )\n> #\\Λ\n> > ( char-upcase #\\space )\n> #\\space\n> ```\n> ```\n(char-foldcase char)  →  char?\n  char : char?```\nLike [char-upcase](#%28def._%28%28quote._~23~25kernel%29._char-upcase%29%29), but for the Unicode case-folding mapping.\nExamples:\n> ```racket\n> > ( char-foldcase #\\A )\n> #\\a\n> > ( char-foldcase #\\Σ )\n> #\\σ\n> > ( char-foldcase #\\ς )\n> #\\σ\n> > ( char-foldcase #\\space )\n> #\\space\n> ```"} {"text": "#### 4.6.5 Character Grapheme-Cluster Streaming\n> ```\n(char-grapheme-step char state)   →   boolean?   fixnum?\n  char : char?\n  state : fixnum?\n```\n(single)\t→\t\n(-> see Reading Symbols)```\n\n\nReturns #t if v is a symbol, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( symbol? ' Apple )\n> #t\n> > ( symbol? 10 )\n> #f\n> ```\n\n> ```\n(parameter)\t→\n```\n(parameter)\t→\t\n(-> parameter)```\nReturns #t if sym is an [unreadable symbol](#%28tech._unreadable._symbol%29), #f otherwise.\nExamples:\n> ```racket\n> > ( symbol-unreadable? ' Apple )\n> #f\n> > ( symbol-unreadable? ( gensym ) )\n> #f\n> > ( symbol-unreadable? ( string->unreadable-symbol \"Apple\" ) )\n> #t\n> ```\n> ```\n(parameter)\t→\n```\n(parameter)\t→\t\n(-> symbol → string ' Apple)```\n\n\nReturns an [interned](reader.html#%28tech._interned%29) symbol whose characters are the same as in str.\n\nExamples:\n\n> ```racket\n> > ( string->symbol \"Apple\" )\n> 'Apple\n> > ( string->symbol \"1\" )\n> '|1|\n> ```\n\n> ```\n(parameter)\t→\n```\n(parameter)\t→\t\n(-> string → uninterned-symbol \"Apple\")```\nLike ([string->symbol](#%28def._%28%28quote._~23~25kernel%29._string-~3esymbol%29%29) str), but the resulting symbol is a new [unreadable symbol](#%28tech._unreadable._symbol%29). Calling [string->unreadable-symbol](#%28def._%28%28quote._~23~25kernel%29._string-~3eunreadable-symbol%29%29) twice with equivalent strs returns the same symbol, but [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) never produces the symbol.\nExamples:"} {"text": "# 4.6 Characters\n> ```racket\n> > ( string->unreadable-symbol \"Apple\" )\n> 'Apple\n> > ( eq? ' a ( string->unreadable-symbol \"a\" ) )\n> #f\n> > ( eq? ( string->unreadable-symbol \"a\" ) ( string->unreadable-symbol \"a\" ) )\n> #t\n> ```\n> ```\n(parameter)\t→\t\n(-> or/c string? symbol?)\n```\n(parameter)\t→\t\n(-> require racket/symbol)```\n\n\nLike [symbol->string](#%28def._%28%28quote._~23~25kernel%29._symbol-~3estring%29%29), but the result is an immutable string, not necessarily freshly allocated.\n\nExamples:\n\n> ```racket\n> > ( symbol->immutable-string ' Apple )\n> \"Apple\"\n> > ( immutable? ( symbol->immutable-string ' Apple ) )\n> #t\n> ```\n\nAdded in version 7.6 of package base.\n\n------------------------------------------------------------------------\n\n# 4.8 Regular Expressions\n\n### 4.8 Regular Expressions\n\n> > > \"+\"[Regular Expressions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=regexp.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces regular expressions.\n\nRegular expressions are specified as strings or byte strings, using the same pattern language as either the Unix utility egrep or Perl. A string-specified pattern produces a character regexp matcher, and a byte-string pattern produces a byte regexp matcher. If a character regexp is used with a byte string or input port, it matches UTF-8 encodings (see [Encodings and Locales](encodings.html)) of matching character streams; if a byte regexp is used with a character string, it matches bytes in the UTF-8 encoding of the string.\n\nA regular expression that is represented as a string or byte string can be compiled to a regexp value, which can be used more efficiently by functions such as [regexp-match](#%28def._%28%28quote._~23~25kernel%29._regexp-match%29%29) compared to the string or byte string form. The [regexp](#%28def._%28%28quote._~23~25kernel%29._regexp%29%29) and [byte-regexp](#%28def._%28%28quote._~23~25kernel%29._byte-regexp%29%29) procedures convert a string or byte string (respectively) into a regexp value using a syntax of regular expressions that is most compatible to egrep. The [pregexp](#%28def._%28%28quote._~23~25kernel%29._pregexp%29%29) and [byte-pregexp](#%28def._%28%28quote._~23~25kernel%29._byte-pregexp%29%29) procedures produce a regexp value using a slightly different syntax of regular expressions that is more compatible with Perl.\n\nTwo [regexp values](#%28tech._regexp._value%29) are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) if they have the same source, use the same pattern language, and are both character regexps or both byte regexps.\n\nA literal or printed [regexp value](#%28tech._regexp._value%29) starts with #rx or #px. See [Reading Regular Expressions](reader.html#%28part._parse-regexp%29) for information on [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29)ing regular expressions and [Printing Regular Expressions](printing.html#%28part._print-regexp%29) for information on [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29)ing regular expressions. Regexp values produced by the default reader are [interned](reader.html#%28tech._interned%29) in [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29) mode.\n\nOn the [BC](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=performance.html%23%2528tech._bc%2529&version=8.18.0.13) variant of Racket, the internal size of a [regexp value](#%28tech._regexp._value%29) is limited to 32 kilobytes; this limit roughly corresponds to a source string with 32,000 literal characters or 5,000 operators.\n\n#### 4.8.1 Regexp Syntax\n\nThe following syntax specifications describe the content of a string that represents a regular expression. The syntax of the corresponding string may involve extra escape characters. For example, the regular expression (.\\*)\\\\1 can be represented with the string \"(.\\*)\\\\\\\\1\" or the regexp constant #rx\"(.\\*)\\\\\\\\1\"; the \\\\ in the regular expression must be escaped to include it in a string or regexp constant.\n\nThe [regexp](#%28def._%28%28quote._~23~25kernel%29._regexp%29%29) and [pregexp](#%28def._%28%28quote._~23~25kernel%29._pregexp%29%29) syntaxes share a common core:\n\n| | | | | | | |\n|:----|:---------|:-----:|:-----------------------|:----|:---------------------------------------------|:-------------------------------------|\n|   | ‹regexp› |  ::=  | ‹pces› |   | Match ‹pces› | |\n|   |   | \\| | ‹regexp›\\|‹regexp› |   | Match either ‹regexp›, try left first |  [ex1](#%28elem._%28rxex._1%29%29) |\n|   | ‹pces› |  ::=  | |   | Match empty | |\n|   |   | \\| | ‹pce›‹pces› |   | Match ‹pce› followed by ‹pces› | |\n|   | ‹pce› |  ::=  | ‹repeat› |   | Match ‹repeat›, longest possible |  [ex3](#%28elem._%28rxex._3%29%29) |\n|   |   | \\| | ‹repeat›? |   | Match ‹repeat›, shortest possible |  [ex6](#%28elem._%28rxex._6%29%29) |\n|   |   | \\| | ‹atom› |   | Match ‹atom› exactly once | |\n|   | ‹repeat› |  ::=  | ‹atom›\\* |   | Match ‹atom› 0 or more times |  [ex3](#%28elem._%28rxex._3%29%29) |\n|   |   | \\| | ‹atom›+ |   | Match ‹atom› 1 or more times |  [ex4](#%28elem._%28rxex._4%29%29) |\n|   |   | \\| | ‹atom›? |   | Match ‹atom› 0 or 1 times |  [ex5](#%28elem._%28rxex._5%29%29) |\n|   | ‹atom› |  ::=  | (‹regexp›) |   | Match sub-expression ‹regexp› and report |  [ex11](#%28elem._%28rxex._11%29%29) |\n|   |   | \\| | \\[‹rng›\\] |   | Match any character in ‹rng› |  [ex2](#%28elem._%28rxex._2%29%29) |\n|   |   | \\| | \\[^‹crng›\\] |   | Match any character not in ‹crng› |  [ex12](#%28elem._%28rxex._12%29%29) |\n|   |   | \\| | . |   | Match any (except newline in multi mode) |  [ex13](#%28elem._%28rxex._13%29%29) |\n|   |   | \\| | ^ |   | Match start (or after newline in multi mode) |  [ex14](#%28elem._%28rxex._14%29%29) |\n|   |   | \\| | $ |   | Match end (or before newline in multi mode) |  [ex15](#%28elem._%28rxex._15%29%29) |\n|   |   | \\| | ‹literal› |   | Match a single literal character |  [ex1](#%28elem._%28rxex._1%29%29) |\n|   |   | \\| | (?‹mode›:‹regexp›) |   | Match ‹regexp› using ‹mode› |  [ex35](#%28elem._%28rxex._35%29%29) |\n|   |   | \\| | (?>‹regexp›) |   | Match ‹regexp›, only first possible | |\n|   |   | \\| | ‹look› |   | Match empty if ‹look› matches | |\n|   |   | \\| | (?‹tst›‹pces›\\|‹pces›) |   | Match 1st ‹pces› if ‹tst›, else 2nd ‹pces› |  [ex36](#%28elem._%28rxex._36%29%29) |\n|   |   | \\| | (?‹tst›‹pces›) |   | Match ‹pces› if ‹tst›, empty if not ‹tst› | |\n|   |   | \\| | \\\\ at end of pattern |   | Match the nul character (ASCII 0) | |\n|   | ‹crng› |  ::=  | ‹rng› |   | ‹crng› contains everything in ‹rng› | |\n|   |   | \\| | ^‹crng› |   | ‹crng› contains ^ and everything in ‹crng› |  [ex37](#%28elem._%28rxex._37%29%29) |\n|   | ‹rng› |  ::=  | \\] |   | ‹rng› contains \\] only |  [ex27](#%28elem._%28rxex._27%29%29) |\n|   |   | \\| | \\- |   | ‹rng› contains - only |  [ex28](#%28elem._%28rxex._28%29%29) |\n|   |   | \\| | ‹mrng› |   | ‹rng› contains everything in ‹mrng› | |\n|   |   | \\| | ‹mrng›- |   | ‹rng› contains - and everything in ‹mrng› | |\n|   | ‹mrng› |  ::=  | \\]‹lrng› |   | ‹mrng› contains \\] and everything in ‹lrng› |  [ex29](#%28elem._%28rxex._29%29%29) |\n|   |   | \\| | -‹lrng› |   | ‹mrng› contains - and everything in ‹lrng› |  [ex29](#%28elem._%28rxex._29%29%29) |\n|   |   | \\| | ‹lirng› |   | ‹mrng› contains everything in ‹lirng› | |\n|   | ‹lirng› |  ::=  | ‹riliteral› |   | ‹lirng› contains a literal character | |\n|   |   | \\| | ‹riliteral›-‹rliteral› |   | ‹lirng› contains Unicode range inclusive |  [ex22](#%28elem._%28rxex._22%29%29) |\n|   |   | \\| | ‹lirng›‹lrng› |   | ‹lirng› contains everything in both | |\n|   | ‹lrng› |  ::=  | ^ |   | ‹lrng› contains ^ |  [ex30](#%28elem._%28rxex._30%29%29) |\n|   |   | \\| | ‹rliteral›-‹rliteral› |   | ‹lrng› contains Unicode range inclusive | |\n|   |   | \\| | ^‹lrng› |   | ‹lrng› contains ^ and more | |\n|   |   | \\| | ‹lirng› |   | ‹lrng› contains everything in ‹lirng› | |\n|   | ‹look› |  ::=  | (?=‹regexp›) |   | Match if ‹regexp› matches |  [ex31](#%28elem._%28rxex._31%29%29) |\n|   |   | \\| | (?!‹regexp›) |   | Match if ‹regexp› doesn’t match |  [ex32](#%28elem._%28rxex._32%29%29) |\n|   |   | \\| | (?\\<=‹regexp›) |   | Match if ‹regexp› matches preceding |  [ex33](#%28elem._%28rxex._33%29%29) |\n|   |   | \\| | (?\\ ```racket\n> > ( regexp-match #rx\"a|b\" \"cat\" ) ; ex 1\n> '(\"a\")\n> > ( regexp-match #rx\"[at]\" \"cat\" ) ; ex 2\n> '(\"a\")\n> > ( regexp-match #rx\"ca*[at]\" \"caaat\" ) ; ex 3\n> '(\"caaat\")\n> > ( regexp-match #rx\"ca+[at]\" \"caaat\" ) ; ex 4\n> '(\"caaat\")\n> > ( regexp-match #rx\"ca?t?\" \"ct\" ) ; ex 5\n> '(\"ct\")\n> > ( regexp-match #rx\"ca*?[at]\" \"caaat\" ) ; ex 6\n> '(\"ca\")\n> > ( regexp-match #px\"ca{2}\" \"caaat\" ) ; ex 7 , uses #px\n> '(\"caa\")\n> > ( regexp-match #px\"ca{2,}t\" \"catcaat\" ) ; ex 8 , uses #px\n> '(\"caat\")\n> > ( regexp-match #px\"ca{,2}t\" \"caaatcat\" ) ; ex 9 , uses #px\n> '(\"cat\")\n> > ( regexp-match #px\"ca{1,2}t\" \"caaatcat\" ) ; ex 10 , uses #px\n> '(\"cat\")\n> > ( regexp-match #rx\"(c<*)(a*)\" \"caat\" ) ; ex 11> '(\"caa\" \"c\" \"aa\")\n> > ( regexp-match #rx\"[^ca]\" \"caat\" ) ; ex 12\n> '(\"t\")\n> > ( regexp-match #rx\".(.).\" \"cat\" ) ; ex 13\n> '(\"cat\" \"a\")\n> > ( regexp-match #rx\"^a|^c\" \"cat\" ) ; ex 14\n> '(\"c\")\n> > ( regexp-match #rx\"a$|t$\" \"cat\" ) ; ex 15\n> '(\"t\")\n> > ( regexp-match #px\"c(.)\\\\1t\" \"caat\" ) ; ex 16 , uses #px\n> '(\"caat\" \"a\")\n> > ( regexp-match #px\".\\\\b.\" \"cat in hat\" ) ; ex 17 , uses #px\n> '(\"t \")\n> > ( regexp-match #px\".\\\\B.\" \"cat in hat\" ) ; ex 18 , uses #px\n> '(\"ca\")\n> > ( regexp-match #px\"\\\\p{Ll}\" \"Cat\" ) ; ex 19 , uses #px\n> '(\"a\")\n> > ( regexp-match #px\"\\\\P{Ll}\" \"cat!\" ) ; ex 20 , uses #px\n> '(\"!\")\n> > ( regexp-match #rx\"\\\\|\" \"c|t\" ) ; ex 21\n> '(\"|\")\n> > ( regexp-match #rx\"[a-f]*\" \"cat\" ) ; ex 22\n> '(\"ca\")\n> > ( regexp-match #px\"[a-f\\\\d]*\" \"1cat\" ) ; ex 23 , uses #px\n> '(\"1ca\")\n> > ( regexp-match #px\" [\\\\w]\" \"cat hat\" ) ; ex 24 , uses #px\n> '(\" h\")\n> > ( regexp-match #px\"t[\\\\s]\" \"cat\\nhat\" ) ; ex 25 , uses #px\n> '(\"t\\n\")\n> > ( regexp-match #px\"[[:lower:]]+\" \"Cat\" ) ; ex 26 , uses #px\n> '(\"at\")\n> > ( regexp-match #rx\"[]]\" \"c]t\" ) ; ex 27\n> '(\"]\")\n> > ( regexp-match #rx\"[-]\" \"c-t\" ) ; ex 28\n> '(\"-\")\n> > ( regexp-match #rx\"[]a[]+\" \"c[a]t\" ) ; ex 29\n> '(\"[a]\")\n> > ( regexp-match #rx\"[a^]+\" \"ca^t\" ) ; ex 30\n> '(\"a^\")\n> > ( regexp-match #rx\".a(?=p)\" \"cat nap\" ) ; ex 31\n> '(\"na\")\n> > ( regexp-match #rx\".a(?!t)\" \"cat nap\" ) ; ex 32\n> '(\"na\")\n> > ( regexp-match #rx\"(?<=n)a.\" \"cat nap\" ) ; ex 33> '(\"ap\")\n> > ( regexp-match #rx\"(? '(\"ap\")\n> > ( regexp-match #rx\"(?i:a)[tp]\" \"cAT nAp\" ) ; ex 35\n> '(\"Ap\")\n> > ( regexp-match #rx\"(?(?<=c)a|b)+\" \"cabal\" ) ; ex 36> '(\"ab\")\n> > ( regexp-match #rx\"[^^]+\" \"^cat^\" ) ; ex 37\n> '(\"cat\")\n> ```\n\nChanged in version 8.15.0.8 of package base: Added \\\\X grapheme cluster pattern.\n\n#### 4.8.2 Additional Syntactic Constraints\n\nIn addition to matching a grammar, regular expressions must meet two syntactic restrictions:\n\n- In a ‹repeat› other than ‹atom›?, the ‹atom› must not match an empty sequence.\n\n- In a (?\\<=‹regexp›) or (?\\

 ‹regexp›1 : [n1, m1]   ‹regexp›2 : [n2, m2] 

 ‹regexp›1|‹regexp›2 : [min(n1, n2), max(m1, m2)] 

 

 ‹pce› : [n1, m1]   ‹pces› : [n2, m2] 

 ‹pce›‹pces› : [n1+n2, m1+m2] 

 

 ‹repeat› : [n, m] 

 ‹repeat›? : [0, m] 

   

 ‹atom› : [n, m]   n > 0 

 ‹atom›* : [0, ∞] 

 

 ‹atom› : [n, m]   n > 0 

 ‹atom›+ : [1, ∞] 

   

 ‹atom› : [n, m] 

 ‹atom›? : [0, m] 

 

 ‹atom› : [n, m]   n > 0 

 ‹atom›{‹n›} : [n*‹n›, m*‹n›] 

 

 ‹atom› : [n, m]   n > 0 

 ‹atom›{‹n›,} : [n*‹n›, ∞] 

 

 ‹atom› : [n, m]   n > 0 

 ‹atom›{,‹m›} : [0, m*‹m›] 

 

 ‹atom› : [n, m]   n > 0 

 ‹atom›{‹n›,‹m›} : [n*‹n›, m*‹m›] 

 

 ‹regexp› : [n, m] 

 (‹regexp›) : [n, m]   α‹n›=n 

 

 ‹regexp› : [n, m] 

 (?‹mode›:‹regexp›) : [n, m] 

 

 ‹regexp› : [n, m] 

 (?=‹regexp›) : [0, 0] 

   

 ‹regexp› : [n, m] 

 (?!‹regexp›) : [0, 0] 

 

 ‹regexp› : [n, m]   m < ∞ 

 (?<=‹regexp›) : [0, 0] 

   

 ‹regexp› : [n, m]   m < ∞ 

 (?<!‹regexp›) : [0, 0] 

 

 ‹regexp› : [n, m] 

 (?>‹regexp›) : [n, m] 

 

 ‹tst› : [n0, m0]   ‹pces›1 : [n1, m1]   ‹pces›2 : [n2, m2] 

 (?‹tst›‹pces›1|‹pces›2) : [min(n1, n2), max(m1, m2)] 

 

 ‹tst› : [n0, m0]   ‹pces› : [n1, m1] 

 (?‹tst›‹pces›) : [0, m1] 

 

(‹n›) : [α‹n›, ∞]

   

[‹rng›] : [1, 1]

   

[^‹rng›] : [1, 1]

 

. : [1, 1]

   

^ : [0, 0]

   

$ : [0, 0]

 

‹literal› : [1, 1]

   

\\‹n› : [α‹n›, ∞]

   

‹class› : [1, 1]

 

\\b : [0, 0]

   

\\B : [0, 0]

 

\\p{‹property›} : [1, 6]

   

\\P{‹property›} : [1, 6]

 

\\X : [1, ∞]

\n\n#### 4.8.3 Regexp Constructors\n\n> ```\n(regexp? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 4.6 Characters\nReturns #t if v is a regexp value created by regexp or pregexp, #f otherwise.\n> ```\n(pregexp? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a [regexp value](#%28tech._regexp._value%29) created by [pregexp](#%28def._%28%28quote._~23~25kernel%29._pregexp%29%29) (not [regexp](#%28def._%28%28quote._~23~25kernel%29._regexp%29%29)), #f otherwise.\n> ```\n(byte-regexp? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a regexp value created by byte-regexp or byte-pregexp, #f otherwise.\n\n> ```\n(byte-pregexp? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a [regexp value](#%28tech._regexp._value%29) created by [byte-pregexp](#%28def._%28%28quote._~23~25kernel%29._byte-pregexp%29%29) (not [byte-regexp](#%28def._%28%28quote._~23~25kernel%29._byte-regexp%29%29)), #f otherwise.\n\n> ```\n(regexp str)  →  regexp?\n  str : string?\n(regexp str handler)  →  any\n  str : string?\n  handler : (or/c #f (string? . → . any))\n```\nTakes a string representation of a regular expression (using the syntax in Regexp Syntax) and compiles it into a regexp value. Other regular expression procedures accept either a string or a regexp value as the matching pattern. If a regular expression string is used multiple times, it is faster to compile the string once to a regexp value and use it for repeated matches instead of using the string each time."} {"text": "# 4.6 Characters\nIf handler is provided and not #f, it is called and its result is returned when str is not a valid representation of a regular expression; the argument to handler is a string that describes the problem with str. If handler is #f or not provided, then exn:fail:contract exception is raised.\nThe object-name procedure returns the source string for a regexp value.\nExamples:\n> ```racket\n> > ( regexp \"ap*le\" )\n> #rx\"ap*le\"\n> > ( object-name #rx\"ap*le\" )\n> \"ap*le\"\n> > ( regexp \"+\" ( λ ( s ) ( list s ) ) )\n> '(\"`+` follows nothing in pattern\")\n> ```\nChanged in version 6.5.0.1 of package base: Added the handler argument.\n> ```\n(pregexp str)  →  pregexp?\n  str : string?\n(pregexp str handler)  →  any\n  str : string?\n  handler : (or/c #f (string? . → . any))```\nLike [regexp](#%28def._%28%28quote._~23~25kernel%29._regexp%29%29), except that it uses a slightly different syntax (see [Regexp Syntax](#%28part._regexp-syntax%29)). The result can be used with [regexp-match](#%28def._%28%28quote._~23~25kernel%29._regexp-match%29%29), etc., just like the result from [regexp](#%28def._%28%28quote._~23~25kernel%29._regexp%29%29).\nExamples:\n> ```racket\n> > ( pregexp \"ap*le\" )\n> #px\"ap*le\"\n> > ( regexp? #px\"ap*le\" )\n> #t\n> > ( pregexp \"+\" ( λ ( s ) ( vector s ) ) )\n> '#(\"`+` follows nothing in pattern\")\n> ```\nChanged in version 6.5.0.1 of package base: Added the handler argument.\n> ```\n(byte-regexp bstr)  →  byte-regexp?\n  bstr : bytes?\n(byte-regexp bstr handler)  →  any\n  bstr : bytes?\n  handler : (or/c #f (bytes? . → . any))"} {"text": "# 4.6 Characters\n```\nTakes a byte-string representation of a regular expression (using the syntax in Regexp Syntax) and compiles it into a byte-regexp value.\n\nIf handler is provided, it is called and its result is returned if bstr is not a valid representation of a regular expression.\n\nThe object-name procedure returns the source byte string for a regexp value.\n\nExamples:\n\n> ```racket\n> > ( byte-regexp #\"ap*le\" )\n> #rx#\"ap*le\"\n> > ( object-name #rx#\"ap*le\" )\n> #\"ap*le\"\n> > ( byte-regexp \"ap*le\" )\n> byte-regexp: contract violation\n> expected: bytes?\n> given: \"ap*le\"\n> > ( byte-regexp #\"+\" ( λ ( s ) ( list s ) ) )\n> '(\"`+` follows nothing in pattern\")\n> ```\n\nChanged in version 6.5.0.1 of package base: Added the handler argument.\n\n> ```\n(byte-pregexp bstr)  →  byte-pregexp?\n  bstr : bytes?\n(byte-pregexp bstr handler)  →  any\n  bstr : bytes?\n  handler : (or/c #f (bytes? . → . any))```\n\n\nLike [byte-regexp](#%28def._%28%28quote._~23~25kernel%29._byte-regexp%29%29), except that it uses a slightly different syntax (see [Regexp Syntax](#%28part._regexp-syntax%29)). The result can be used with [regexp-match](#%28def._%28%28quote._~23~25kernel%29._regexp-match%29%29), etc., just like the result from [byte-regexp](#%28def._%28%28quote._~23~25kernel%29._byte-regexp%29%29).\n\nExamples:\n\n> ```racket\n> > ( byte-pregexp #\"ap*le\" )\n> #px#\"ap*le\"\n> > ( byte-pregexp #\"+\" ( λ ( s ) ( vector s ) ) )\n> '#(\"`+` follows nothing in pattern\")\n> ```\n\nChanged in version 6.5.0.1 of package base: Added the handler argument.\n\n> ```\n(regexp-quote str [case-sensitive?) → string?\n  str : string?\n  case-sensitive? : any/c = #t\n(regexp-quote bstr [case-sensitive?)  →  bytes?\n  bstr : bytes?\n  case-sensitive? : any/c = #t\n```"} {"text": "# 4.6 Characters\nProduces a string or byte string suitable for use with regexp to match the literal sequence of characters in str or sequence of bytes in bstr. If case-sensitive? is true (the default), the resulting regexp matches letters in str or bstr case-sensitively, otherwise it matches case-insensitively.\nExamples:\n> ```racket\n> > ( regexp-match \".\" \"apple.scm\" )\n> '(\"a\")\n> > ( regexp-match ( regexp-quote \".\" ) \"apple.scm\" )\n> '(\".\")\n> ```\n> ```\n(pregexp-quote str [case-sensitive?) → string?\n  str : string?\n  case-sensitive? : any/c = #t\n(pregexp-quote bstr [case-sensitive?)  →  bytes?\n  bstr : bytes?\n  case-sensitive? : any/c = #t```\nLike [regexp-quote](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._regexp-quote%29%29), but intended for use with [pregexp](#%28def._%28%28quote._~23~25kernel%29._pregexp%29%29). Escapes all non-alphanumeric, non-underscore characters in the input.\nAdded in version 8.11.1.9 of package base.\n> ```\n(regexp-max-lookbehind pattern)  →  exact-nonnegative-integer?\n  pattern : (or/c regexp? byte-regexp?)"} {"text": "# 4.6 Characters\n```\nReturns the maximum number of bytes that pattern may consult before the starting position of a match to determine the match. For example, the pattern (?\\<=abc)d consults three bytes preceding a matching d, while e(?\\<=a..)d consults two bytes before a matching ed. A ^ pattern may consult a preceding byte to determine whether the current position is the start of the input or of a line.\n\nExamples:\n\n> ```racket\n> > ( regexp-max-lookbehind #rx#\"(?<=abc)d\" )> 3\n> > ( regexp-max-lookbehind #rx#\"e(?<=a..)d\" )> 2\n> > ( regexp-max-lookbehind #rx\"^\" )\n> 1\n> ```\n\n> ```\n(regexp-capture-group-count pattern)\n  →  exact-nonnegative-integer?\n  pattern : (or/c regexp? byte-regexp?)```\n\n\nReturns the number of capture groups that are in pattern, which corresponds to one less than the length of the list returned by [regexp-match](#%28def._%28%28quote._~23~25kernel%29._regexp-match%29%29) for a successful match to pattern.\n\nExamples:\n\n> ```racket\n> > ( regexp-capture-group-count #rx\"abcd\" )\n> 0\n> > ( regexp-capture-group-count #rx\"a(b*c)(d*)\" )\n> 2\n> > ( regexp-capture-group-count #rx\"a(?:bc)*d\" )\n> 0\n> ```\n\nAdded in version 8.15.0.8 of package base.\n\n#### 4.8.4 Regexp Matching\n\n> ```\n(regexp-match pattern\n    input  \n   [ start-pos  \n    end-pos  \n    output-port  \n    input-prefix)  \n\n  →   ( if ( and ( or ( string? pattern ) ( regexp? pattern ) )\n> ( or ( string? input ) ( path? input ) ) )\n> ( or/c #f ( cons/c string? ( listof ( or/c string? #f ) ) ) )\n> ( or/c #f ( cons/c bytes? ( listof ( or/c bytes? #f ) ) ) ) )\n\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : (or/c string? bytes? path? input-port?)\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  output-port : (or/c output-port? #f) = #f\n  input-prefix : bytes? = #\"\"\n```"} {"text": "# 4.6 Characters\n(byte)\t→\t\n(-> in the case of an input port)```\nLike [regexp-match](#%28def._%28%28quote._~23~25kernel%29._regexp-match%29%29), but the result is a list of strings or byte strings corresponding to a sequence of matches of pattern in input.\nThe pattern is used in order to find matches, where each match attempt starts at the end of the last match, and ^ is allowed to match the beginning of the input (if input-prefix is #\"\") only for the first match. Empty matches are handled like other matches, returning a zero-length string or byte sequence (they are more useful in making this a complement of [regexp-split](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._regexp-split%29%29)), but pattern is restricted from matching an empty sequence immediately after an empty match.\nIf input contains no matches (in the range start-pos to end-pos), [null](pairs.html#%28def._%28%28quote._~23~25kernel%29._null%29%29) is returned. Otherwise, each item in the resulting list is a distinct substring or byte sequence from input that matches pattern. The end-pos argument can be #f to match to the end of input (which corresponds to an end-of-file if input is an input port).\nExamples:\n> ```racket\n> > ( regexp-match* #rx\"x.\" \"12x4x6\" )\n> '(\"x4\" \"x6\")\n> > ( regexp-match* #rx\"x*\" \"12x4x6\" )\n> '(\"\" \"\" \"x\" \"\" \"x\" \"\" \"\")\n> ```"} {"text": "# 4.6 Characters\nThe match-select function specifies the collected results. The default of [car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) means that the result is the list of matches without returning parenthesized sub-patterns. It can be given as a “selector” function which chooses an item from a list, or it can choose a list of items. For example, you can use [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) to get a list of lists of parenthesized sub-patterns matches, or [values](values.html#%28def._%28%28quote._~23~25kernel%29._values%29%29) (as an identity function) to get the full matches as well. (Note that the selector must choose an element of its input list or a list of elements, but it must not inspect its input as they can be either a list of strings or a list of position pairs. Furthermore, the selector must be consistent in its choice(s).)\nExamples:\n> ```racket\n> > ( regexp-match* #rx\"x(.)\" \"12x4x6\" #:match-select cadr )\n> '(\"4\" \"6\")\n> > ( regexp-match* #rx\"x(.)\" \"12x4x6\" #:match-select values )\n> '((\"x4\" \"4\") (\"x6\" \"6\"))\n> ```\nIn addition, specifying gap-select as a non-#f value will make the result an interleaved list of the matches as well as the separators between them matches, starting and ending with a separator. In this case, match-select can be given as #f to return only the separators, making such uses equivalent to [regexp-split](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._regexp-split%29%29).\nExamples:"} {"text": "# 4.6 Characters\n> ```racket\n> > ( regexp-match* #rx\"x(.)\" \"12x4x6\" #:match-select cadr #:gap-select? #t )\n> '(\"12\" \"4\" \"\" \"6\" \"\")\n> > ( regexp-match* #rx\"x(.)\" \"12x4x6\" #:match-select #f #:gap-select? #t )\n> '(\"12\" \"\" \"\")\n> ```\n> ```\n(regexp-try-match pattern\n    input  \n   [ start-pos  \n    end-pos  \n    output-port  \n    input-prefix)  \n  →  (or/c #f (cons/c bytes? (listof (or/c bytes? #f))))\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : input-port?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  output-port : (or/c output-port? #f) = #f\n  input-prefix : bytes? = #\"\""} {"text": "# 4.6 Characters\n```\nLike regexp-match on input ports, except that if the match fails, no characters are read and discarded from in.\n\nThis procedure is especially useful with a pattern that begins with a start-of-string ^ or with a non-#f end-pos, since each limits the amount of peeking into the port. Otherwise, beware that a large portion of the stream may be peeked (and therefore pulled into memory) before the match succeeds or fails.\n\n> ```\n(regexp-match-positions pattern\n    input  \n   [ start-pos  \n    end-pos  \n    output-port  \n    input-prefix)  \n\n  →   ( or/c ( cons/c ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? )\n> ( listof ( or/c ( cons/c exact-integer?\n> exact-integer? )\n> #f ) ) )\n> #f )\n\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : (or/c string? bytes? path? input-port?)\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  output-port : (or/c output-port? #f) = #f\n  input-prefix : bytes? = #\"\"```\n\n\nLike [regexp-match](#%28def._%28%28quote._~23~25kernel%29._regexp-match%29%29), but returns a list of number pairs (and #f) instead of a list of strings. Each pair of numbers refers to a range of characters or bytes in input. If the result for the same arguments with [regexp-match](#%28def._%28%28quote._~23~25kernel%29._regexp-match%29%29) would be a list of byte strings, the resulting ranges correspond to byte ranges; in that case, if input is a character string, the byte ranges correspond to bytes in the UTF-8 encoding of the string.\n\nRange results are returned in a [substring](strings.html#%28def._%28%28quote._~23~25kernel%29._substring%29%29)- and [subbytes](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._subbytes%29%29)-compatible manner, independent of start-pos. In the case of an input port, the returned positions indicate the number of bytes that were read, including start-pos, before the first matching byte.\n\nExamples:\n\n> ```racket\n> > ( regexp-match-positions #rx\"x.\" \"12x4x6\" )\n> '((2 . 4))\n> > ( regexp-match-positions #rx\"x.\" \"12x4x6\" 3 )\n> '((4 . 6))\n> > ( regexp-match-positions #rx\"(-[0-9]*)+\" \"a-12--345b\" )\n> '((1 . 9) (5 . 9))\n> ```\n\nRange results after the first one can include negative numbers if input-prefix is non-empty and if pattern includes a lookbehind pattern. Such ranges start in the input-prefix instead of input. More generally, when start-pos is positive, then range results that are less than start-pos start in input-prefix.\n\nExamples:\n\n> ```racket\n> > ( regexp-match-positions #rx\"(?<=(.)).\" \"a\" 0 #f #f #\"x\" )> '((0 . 1) (-1 . 0))\n> > ( regexp-match-positions #rx\"(?<=(..)).\" \"a\" 0 #f #f #\"x\" )> #f\n> > ( regexp-match-positions #rx\"(?<=(..)).\" \"_a\" 1 #f #f #\"x\" )> #f\n> ```\n\nAlthough input-prefix is always a byte string, when the returned positions are string indices and they refer to a portion of input-prefix, then they correspond to a UTF-8 decoding of a tail of input-prefix.\n\nExamples:\n\n> ```racket\n> > ( bytes-length ( string->bytes/utf-8 \"λ\" ) )\n> 2\n> > ( regexp-match-positions #rx\"(?<=(.)).\" \"a\" 0 #f #f ( string->bytes/utf-8 \"λ\" ) )\n> '((0 . 1) (-1 . 0))\n> ```\n\n> ```\n(regexp-match-positions* pattern\n    input  \n   [ start-pos  \n    end-pos  \n    input-prefix  \n    #:match-select match-select)  \n\n  →   ( or/c ( listof ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? ) )\n> ( listof ( listof ( or/c #f ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? ) ) ) ) )\n\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : (or/c string? bytes? path? input-port?)\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  input-prefix : bytes? = #\"\"\n  match-select : (list? . → . (or/c any/c list?)) = car\n```"} {"text": "# 4.6 Characters\nLike regexp-match-positions, but returns multiple matches like regexp-match*.\nExamples:\n> ```racket\n> > ( regexp-match-positions* #rx\"x.\" \"12x4x6\" )\n> '((2 . 4) (4 . 6))\n> > ( regexp-match-positions* #rx\"x(.)\" \"12x4x6\" #:match-select cadr )\n> '((3 . 4) (5 . 6))\n> ```\nNote that unlike regexp-match*, there is no #:gap-select? input keyword, as this information can be easily inferred from the resulting matches.\n> ```\n(regexp-match? pattern\n    input        \n   [ start-pos        \n    end-pos        \n    output-port        \n    input-prefix)   →   boolean?\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : (or/c string? bytes? path? input-port?)\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  output-port : (or/c output-port? #f) = #f\n  input-prefix : bytes? = #\"\"```\nLike [regexp-match](#%28def._%28%28quote._~23~25kernel%29._regexp-match%29%29), but returns merely #t when the match succeeds, #f otherwise.\nExamples:\n> ```racket\n> > ( regexp-match? #rx\"x.\" \"12x4x6\" )\n> #t\n> > ( regexp-match? #rx\"y.\" \"12x4x6\" )\n> #f\n> ```\n> ```\n(regexp-match-exact? pattern input)  →  boolean?\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : (or/c string? bytes? path?)"} {"text": "# 4.6 Characters\n```\nLike regexp-match?, but #t is only returned when the first found match is to the entire content of input.\n\nExamples:\n\n> ```racket\n> > ( regexp-match-exact? #rx\"x.\" \"12x4x6\" )\n> #f\n> > ( regexp-match-exact? #rx\"1.*x.\" \"12x4x6\" )\n> #t\n> ```\n\nBeware that regexp-match-exact? can return #f if pattern generates a partial match for input first, even if pattern could also generate a complete match. To check if there is any match of pattern that covers all of input, use regexp-match? with ^(?:pattern)$ instead.\n\nExamples:\n\n> ```racket\n> > ( regexp-match-exact? #rx\"a|ab\" \"ab\" )\n> #f\n> > ( regexp-match? #rx\"^(?:a|ab)$\" \"ab\" )\n> #t\n> ```\n\nThe (?:) grouping is necessary because concatenation has lower precedence than alternation; the regular expression without it, ^a\\|ab$, matches any input that either starts with a or ends with ab.\n\nExample:\n\n> ```racket\n> > ( regexp-match? #rx\"^a|ab$\" \"123ab\" )\n> #t\n> ```\n\n> ```\n(regexp-match-peek pattern\n    input  \n   [ start-pos  \n    end-pos  \n    progress  \n    input-prefix)  \n\n  →   ( or/c ( cons/c bytes? ( listof ( or/c bytes? #f ) ) )\n> #f )\n\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : input-port?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  progress : (or/c progress-evt? #f) = #f\n  input-prefix : bytes? = #\"\"```\n\n\nLike [regexp-match](#%28def._%28%28quote._~23~25kernel%29._regexp-match%29%29) on input ports, but only peeks bytes from input instead of reading them. Furthermore, instead of an output port, the optional progress argument is a progress event for input (see [port-progress-evt](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._port-progress-evt%29%29)). If progress becomes ready, then the match stops peeking from input and returns #f. The progress argument can be #f, in which case the peek may continue with inconsistent information if another process meanwhile reads from input.\n\nExamples:\n\n> ```racket\n> > ( define p ( open-input-string \"a abcd\" ) )\n> > ( regexp-match-peek \".*bc\" p )\n> '(#\"a abc\")\n> > ( regexp-match-peek \".*bc\" p 2 )\n> '(#\"abc\")\n> > ( regexp-match \".*bc\" p 2 )\n> '(#\"abc\")\n> > ( peek-char p )\n> #\\d\n> > ( regexp-match \".*bc\" p )\n> #f\n> > ( peek-char p )\n> #\n> ```\n\n> ```\n(regexp-match-peek-positions pattern\n    input  \n   [ start-pos  \n    end-pos  \n    progress  \n    input-prefix)  \n\n  →   ( or/c ( cons/c ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? )\n> ( listof ( or/c ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? )\n> #f ) ) )\n> #f )\n\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : input-port?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  progress : (or/c progress-evt? #f) = #f\n  input-prefix : bytes? = #\"\"\n```"} {"text": "# 4.6 Characters\nLike regexp-match-positions on input ports, but only peeks bytes from input instead of reading them, and with a progress argument like regexp-match-peek.\n> ```\n(regexp-match-peek-immediate pattern\n    input  \n   [ start-pos  \n    end-pos  \n    progress  \n    input-prefix)  \n  →   ( or/c ( cons/c bytes? ( listof ( or/c bytes? #f ) ) )\n> #f )\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : input-port?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  progress : (or/c progress-evt? #f) = #f\n  input-prefix : bytes? = #\"\"```\nLike [regexp-match-peek](#%28def._%28%28quote._~23~25kernel%29._regexp-match-peek%29%29), but it attempts to match only bytes that are available from input without blocking. The match fails if not-yet-available characters might be used to match pattern.\n> ```\n(regexp-match-peek-positions-immediate pattern\n    input  \n   [ start-pos  \n    end-pos  \n    progress  \n    input-prefix)  \n  →   ( or/c ( cons/c ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? )\n> ( listof ( or/c ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? )\n> #f ) ) )\n> #f )\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : input-port?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  progress : (or/c progress-evt? #f) = #f\n  input-prefix : bytes? = #\"\""} {"text": "# 4.6 Characters\n```\nLike regexp-match-peek-positions, but it attempts to match only bytes that are available from input without blocking. The match fails if not-yet-available characters might be used to match pattern.\n\n> ```\n(regexp-match-peek-positions* pattern\n    input  \n   [ start-pos  \n    end-pos  \n    input-prefix  \n    #:match-select match-select)  \n\n  →   ( or/c ( listof ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? ) )\n> ( listof ( listof ( or/c #f ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? ) ) ) ) )\n\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : input-port?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  input-prefix : bytes? = #\"\"\n  match-select : (list? . → . (or/c any/c list?)) = car```\n\n\nLike [regexp-match-peek-positions](#%28def._%28%28quote._~23~25kernel%29._regexp-match-peek-positions%29%29), but returns multiple matches like [regexp-match-positions*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._regexp-match-positions%2A%29%29).\n\n> ```\n(regexp-match/end pattern\n    input  \n   [ start-pos  \n    end-pos  \n    output-port  \n    input-prefix  \n    count)  \n\n  →   ( if ( and ( or ( string? pattern ) ( regexp? pattern ) )\n> ( or/c ( string? input ) ( path? input ) ) )\n> ( or/c #f ( cons/c string? ( listof ( or/c string? #f ) ) ) )\n> ( or/c #f ( cons/c bytes? ( listof ( or/c bytes? #f ) ) ) ) )\n(or/c #f bytes?)\n\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : (or/c string? bytes? path? input-port?)\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  output-port : (or/c output-port? #f) = #f\n  input-prefix : bytes? = #\"\"\n  count : exact-nonnegative-integer? = 1\n```"} {"text": "# 4.6 Characters\nLike regexp-match, but with a second result: a byte string of up to count bytes that correspond to the input (possibly including the input-prefix) leading to the end of the match; the second result is #f if no match is found.\nThe second result can be useful as an input-prefix for attempting a second match on input starting from the end of the first match. In that case, use regexp-max-lookbehind to determine an appropriate value for count.\n> ```\n(regexp-match-positions/end pattern\n    input  \n   [ start-pos  \n    end-pos  \n    input-prefix  \n    count)  \n  →   ( listof ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? ) )\n(or/c #f bytes?)\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : (or/c string? bytes? path? input-port?)\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  input-prefix : bytes? = #\"\"\n  count : exact-nonnegative-integer? = 1\n(regexp-match-peek-positions/end   pattern  \n    input  \n   [ start-pos  \n    end-pos  \n    progress  \n    input-prefix  \n    count)  \n  →   ( or/c ( cons/c ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? )\n> ( listof ( or/c ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? )\n> #f ) ) )\n> #f )\n(or/c #f bytes?)\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : input-port?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  progress : (or/c progress-evt? #f) = #f\n  input-prefix : bytes? = #\"\"\n  count : exact-nonnegative-integer? = 1"} {"text": "# 4.6 Characters\n(regexp-match-peek-positions-immediate/end   pattern  \n    input  \n   [ start-pos  \n    end-pos  \n    progress  \n    input-prefix  \n    count)  \n  →   ( or/c ( cons/c ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? )\n> ( listof ( or/c ( cons/c exact-nonnegative-integer?\n> exact-nonnegative-integer? )\n> #f ) ) )\n> #f )\n(or/c #f bytes?)\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : input-port?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  progress : (or/c progress-evt? #f) = #f\n  input-prefix : bytes? = #\"\"\n  count : exact-nonnegative-integer? = 1```\nLike [regexp-match-positions](#%28def._%28%28quote._~23~25kernel%29._regexp-match-positions%29%29), etc., but with a second result like [regexp-match/end](#%28def._%28%28quote._~23~25kernel%29._regexp-match%2Fend%29%29)."} {"text": "#### 4.8.5 Regexp Splitting\n> ```\n(regexp-split pattern\n    input  \n   [ start-pos  \n    end-pos  \n    input-prefix)  \n  →   ( if ( and ( or ( string? pattern ) ( regexp? pattern ) )\n> ( string? input ) )\n> ( cons/c string? ( listof string? ) )\n> ( cons/c bytes? ( listof bytes? ) ) )\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : (or/c string? bytes? input-port?)\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  input-prefix : bytes? = #\"\"\n```\nThe complement of regexp-match*: the result is a list of strings (if pattern is a string or character regexp and input is a string) or byte strings (otherwise) from input that are separated by matches to pattern. Adjacent matches are separated with \"\" or #\"\". Zero-length matches are treated the same as for regexp-match*.\n\nIf input contains no matches (in the range start-pos to end-pos), the result is a list containing input’s content (from start-pos to end-pos) as a single element. If a match occurs at the beginning of input (at start-pos), the resulting list will start with an empty string or byte string, and if a match occurs at the end (at end-pos), the list will end with an empty string or byte string. The end-pos argument can be #f, in which case splitting goes to the end of input (which corresponds to an end-of-file if input is an input port).\n\nExamples:\n\n> ```racket\n> > ( regexp-split #rx\" +\" \"12 34\" )\n> '(\"12\" \"34\")\n> > ( regexp-split #rx\".\" \"12 34\" )\n> '(\"\" \"\" \"\" \"\" \"\" \"\" \"\")\n> > ( regexp-split #rx\"\" \"12 34\" )\n> '(\"\" \"1\" \"2\" \" \" \" \" \"3\" \"4\" \"\")\n> > ( regexp-split #rx\" *\" \"12 34\" )\n> '(\"\" \"1\" \"2\" \"\" \"3\" \"4\" \"\")\n> > ( regexp-split #px\"\\\\b\" \"12, 13 and 14.\" )\n> '(\"\" \"12\" \", \" \"13\" \" \" \"and\" \" \" \"14\" \".\")\n> > ( regexp-split #rx\" +\" \"\" )\n> '(\"\")\n> ```\n\n#### 4.8.6 Regexp Substitution\n\n> ```\n(regexp-replace pattern\n    input  \n    insert  \n   [ input-prefix)  \n\n  →   ( if ( and ( or ( string? pattern ) ( regexp? pattern ) )\n> ( string? input ) )\n> string?\n> bytes? )\n\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : (or/c string? bytes?)\n   insert   :   ( or/c string? bytes?\n> ( string? string? ... . → . string? )\n> ( bytes? bytes? ... . → . bytes? ) )\n\n  input-prefix : bytes? = #\"\"```\n\n\nPerforms a match using pattern on input, and then returns a string or byte string in which the matching portion of input is replaced with insert. If pattern matches no part of input, then input is returned unmodified.\n\nThe insert argument can be either a (byte) string, or a function that returns a (byte) string. In the latter case, the function is applied on the list of values that [regexp-match](#%28def._%28%28quote._~23~25kernel%29._regexp-match%29%29) would return (i.e., the first argument is the complete match, and then one argument for each parenthesized sub-expression) to obtain a replacement (byte) string.\n\nIf pattern is a string or character regexp and input is a string, then insert must be a string or a procedure that accept strings, and the result is a string. If pattern is a byte string or byte regexp, or if input is a byte string, then insert as a string is converted to a byte string, insert as a procedure is called with a byte string, and the result is a byte string.\n\nIf insert contains &, then & is replaced with the matching portion of input before it is substituted into the match’s place. If insert contains \\\\‹n› for some integer ‹n›, then it is replaced with the ‹n›th matching sub-expression from input. A & and \\\\0 are aliases. If the ‹n›th sub-expression was not used in the match, or if ‹n› is greater than the number of sub-expressions in pattern, then \\\\‹n› is replaced with the empty string.\n\nTo substitute a literal & or \\\\, use \\\\& and \\\\\\\\, respectively, in insert. A \\\\$ in insert is equivalent to an empty sequence; this can be used to terminate a number ‹n› following \\\\. If a \\\\ in insert is followed by anything other than a digit, &, \\\\, or $, then the \\\\ by itself is treated as \\\\0.\n\nNote that the \\\\ described in the previous paragraphs is a character or byte of insert. To write such an insert as a Racket string literal, an escaping \\\\ is needed before the \\\\. For example, the Racket constant \"\\\\\\\\1\" is \\\\1.\n\nExamples:\n\n> ```racket\n> > ( regexp-replace #rx\"mi\" \"mi casa\" \"su\" )\n> \"su casa\"\n> > ( regexp-replace #rx\"mi\" \"mi casa\" string-upcase )\n> \"MI casa\"\n> > ( regexp-replace #rx\"([Mm])i ([a-zA-Z]*)\" \"Mi Casa\" \"\\\\1y \\\\2\" )\n> \"My Casa\"\n> > ( regexp-replace #rx\"([Mm])i ([a-zA-Z]*)\" \"mi cerveza Mi Mi Mi\" \"\\\\1y \\\\2\" )\n> \"my cerveza Mi Mi Mi\"\n> > ( regexp-replace #rx\"x\" \"12x4x6\" \"\\\\\\\\\" )\n> \"12\\\\4x6\"\n> > ( display ( regexp-replace #rx\"x\" \"12x4x6\" \"\\\\\\\\\" ) )\n> 12\\4x6\n> ```\n\n> ```\n(regexp-replace* pattern\n    input        \n    insert        \n   [ start-pos        \n    end-pos        \n    input-prefix)   →   (or/c string? bytes?)\n\n  pattern : (or/c regexp? byte-regexp? string? bytes?)\n  input : (or/c string? bytes?)\n   insert   :   ( or/c string? bytes?\n> ( string? string? ... . → . string? )\n> ( bytes? bytes? ... . → . bytes? ) )\n\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : (or/c exact-nonnegative-integer? #f) = #f\n  input-prefix : bytes? = #\"\"\n```"} {"text": "# 4.6 Characters\nLike regexp-replace, except that every instance of pattern in input is replaced with insert, instead of just the first match. The result is input only if there are no matches, start-pos is 0, and end-pos is #f or the length of input. Only non-overlapping instances of pattern in input are replaced, so instances of pattern within inserted strings are not replaced recursively. Zero-length matches are treated the same as in regexp-match*.\nThe optional start-pos and end-pos arguments select a portion of input for matching; the default is the entire string or the stream up to an end-of-file.\nExamples:\n> ```racket\n> > ( regexp-replace* #rx\"(Mm)i (a-zA-Z*)\" \"mi cerveza Mi Mi Mi\" \"\\\\1y \\\\2\" )\n> \"my cerveza My Mi Mi\"\n> > ( regexp-replace* #rx\"(Mm)i (a-zA-Z*)\" \"mi cerveza Mi Mi Mi\" ( lambda ( all one two ) ( string-append ( string-downcase one ) \"y\" ( string-upcase two ) ) ) )\n> \"myCERVEZA myMI Mi\"\n> > ( regexp-replace* #px\"\\\\w\" \"hello world\" string-upcase 0 5 )\n> \"HELLO world\"\n> > ( display ( regexp-replace* #rx\"x\" \"12x4x6\" \"\\\\\\\\\" ) )\n> 12\\4\\6\n> ```\nChanged in version 8.1.0.7 of package base: Changed to return input when no replacements are performed.\n> ```\n(regexp-replaces input replacements) → (or/c string? bytes?)\n  input : (or/c string? bytes?)\n   replacements   :   ( listof\n> ( list/c ( or/c regexp? byte-regexp? string? bytes? )\n> ( or/c string? bytes?\n> ( string? string? ... . → . string? )\n> ( bytes? bytes? ... . → . bytes? ) ) ) )```"} {"text": "# 4.6 Characters\nPerforms a chain of [regexp-replace*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._regexp-replace%2A%29%29) operations, where each element in replacements specifies a replacement as a ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) pattern insert). The replacements are done in order, so later replacements can apply to previous insertions.\nExamples:\n> ```racket\n> > ( regexp-replaces \"zero-or-more?\" ' ( [ #rx\"-\" \"_\" ] [ #rx\"(.*)\\\\?$\" \"is_\\\\1\" ] ) )\n> \"is_zero_or_more\"\n> > ( regexp-replaces \"zero-or-more?\" ' ( [ #rx\"e\" \"o\" ] [ #rx\"o\" \"oo\" ] ) )\n> \"zooroo-oor-mooroo?\"\n> ```\n> ```\n(regexp-replace-quote str)  →  string?\n  str : string?\n(regexp-replace-quote bstr)  →  bytes?\n  bstr : bytes?\n```\n(parameter)\t→```\n\n\nReturns #t if v is a keyword, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( keyword? ' #:apple )\n> #t\n> > ( keyword? ' define )\n> #f\n> > ( keyword? ' #:define )\n> #t\n> ```\n\n> ```\n(parameter)\t→\n```\n(parameter)\t→\t\n(-> keyword → string ' #:apple)```\nReturns a keyword whose [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29)ed form is the same as that of str, but with a leading #:.\nExample:\n> ```racket\n> > ( string->keyword \"apple\" )\n> '#:apple\n> ```\n>
\n

procedure

"} {"text": "# 4.6 Characters\n

([keyword

  a-keyword : [keyword?](#%28def._%28%28quote._~23~25kernel%29._keyword~3f%29%29)
  b-keyword : [keyword?](#%28def._%28%28quote._~23~25kernel%29._keyword~3f%29%29)
\nReturns #t if the arguments are sorted, where the comparison for each pair of keywords is the same as using [keyword->string](#%28def._%28%28quote._~23~25kernel%29._keyword-~3estring%29%29) with [string->bytes/utf-8](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._string-~3ebytes%2Futf-8%29%29) and [bytes ```racket\n> > ( keyword #t\n> ```\nChanged in version 7.0.0.13 of package base: Allow one argument, in addition to allowing two or more."} {"text": "#### 4.9.1 Additional Keyword Functions\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/keyword](#%28mod-path._racket%2Fkeyword%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/keyword](#%28mod-path._racket%2Fkeyword%29) library, not [racket/base](index.html) or [racket](index.html).\nAdded in version 7.6 of package base.\n> ```\n(parameter)\t→\t\n(-> and/c string? immutable?)"} {"text": "# 4.6 Characters\n```\nLike keyword → string, but the result is an immutable string, not necessarily freshly allocated.\n\nExamples:\n\n> ```racket\n> > ( keyword → immutable-string ' #:apple )\n> \"apple\"\n> > ( immutable? ( keyword → immutable-string ' #:apple ) )\n> #t\n> ```\n\nAdded in version 7.6 of package base.\n\n------------------------------------------------------------------------\n\n# 4.10 Pairs and Lists\n\n### 4.10 Pairs and Lists\n\n> > > \"+\"Pairs and Lists in The Racket Guide introduces pairs and lists.\n\nA pair combines exactly two values. The first value is accessed with the car procedure, and the second value is accessed with the cdr procedure. Pairs are not mutable (but see Mutable Pairs and Lists).\n\nA list is recursively defined: it is either the constant null, or it is a pair whose second value is a list.\n\nA list can be used as a single-valued sequence (see Sequences). The elements of the list serve as elements of the sequence. See also in-list.\n\nCyclic data structures can be created using only immutable pairs via read or make-reader-graph. If starting with a pair and using some number of cdrs returns to the starting pair, then the pair is not a list.\n\nSee Reading Pairs and Lists for information on reading pairs and lists and Printing Pairs and Lists for information on printing pairs and lists.\n\n#### 4.10.1 Pair Constructors and Selectors\n\n> ```\n(pair? v) → boolean?\n  v : any/c```\n\n\nReturns #t if v is a pair, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( pair? 1 )\n> #f\n> > ( pair? ( cons 1 2 ) )\n> #t\n> > ( pair? ( list 1 2 ) )\n> #t\n> > ( pair? ' ( 1 2 ) )\n> #t\n> > ( pair? ' ( ) )\n> #f\n> ```\n\n> ```\n(null? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 4.6 Characters\nReturns #t if v is the empty list, #f otherwise.\nExamples:\n> ```racket\n> > ( null? 1 )\n> #f\n> > ( null? ' ( 1 2 ) )\n> #f\n> > ( null? ' ( ) )\n> #t\n> > ( null? ( cdr ( list 1 ) ) )\n> #t\n> ```\n> ```\n(cons a d)  →  list?\n  a : any/c\n  d : list?\n(cons a d)  →  pair?\n  a : any/c\n  d : any/c\n```\n\n\nReturns a newly allocated pair whose first element is a and second element is d. When d is a list, the allocated pair is also a list.\n\nExamples:\n\n> ```racket\n> > ( cons 1 2 )\n> '(1 . 2)\n> > ( cons 1 ' ( ) )\n> '(1)\n> ```\n\n> ```\n(car p)  →  any/c\n  p : pair?\n```\nReturns the first element of the pair p.\nExamples:\n> ```racket\n> > ( car ' ( 1 2 ) )\n> 1\n> > ( car ' ( 2 . 3 ) )\n> 2\n> ```\n> ```\n(cdr p)  →  any/c\n  p : pair?\n```\n\n\nReturns the second element of the pair p.\n\nExamples:\n\n> ```racket\n> > ( cdr ' ( 1 2 ) )\n> '(2)\n> > ( cdr ' ( 2 . 3 ) )\n> 3\n> ```\n\n>
\n\n

value

\n\n

[null](#%28def._%28%28quote._~23~25kernel%29._null%29%29) : [null?](#%28def._%28%28quote._~23~25kernel%29._null~3f%29%29)

\n\nThe empty list.\n\nExamples:\n\n> ```racket\n> > null\n> '()\n> > ' ( )\n> '()\n> > ( eq? ' ( ) null )\n> #t\n> ```\n\n> ```\n(list? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a list: either the empty list, or a pair whose second element is a list. This procedure effectively takes constant time due to internal caching (so that any necessary traversals of pairs can in principle count as an extra cost of allocating the pairs)."} {"text": "# 4.6 Characters\nExamples:\n> ```racket\n> > ( list? ' ( 1 2 ) )\n> #t\n> > ( list? ( cons 1 ( cons 2 ' ( ) ) ) )\n> #t\n> > ( list? ( cons 1 2 ) )\n> #f\n> ```\n> ```\n(list v ...) → list?\n  v : any/c```\nReturns a newly allocated list containing the vs as its elements.\nExamples:\n> ```racket\n> > ( list 1 2 3 4 )\n> '(1 2 3 4)\n> > ( list ( list 1 2 ) ( list 3 4 ) )\n> '((1 2) (3 4))\n> ```\n> ```\n(list* v ... tail) → list?\n  v : any/c\n  tail : list?\n(list* v ... tail)  →  any/c\n  v : any/c\n  tail : any/c\n```\nLike list, but the last argument is used as the tail of the result, instead of the final element. The result is a list only if the last argument is a list.\n\nExamples:\n\n> ```racket\n> > ( list* 1 2 3 )\n> '(1 2 . 3)\n> > ( list* 1 2 ( list 3 4 ) )\n> '(1 2 3 4)\n> ```\n\n> ```\n(build-list n proc)  →  list?\n  n : exact-nonnegative-integer?\n  proc : (exact-nonnegative-integer? . → . any/c)```\n\n\nCreates a list of n elements by applying proc to the integers from 0 to ([sub1](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._sub1%29%29) n) in order. If lst is the resulting list, then ([list-ref](#%28def._%28%28quote._~23~25kernel%29._list-ref%29%29) lst i) is the value produced by (proc i).\n\nExamples:\n\n> ```racket\n> > ( build-list 10 values )\n> '(0 1 2 3 4 5 6 7 8 9)\n> > ( build-list 5 ( lambda ( x ) ( * x x ) ) )\n> '(0 1 4 9 16)\n> ```\n\n#### 4.10.2 List Operations\n\n> ```\n(length lst)  →  exact-nonnegative-integer?\n  lst : list?\n```\nReturns the number of elements in lst. This function takes time proportional to that length.\nExamples:"} {"text": "# 4.6 Characters\n> ```racket\n> > ( length ( list 1 2 3 4 ) )\n> 4\n> > ( length ' ( ) )\n> 0\n> ```\n> ```\n(list-ref lst pos)  →  any/c\n  lst : list?\n  pos : exact-nonnegative-integer?\n(list-ref lst pos)  →  any/c\n  lst : pair?\n  pos : exact-nonnegative-integer?\n```\n\n\nReturns the element of lst at position pos, where the list’s first element is position 0. If the list has pos or fewer elements, then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nThe lst argument need not actually be a list; lst must merely start with a chain of at least ([add1](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._add1%29%29) pos) pairs.\n\nThis function takes time proportional to pos.\n\nExamples:\n\n> ```racket\n> > ( list-ref ( list ' a ' b ' c ) 0 )\n> 'a\n> > ( list-ref ( list ' a ' b ' c ) 1 )\n> 'b\n> > ( list-ref ( list ' a ' b ' c ) 2 )\n> 'c\n> > ( list-ref ( cons 1 2 ) 0 )\n> 1\n> > ( list-ref ( cons 1 2 ) 1 )\n> list-ref: index reaches a non-pair\n> index: 1\n> in: '(1 . 2)\n> ```\n\n> ```\n(list-tail lst pos)  →  list?\n  lst : list?\n  pos : exact-nonnegative-integer?\n(list-tail lst pos)  →  any/c\n  lst : any/c\n  pos : exact-nonnegative-integer?\n```\nReturns the list after the first pos elements of lst. If the list has fewer than pos elements, then the exn:fail:contract exception is raised.\nThe lst argument need not actually be a list; lst must merely start with a chain of at least pos pairs.\nThis function takes time proportional to pos.\nExamples:"} {"text": "# 4.6 Characters\n> ```racket\n> > ( list-tail ( list 1 2 3 4 5 ) 2 )\n> '(3 4 5)\n> > ( list-tail ( cons 1 2 ) 1 )\n> 2\n> > ( list-tail ( cons 1 2 ) 2 )\n> list-tail: index reaches a non-pair\n> index: 2\n> in: '(1 . 2)\n> > ( list-tail ' not-a-pair 0 )\n> 'not-a-pair\n> ```\n> ```\n(append lst ...) → list?\n  lst : list?\n(append lst ... v)  →  any/c\n  lst : list?\n  v : any/c```\nWhen given all list arguments, the result is a list that contains all of the elements of the given lists in order. The last argument is used directly in the tail of the result.\nThe last argument need not be a list, in which case the result is an “improper list.”\nThis function takes time proportional to the length of all arguments (added together) except the last argument.\nExamples:\n> ```racket\n> > ( append ( list 1 2 ) ( list 3 4 ) )\n> '(1 2 3 4)\n> > ( append ( list 1 2 ) ( list 3 4 ) ( list 5 6 ) ( list 7 8 ) )\n> '(1 2 3 4 5 6 7 8)\n> ```\n> ```\n(reverse lst)  →  list?\n  lst : list?"} {"text": "# 4.6 Characters\n```\nReturns a list that has the same elements as lst, but in reverse order.\n\nThis function takes time proportional to the length of lst.\n\nExample:\n\n> ```racket\n> > ( reverse ( list 1 2 3 4 ) )\n> '(4 3 2 1)\n> ```\n\n#### 4.10.3 List Iteration\n\n> ```\n(map proc lst ...+) → list?\n  proc : procedure?\n  lst : list?```\n\n\nApplies proc to the elements of the lsts from the first elements to the last. The proc argument must accept the same number of arguments as the number of supplied lsts, and all lsts must have the same number of elements. The result is a list containing each result of proc in order.\n\nExamples:\n\n> ```racket\n> > ( map ( lambda ( number ) ( + 1 number ) ) ' ( 1 2 3 4 ) )\n> '(2 3 4 5)\n> > ( map ( lambda ( number1 number2 ) ( + number1 number2 ) ) ' ( 1 2 3 4 ) ' ( 10 100 1000 10000 ) )\n> '(11 102 1003 10004)\n> ```\n\n> ```\n(andmap proc lst ...+) → any\n  proc : procedure?\n  lst : list?\n```\nSimilar to map in the sense that proc is applied to each element of lst, but\n> > > The andmap function is actually closer to foldl than map, since andmap doesn’t produce a list. Still, (andmap f (list x y z)) is equivalent to (and (f x) (f y) (f z)) in the same way that (map f (list x y z)) is equivalent to (list (f x) (f y) (f z)).\n- the result is #f if any application of proc produces #f, in which case proc is not applied to later elements of the lsts; and\n- the result is that of proc applied to the last elements of the lsts; more specifically, the application of proc to the last elements in the lsts is in tail position with respect to the andmap call."} {"text": "# 4.6 Characters\nIf the lsts are empty, then #t is returned.\nExamples:\n> ```racket\n> > ( andmap positive? ' ( 1 2 3 ) )\n> #t\n> > ( andmap positive? ' ( 1 2 a ) )\n> positive?: contract violation\n> expected: real?\n> given: 'a\n> > ( andmap positive? ' ( 1 -2 a ) )\n> #f\n> > ( andmap + ' ( 1 2 3 ) ' ( 4 5 6 ) )\n> 9\n> ```\n> ```\n(ormap proc lst ...+) → any\n  proc : procedure?\n  lst : list?```\nSimilar to [map](#%28def._%28%28lib._racket%2Fprivate%2Fmap..rkt%29._map%29%29) in the sense that proc is applied to each element of lst, but\n> > > To continue the [andmap](#%28def._%28%28lib._racket%2Fprivate%2Fmap..rkt%29._andmap%29%29) note above, ([ormap](#%28def._%28%28lib._racket%2Fprivate%2Fmap..rkt%29._ormap%29%29) f ([list](#%28def._%28%28quote._~23~25kernel%29._list%29%29) x y z)) is equivalent to ([or](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29) (f x) (f y) (f z)).\n- the result is #f if every application of proc produces #f; and\n- the result is that of the first application of proc producing a value other than #f, in which case proc is not applied to later elements of the lsts; the application of proc to the last elements of the lsts is in tail position with respect to the [ormap](#%28def._%28%28lib._racket%2Fprivate%2Fmap..rkt%29._ormap%29%29) call.\nIf the lsts are empty, then #f is returned.\nExamples:\n> ```racket\n> > ( ormap eq? ' ( a b c ) ' ( a b c ) )\n> #t\n> > ( ormap positive? ' ( 1 2 a ) )\n> #t\n> > ( ormap + ' ( 1 2 3 ) ' ( 4 5 6 ) )\n> 5\n> ```\n> ```\n(parameter)\t→"} {"text": "# 4.6 Characters\n```\nSimilar to map, but proc is called only for its effect, and its result (which can be any number of values) is ignored.\n\nExample:\n\n> ```racket\n> > ( for-each ( lambda ( arg ) ( printf \"Got ~a\\n\" arg ) 23 ) ' ( 1 2 3 4 ) )\n> Got 1 Got 2 Got 3 Got 4\n> ```\n\n> ```\n(foldl proc init lst ...+) → any/c\n  proc : procedure?\n  init : any/c\n  lst : list?```\n\n\nLike [map](#%28def._%28%28lib._racket%2Fprivate%2Fmap..rkt%29._map%29%29), [foldl](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._foldl%29%29) applies a procedure to the elements of one or more lists. Whereas [map](#%28def._%28%28lib._racket%2Fprivate%2Fmap..rkt%29._map%29%29) combines the return values into a list, [foldl](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._foldl%29%29) combines the return values in an arbitrary way that is determined by proc.\n\nIf [foldl](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._foldl%29%29) is called with n lists, then proc must take n+1 arguments. The extra argument is the combined return values so far. The proc is initially invoked with the first item of each list, and the final argument is init. In subsequent invocations of proc, the last argument is the return value from the previous invocation of proc. The input lsts are traversed from left to right, and the result of the whole [foldl](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._foldl%29%29) application is the result of the last application of proc. If the lsts are empty, the result is init.\n\nUnlike [foldr](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._foldr%29%29), [foldl](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._foldl%29%29) processes the lsts in constant space (plus the space for each call to proc).\n\nExamples:\n\n> ```racket\n> > ( foldl cons ' ( ) ' ( 1 2 3 4 ) )\n> '(4 3 2 1)\n> > ( foldl + 0 ' ( 1 2 3 4 ) )\n> 10\n> > ( foldl ( lambda ( a b result ) ( * result ( - a b ) ) ) 1 ' ( 1 2 3 ) ' ( 4 5 6 ) )\n> -27\n> ```\n\n> ```\n(foldr proc init lst ...+) → any/c\n  proc : procedure?\n  init : any/c\n  lst : list?\n```"} {"text": "# 4.6 Characters\nLike foldl, but the lists are traversed from right to left. Unlike foldl, foldr processes the lsts in space proportional to the length of lsts (plus the space for each call to proc).\nExamples:\n> ```racket\n> > ( foldr cons ' ( ) ' ( 1 2 3 4 ) )\n> '(1 2 3 4)\n> > ( foldr ( lambda ( v l ) ( cons ( add1 v ) l ) ) ' ( ) ' ( 1 2 3 4 ) )\n> '(2 3 4 5)\n> ```"} {"text": "#### 4.10.4 More List Iteration\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------|\n|  (require racket/list/iteration) | |\n|   |  package: sequence-tools-lib |\nThe bindings documented in this section are provided by the racket/list/iteration library, not racket/base or racket.\nThe bindings in this section are provided by the sequence-tools-lib package, which acts as an extension to the base sequence libraries.\n> ```\n(running-foldl proc init lst ...+) → list?\n  proc : procedure?\n  init : any/c\n  lst : list?```\nLike [foldl](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._foldl%29%29), but produces a list containing all the results of applying proc as well as the initial accumulator.\nExamples:\n> ```racket\n> > ( running-foldl + 0 ' ( 1 2 3 ) )\n> '(0 1 3 6)\n> > ( running-foldl + 0 ' ( ) )\n> '(0)\n> > ( running-foldl ( lambda ( a b acc ) ( * acc ( + a b ) ) ) 1 ' ( 1 2 ) ' ( 3 4 ) )\n> '(1 4 24)\n> ```\n> ```\n(running-foldr proc init lst ...+) → list?\n  proc : procedure?\n  init : any/c\n  lst : list?"} {"text": "# 4.6 Characters\n```\nLike running-foldl, but produces the intermediate results from the right like foldr.\n\nExamples:\n\n> ```racket\n> > ( running-foldr + 0 ' ( 1 2 3 ) )\n> '(6 5 3 0)\n> > ( running-foldr + 0 ' ( ) )\n> '(0)\n> > ( running-foldr ( lambda ( a b acc ) ( * acc ( + a b ) ) ) 1 ' ( 1 2 ) ' ( 3 4 ) )\n> '(24 6 1)\n> ```\n\n#### 4.10.5 List Filtering\n\n> ```\n(filter pred lst)  →  list?\n  pred : procedure?\n  lst : list?```\n\n\nReturns a list with the elements of lst for which pred produces a true value. The pred procedure is applied to each element from first to last.\n\nExample:\n\n> ```racket\n> > ( filter positive? ' ( 1 -2 3 4 -5 ) )\n> '(1 3 4)\n> ```\n\n> ```\n(remove v lst [proc) → list?\n  v : any/c\n  lst : list?\n  proc : procedure? = equal?\n```\nReturns a list that is like lst, omitting the first element of lst that is equal to v using the comparison procedure proc (which must accept two arguments), with v as the first argument and an element in lst as the second argument. If no element in lst is equal to v (according to proc), lst is returned unchanged.\nExamples:\n> ```racket\n> > ( remove 2 ( list 1 2 3 2 4 ) )\n> '(1 3 2 4)\n> > ( remove ' ( 2 ) ( list ' ( 1 ) ' ( 2 ) ' ( 3 ) ) )\n> '((1) (3))\n> > ( remove \"2\" ( list \"1\" \"2\" \"3\" ) )\n> '(\"1\" \"3\")\n> > ( remove #\\c ( list #\\a #\\b #\\c ) )\n> '(#\\a #\\b)\n> > ( remove \"B\" ( list \"a\" \"A\" \"b\" \"B\" ) string-ci=? )\n> '(\"a\" \"A\" \"B\")\n> > ( remove 5 ( list 1 2 3 2 4 ) )\n> '(1 2 3 2 4)\n> ```\nChanged in version 8.2.0.2 of package base: Guaranteed that the output is eq? to lst if no removal occurs.\n> ```"} {"text": "# 4.6 Characters\n(remq v lst) → list?\n  v : any/c\n  lst : list?```\nReturns ([remove](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._remove%29%29) v lst [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)).\nExamples:\n> ```racket\n> > ( remq 2 ( list 1 2 3 4 5 ) )\n> '(1 3 4 5)\n> > ( remq ' ( 2 ) ( list ' ( 1 ) ' ( 2 ) ' ( 3 ) ) )\n> '((1) (2) (3))\n> > ( remq \"2\" ( list \"1\" \"2\" \"3\" ) )\n> '(\"1\" \"3\")\n> > ( remq #\\c ( list #\\a #\\b #\\c ) )\n> '(#\\a #\\b)\n> ```\n> ```\n(remv v lst)  →  list?\n  v : any/c\n  lst : list?\n```\nReturns (remove v lst eqv?).\n\nExamples:\n\n> ```racket\n> > ( remv 2 ( list 1 2 3 4 5 ) )\n> '(1 3 4 5)\n> > ( remv ' ( 2 ) ( list ' ( 1 ) ' ( 2 ) ' ( 3 ) ) )\n> '((1) (2) (3))\n> > ( remv \"2\" ( list \"1\" \"2\" \"3\" ) )\n> '(\"1\" \"3\")\n> > ( remv #\\c ( list #\\a #\\b #\\c ) )\n> '(#\\a #\\b)\n> ```\n\n> ```\n(remw v lst)  →  list?\n  v : any/c\n  lst : list?```\n\n\nReturns ([remove](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._remove%29%29) v lst [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29)).\n\nExamples:\n\n> ```racket\n> > ( remw 2 ( list 1 2 3 4 5 ) )\n> '(1 3 4 5)\n> > ( remw ' ( 2 ) ( list ' ( 1 ) ' ( 2 ) ' ( 3 ) ) )\n> '((1) (3))\n> > ( remw \"2\" ( list \"1\" \"2\" \"3\" ) )\n> '(\"1\" \"3\")\n> > ( remw #\\c ( list #\\a #\\b #\\c ) )\n> '(#\\a #\\b)\n> > ( define b1 ( box 5 ) )\n> > ( define b2 ( box 5 ) )\n> > ( remw b2 ( list 0 b1 1 b2 2 ) )\n> '(0 #&5 1 2)\n> ```\n\nAdded in version 8.5.0.3 of package base.\n\n> ```\n(remove* v-lst lst [proc) → list?\n  v-lst : list?\n  lst : list?\n  proc : procedure? = equal?\n```"} {"text": "# 4.6 Characters\nLike remove, but removes from lst every instance of every element of v-lst.\nExample:\n> ```racket\n> > ( remove* ( list 1 2 ) ( list 1 2 3 2 4 5 2 ) )\n> '(3 4 5)\n> ```\nChanged in version 8.2.0.2 of package base: Guaranteed that the output is eq? to lst if no removal occurs.\n> ```\n(remq* v-lst lst)  →  list?\n  v-lst : list?\n  lst : list?```\nReturns ([remove*](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._remove%2A%29%29) v-lst lst [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)).\nExample:\n> ```racket\n> > ( remq* ( list 1 2 ) ( list 1 2 3 2 4 5 2 ) )\n> '(3 4 5)\n> ```\n> ```\n(remv* v-lst lst)  →  list?\n  v-lst : list?\n  lst : list?\n```\nReturns (remove* v-lst lst eqv?).\n\nExample:\n\n> ```racket\n> > ( remv* ( list 1 2 ) ( list 1 2 3 2 4 5 2 ) )\n> '(3 4 5)\n> ```\n\n> ```\n(remw* v-lst lst)  →  list?\n  v-lst : list?\n  lst : list?```\n\n\nReturns ([remove*](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._remove%2A%29%29) v-lst lst [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29)).\n\nExamples:\n\n> ```racket\n> > ( remw* ( list 1 2 ) ( list 1 2 3 2 4 5 2 ) )\n> '(3 4 5)\n> > ( define b1 ( box 5 ) )\n> > ( define b2 ( box 5 ) )\n> > ( remw* ( list b2 ) ( list 0 b1 1 b2 2 b2 3 ) )\n> '(0 #&5 1 2 3)\n> ```\n\nAdded in version 8.5.0.3 of package base.\n\n> ```\n(sort lst\n    less-than?        \n   [ #:key extract-key        \n    #:cache-keys? cache-keys?)   →   list?\n\n  lst : list?\n  less-than? : (any/c any/c . → . any/c)\n  extract-key : (or/c #f (any/c . → . any/c)) = #f\n  cache-keys? : boolean? = #f\n```"} {"text": "# 4.6 Characters\nReturns a list sorted according to the less-than? procedure, which takes two elements of lst and returns a true value if the first is less (i.e., should be sorted earlier) than the second.\nThe sort is stable; if two elements of lst are “equal” (i.e., less-than? does not return a true value when given the pair in either order), then the elements preserve their relative order from lst in the output list. To preserve this guarantee, use sort with a strict comparison functions (e.g., < or string > > Because of the peculiar fact that the IEEE-754 number system specifies that +nan.0 is neither greater nor less than nor equal to any other number, sorting lists containing this value may produce a surprising result.\nThe #:key argument extract-key is used to extract a key value for comparison from each list element, where #f is replaced by (lambda (x) x) That is, the full comparison procedure is essentially\n> ```racket\n> ( lambda ( x y )\n> ( less-than? ( extract-key x ) ( extract-key y ) ) )\n> ```"} {"text": "# 4.6 Characters\nBy default, extract-key is applied to two list elements for every comparison, but if cache-keys? is true, then the extract-key function is used exactly once for each list item. Supply a true value for cache-keys? when extract-key is an expensive operation; for example, if file-or-directory-modify-seconds is used to extract a timestamp for every file in a list, then cache-keys? should be #t to minimize file-system calls, but if extract-key is car, then cache-keys? should be #f. As another example, providing extract-key as (lambda (x) (random)) and #t for cache-keys? effectively shuffles the list.\nExamples:\n> ```racket\n> > ( sort ' ( 1 3 4 2 ) < )> '(1 2 3 4)\n> > ( sort ' ( \"aardvark\" \"dingo\" \"cow\" \"bear\" ) string '(\"aardvark\" \"bear\" \"cow\" \"dingo\")\n> > ( sort ' ( ( \"aardvark\" ) ( \"dingo\" ) ( \"cow\" ) ( \"bear\" ) ) #:key car string '((\"aardvark\") (\"bear\") (\"cow\") (\"dingo\"))\n> ```"} {"text": "#### 4.10.6 List Searching\n> ```\n(member v lst [is-equal?) → (or/c #f list?)\n  v : any/c\n  lst : list?\n  is-equal? : (any/c any/c . → . any/c) = equal?\n(member v lst [is-equal?)  →  any/c\n  v : any/c\n  lst : any/c\n  is-equal? : (any/c any/c . → . any/c) = equal?```\nLocates the first element of lst that is equal to v according to is-equal?. If such an element exists, the tail of lst starting with that element is returned. Otherwise, the result is #f.\nThe lst argument need not actually be a list; lst must merely start with a chain of pairs until a matching element is found. If no matching element is found, then lst must be a list (and not a cyclic list). The result can be a non-list in the case that an element is found and the returned tail of lst is a non-list.\nExamples:\n> ```racket\n> > ( member 2 ( list 1 2 3 4 ) )\n> '(2 3 4)\n> > ( member 9 ( list 1 2 3 4 ) )\n> #f\n> > ( member #' x ( list #' x #' y ) free-identifier=? )\n> '(# #)\n> > ( member #' a ( list #' x #' y ) free-identifier=? )\n> #f\n> > ( member ' b ' ( a b . etc ) )\n> '(b . etc)\n> > ( member ' c ' ( a b . etc ) )\n> member: not a proper list\n> in: '(a b . etc)\n> ```\n> ```\n(memw v lst)  →  (or/c #f list?)\n  v : any/c\n  lst : list?\n(memw v lst)  →  any/c\n  v : any/c\n  lst : any/c"} {"text": "# 4.6 Characters\n```\nLike member, but finds an element using equal-always?.\n\nExamples:\n\n> ```racket\n> > ( memw 2 ( list 1 2 3 4 ) )\n> '(2 3 4)\n> > ( memw 9 ( list 1 2 3 4 ) )\n> #f\n> > ( define b1 ( box 5 ) )\n> > ( define b2 ( box 5 ) )\n> > ( memw b2 ( list 0 b1 1 b2 2 ) )\n> '(#&5 2)\n> ```\n\nAdded in version 8.5.0.3 of package base.\n\n> ```\n(memv v lst)  →  (or/c #f list?)\n  v : any/c\n  lst : list?\n(memv v lst)  →  any/c\n  v : any/c\n  lst : any/c```\n\n\nLike [member](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._member%29%29), but finds an element using [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29).\n\nExamples:\n\n> ```racket\n> > ( memv 2 ( list 1 2 3 4 ) )\n> '(2 3 4)\n> > ( memv 9 ( list 1 2 3 4 ) )\n> #f\n> ```\n\n> ```\n(memq v lst)  →  (or/c #f list?)\n  v : any/c\n  lst : list?\n(memq v lst)  →  any/c\n  v : any/c\n  lst : any/c\n```\nLike member, but finds an element using eq?.\nExamples:\n> ```racket\n> > ( memq 2 ( list 1 2 3 4 ) )\n> '(2 3 4)\n> > ( memq 9 ( list 1 2 3 4 ) )\n> #f\n> ```\n> ```\n(memf proc lst)  →  (or/c #f list?)\n  proc : procedure?\n  lst : list?\n(memf proc lst)  →  any/c\n  proc : procedure?\n  lst : any/c```\nLike [member](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._member%29%29), but finds an element using the predicate proc; an element is found when proc applied to the element returns a true value.\nExample:\n> ```racket\n> > ( memf ( lambda ( arg ) ( > arg 9 ) ) ' ( 7 8 9 10 11 ) )\n> '(10 11)\n> ```\n> ```"} {"text": "# 4.6 Characters\n(findf proc lst)  →  (or/c #f any/c)\n  proc : procedure?\n  lst : list?\n(findf proc lst)  →  any/c\n  proc : procedure?\n  lst : any/c\n```\nLike memf, but returns the element or #f instead of a tail of lst or #f.\n\nNotably, if #f is an element of lst, then the result of #f is ambiguous: it may indicate that no element satisfies proc, or may indicate that the element #f satisfies proc.\n\nExample:\n\n> ```racket\n> > ( findf ( lambda ( arg ) ( > arg 9 ) ) ' ( 7 8 9 10 11 ) )\n> 10\n> ```\n\n> ```\n(assoc v lst [is-equal?) → (or/c pair? #f)\n  v : any/c\n  lst : (listof pair?)\n  is-equal? : (any/c any/c . → . any/c) = equal?\n(assoc v lst [is-equal?)  →  pair?\n  v : any/c\n  lst : (list*of pair? (not/c '()))\n  is-equal? : (any/c any/c . → . any/c) = equal?```\n\n\nLocates the first element of lst whose [car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) is equal to v according to is-equal?. If such an element exists, the pair (i.e., an element of lst) is returned. Otherwise, the result is #f.\n\nThe lst argument need not actually be a list of pairs; lst must merely start with a chain of pairs contains pairs until a matching element is found. If no matching element is found, then lst must be a list of pairs (and not a cyclic list).\n\nExamples:\n\n> ```racket\n> > ( assoc 3 ( list ( list 1 2 ) ( list 3 4 ) ( list 5 6 ) ) )\n> '(3 4)\n> > ( assoc 9 ( list ( list 1 2 ) ( list 3 4 ) ( list 5 6 ) ) )\n> #f\n> > ( assoc 3.5 ( list ( list 1 2 ) ( list 3 4 ) ( list 5 6 ) ) ( lambda ( a b ) ( < ( abs ( - a b ) ) 1 ) ) )> '(3 4)\n> ```\n\n> ```\n(assw v lst)  →  (or/c pair? #f)\n  v : any/c\n  lst : (listof pair?)\n(assw v lst)  →  pair?\n  v : any/c\n  lst : (list*of pair? (not/c '()))\n```"} {"text": "# 4.6 Characters\nLike assoc, but finds an element using equal-always?.\nExamples:\n> ```racket\n> > ( assw 3 ( list ( list 1 2 ) ( list 3 4 ) ( list 5 6 ) ) )\n> '(3 4)\n> > ( define b1 ( box 0 ) )\n> > ( define b2 ( box 0 ) )\n> > ( assw b2 ( list ( cons b1 1 ) ( cons b2 2 ) ) )\n> '(#&0 . 2)\n> ```\nAdded in version 8.5.0.3 of package base.\n> ```\n(assv v lst)  →  (or/c pair? #f)\n  v : any/c\n  lst : (listof pair?)\n(assv v lst)  →  pair?\n  v : any/c\n  lst : (list*of pair? (not/c '()))```\nLike [assoc](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._assoc%29%29), but finds an element using [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29).\nExample:\n> ```racket\n> > ( assv 3 ( list ( list 1 2 ) ( list 3 4 ) ( list 5 6 ) ) )\n> '(3 4)\n> ```\n> ```\n(assq v lst)  →  (or/c pair? #f)\n  v : any/c\n  lst : (listof pair?)\n(assq v lst)  →  pair?\n  v : any/c\n  lst : (list*of pair? (not/c '()))"} {"text": "# 4.6 Characters\n```\nLike assoc, but finds an element using eq?.\n\nExample:\n\n> ```racket\n> > ( assq ' c ( list ( list ' a ' b ) ( list ' c ' d ) ( list ' e ' f ) ) )\n> '(c d)\n> ```\n\n> ```\n(assf proc lst)  →  (or/c pair? #f)\n  proc : procedure?\n  lst : (listof pair?)\n(assf proc lst)  →  pair?\n  proc : procedure?\n  lst : (list*of pair? (not/c '()))```\n\n\nLike [assoc](#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._assoc%29%29), but finds an element using the predicate proc; an element is found when proc applied to the [car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) of an lst element returns a true value.\n\nExample:\n\n> ```racket\n> > ( assf ( lambda ( arg ) ( > arg 2 ) ) ( list ( list 1 2 ) ( list 3 4 ) ( list 5 6 ) ) )\n> '(3 4)\n> ```\n\n#### 4.10.7 Pair Accessor Shorthands\n\n> ```\n(caar v)  →  any/c\n  v : (cons/c pair? any/c)\n```\nReturns (car (car v)).\nExample:\n> ```racket\n> > ( caar ' ( ( 1 2 ) 3 4 ) )\n> 1\n> ```\n> ```\n(cadr v)  →  any/c\n  v : (cons/c any/c pair?)```\nReturns ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v)).\nExample:\n> ```racket\n> > ( cadr ' ( ( 1 2 ) 3 4 ) )\n> 3\n> ```\n> ```\n(cdar v)  →  any/c\n  v : (cons/c pair? any/c)"} {"text": "# 4.6 Characters\n```\nReturns (cdr (car v)).\n\nExample:\n\n> ```racket\n> > ( cdar ' ( ( 7 6 5 4 3 2 1 ) 8 9 ) )\n> '(6 5 4 3 2 1)\n> ```\n\n> ```\n(cddr v)  →  any/c\n  v : (cons/c any/c pair?)```\n\n\nReturns ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v)).\n\nExample:\n\n> ```racket\n> > ( cddr ' ( 2 1 ) )\n> '()\n> ```\n\n> ```\n(caaar v)  →  any/c\n  v : (cons/c (cons/c pair? any/c) any/c)\n```\nReturns (car (car (car v))).\nExample:\n> ```racket\n> > ( caaar ' ( ( ( 6 5 4 3 2 1 ) 7 ) 8 9 ) )\n> 6\n> ```\n> ```\n(caadr v)  →  any/c\n  v : (cons/c any/c (cons/c pair? any/c))```\nReturns ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v))).\nExample:\n> ```racket\n> > ( caadr ' ( 9 ( 7 6 5 4 3 2 1 ) 8 ) )\n> 7\n> ```\n> ```\n(cadar v)  →  any/c\n  v : (cons/c (cons/c any/c pair?) any/c)\n```\nReturns (car (cdr (car v))).\n\nExample:\n\n> ```racket\n> > ( cadar ' ( ( 7 6 5 4 3 2 1 ) 8 9 ) )\n> 6\n> ```\n\n> ```\n(caddr v)  →  any/c\n  v : (cons/c any/c (cons/c any/c pair?))```\n\n\nReturns ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v))).\n\nExample:\n\n> ```racket\n> > ( caddr ' ( 3 2 1 ) )\n> 1\n> ```\n\n> ```\n(cdaar v)  →  any/c\n  v : (cons/c (cons/c pair? any/c) any/c)\n```\nReturns (cdr (car (car v))).\nExample:\n> ```racket\n> > ( cdaar ' ( ( ( 6 5 4 3 2 1 ) 7 ) 8 9 ) )\n> '(5 4 3 2 1)\n> ```\n> ```"} {"text": "# 4.6 Characters\n(cdadr v)  →  any/c\n  v : (cons/c any/c (cons/c pair? any/c))```\nReturns ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v))).\nExample:\n> ```racket\n> > ( cdadr ' ( 9 ( 7 6 5 4 3 2 1 ) 8 ) )\n> '(6 5 4 3 2 1)\n> ```\n> ```\n(cddar v)  →  any/c\n  v : (cons/c (cons/c any/c pair?) any/c)\n```\nReturns (cdr (cdr (car v))).\n\nExample:\n\n> ```racket\n> > ( cddar ' ( ( 7 6 5 4 3 2 1 ) 8 9 ) )\n> '(5 4 3 2 1)\n> ```\n\n> ```\n(cdddr v)  →  any/c\n  v : (cons/c any/c (cons/c any/c pair?))```\n\n\nReturns ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v))).\n\nExample:\n\n> ```racket\n> > ( cdddr ' ( 3 2 1 ) )\n> '()\n> ```\n\n> ```\n(caaaar v)  →  any/c\n  v : (cons/c (cons/c (cons/c pair? any/c) any/c) any/c)\n```\nReturns (car (car (car (car v)))).\nExample:\n> ```racket\n> > ( caaaar ' ( ( ( ( 5 4 3 2 1 ) 6 ) 7 ) 8 9 ) )\n> 5\n> ```\n> ```\n(caaadr v)  →  any/c\n  v : (cons/c any/c (cons/c (cons/c pair? any/c) any/c))```\nReturns ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v)))).\nExample:\n> ```racket\n> > ( caaadr ' ( 9 ( ( 6 5 4 3 2 1 ) 7 ) 8 ) )\n> 6\n> ```\n> ```\n(caadar v)  →  any/c\n  v : (cons/c (cons/c any/c (cons/c pair? any/c)) any/c)"} {"text": "# 4.6 Characters\n```\nReturns (car (car (cdr (car v)))).\n\nExample:\n\n> ```racket\n> > ( caadar ' ( ( 7 ( 5 4 3 2 1 ) 6 ) 8 9 ) )\n> 5\n> ```\n\n> ```\n(caaddr v)  →  any/c\n  v : (cons/c any/c (cons/c any/c (cons/c pair? any/c)))```\n\n\nReturns ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v)))).\n\nExample:\n\n> ```racket\n> > ( caaddr ' ( 9 8 ( 6 5 4 3 2 1 ) 7 ) )\n> 6\n> ```\n\n> ```\n(cadaar v)  →  any/c\n  v : (cons/c (cons/c (cons/c any/c pair?) any/c) any/c)\n```\nReturns (car (cdr (car (car v)))).\nExample:\n> ```racket\n> > ( cadaar ' ( ( ( 6 5 4 3 2 1 ) 7 ) 8 9 ) )\n> 5\n> ```\n> ```\n(cadadr v)  →  any/c\n  v : (cons/c any/c (cons/c (cons/c any/c pair?) any/c))```\nReturns ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v)))).\nExample:\n> ```racket\n> > ( cadadr ' ( 9 ( 7 6 5 4 3 2 1 ) 8 ) )\n> 6\n> ```\n> ```\n(caddar v)  →  any/c\n  v : (cons/c (cons/c any/c (cons/c any/c pair?)) any/c)"} {"text": "# 4.6 Characters\n```\nReturns (car (cdr (cdr (car v)))).\n\nExample:\n\n> ```racket\n> > ( caddar ' ( ( 7 6 5 4 3 2 1 ) 8 9 ) )\n> 5\n> ```\n\n> ```\n(cadddr v)  →  any/c\n  v : (cons/c any/c (cons/c any/c (cons/c any/c pair?)))```\n\n\nReturns ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v)))).\n\nExample:\n\n> ```racket\n> > ( cadddr ' ( 4 3 2 1 ) )\n> 1\n> ```\n\n> ```\n(cdaaar v)  →  any/c\n  v : (cons/c (cons/c (cons/c pair? any/c) any/c) any/c)\n```\nReturns (cdr (car (car (car v)))).\nExample:\n> ```racket\n> > ( cdaaar ' ( ( ( ( 5 4 3 2 1 ) 6 ) 7 ) 8 9 ) )\n> '(4 3 2 1)\n> ```\n> ```\n(cdaadr v)  →  any/c\n  v : (cons/c any/c (cons/c (cons/c pair? any/c) any/c))```\nReturns ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v)))).\nExample:\n> ```racket\n> > ( cdaadr ' ( 9 ( ( 6 5 4 3 2 1 ) 7 ) 8 ) )\n> '(5 4 3 2 1)\n> ```\n> ```\n(cdadar v)  →  any/c\n  v : (cons/c (cons/c any/c (cons/c pair? any/c)) any/c)"} {"text": "# 4.6 Characters\n```\nReturns (cdr (car (cdr (car v)))).\n\nExample:\n\n> ```racket\n> > ( cdadar ' ( ( 7 ( 5 4 3 2 1 ) 6 ) 8 9 ) )\n> '(4 3 2 1)\n> ```\n\n> ```\n(cdaddr v)  →  any/c\n  v : (cons/c any/c (cons/c any/c (cons/c pair? any/c)))```\n\n\nReturns ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v)))).\n\nExample:\n\n> ```racket\n> > ( cdaddr ' ( 9 8 ( 6 5 4 3 2 1 ) 7 ) )\n> '(5 4 3 2 1)\n> ```\n\n> ```\n(cddaar v)  →  any/c\n  v : (cons/c (cons/c (cons/c any/c pair?) any/c) any/c)\n```\nReturns (cdr (cdr (car (car v)))).\nExample:\n> ```racket\n> > ( cddaar ' ( ( ( 6 5 4 3 2 1 ) 7 ) 8 9 ) )\n> '(4 3 2 1)\n> ```\n> ```\n(cddadr v)  →  any/c\n  v : (cons/c any/c (cons/c (cons/c any/c pair?) any/c))```\nReturns ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([car](#%28def._%28%28quote._~23~25kernel%29._car%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v)))).\nExample:\n> ```racket\n> > ( cddadr ' ( 9 ( 7 6 5 4 3 2 1 ) 8 ) )\n> '(5 4 3 2 1)\n> ```\n> ```\n(cdddar v)  →  any/c\n  v : (cons/c (cons/c any/c (cons/c any/c pair?)) any/c)"} {"text": "# 4.6 Characters\n```\nReturns (cdr (cdr (cdr (car v)))).\n\nExample:\n\n> ```racket\n> > ( cdddar ' ( ( 7 6 5 4 3 2 1 ) 8 9 ) )\n> '(4 3 2 1)\n> ```\n\n> ```\n(cddddr v)  →  any/c\n  v : (cons/c any/c (cons/c any/c (cons/c any/c pair?)))```\n\n\nReturns ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) v)))).\n\nExample:\n\n> ```racket\n> > ( cddddr ' ( 4 3 2 1 ) )\n> '()\n> ```\n\n#### 4.10.8 Additional List Functions and Synonyms\n\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/list](#%28mod-path._racket%2Flist%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/list](#%28mod-path._racket%2Flist%29) and [racket](index.html) libraries, but not [racket/base](index.html).\n\n>
\n\n

value

\n\n

[empty](#%28def._%28%28lib._racket%2Flist..rkt%29._empty%29%29) : [null?](#%28def._%28%28quote._~23~25kernel%29._null~3f%29%29)

\n\nThe empty list.\n\nExamples:\n\n> ```racket\n> > empty\n> '()\n> > ( eq? empty null )\n> #t\n> ```\n\n> ```\n(cons? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 4.6 Characters\nThe same as (pair? v).\nExample:\n> ```racket\n> > ( cons? ' ( 1 2 ) )\n> #t\n> ```\n> ```\n(empty? v)  →  boolean?\n  v : any/c```\nThe same as ([null?](#%28def._%28%28quote._~23~25kernel%29._null~3f%29%29) v).\nExamples:\n> ```racket\n> > ( empty? ' ( 1 2 ) )\n> #f\n> > ( empty? ' ( ) )\n> #t\n> ```\n> ```\n(first lst)  →  any/c\n  lst : list?\n```\nThe same as (car lst), but only for lists (that are not empty).\n\nExample:\n\n> ```racket\n> > ( first ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 1\n> ```\n\n> ```\n(rest lst)  →  list?\n  lst : list?```\n\n\nThe same as ([cdr](#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) lst), but only for lists (that are not empty).\n\nExample:\n\n> ```racket\n> > ( rest ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> '(2 3 4 5 6 7 8 9 10 11 12 13 14 15)\n> ```\n\n> ```\n(second lst)  →  any/c\n  lst : list?\n```\nReturns the second element of the list.\nExample:\n> ```racket\n> > ( second ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 2\n> ```\n> ```\n(third lst)  →  any/c\n  lst : list?\n```\n\n\nReturns the third element of the list.\n\nExample:\n\n> ```racket\n> > ( third ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 3\n> ```\n\n> ```\n(fourth lst)  →  any/c\n  lst : list?\n```\nReturns the fourth element of the list.\nExample:\n> ```racket\n> > ( fourth ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 4\n> ```\n> ```\n(fifth lst)  →  any/c\n  lst : list?\n```\n\n\nReturns the fifth element of the list.\n\nExample:\n\n> ```racket\n> > ( fifth ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 5\n> ```\n\n> ```\n(sixth lst)  →  any/c\n  lst : list?\n```\nReturns the sixth element of the list.\nExample:"} {"text": "# 4.6 Characters\n> ```racket\n> > ( sixth ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 6\n> ```\n> ```\n(seventh lst)  →  any/c\n  lst : list?\n```\n\n\nReturns the seventh element of the list.\n\nExample:\n\n> ```racket\n> > ( seventh ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 7\n> ```\n\n> ```\n(eighth lst)  →  any/c\n  lst : list?\n```\nReturns the eighth element of the list.\nExample:\n> ```racket\n> > ( eighth ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 8\n> ```\n> ```\n(ninth lst)  →  any/c\n  lst : list?\n```\n\n\nReturns the ninth element of the list.\n\nExample:\n\n> ```racket\n> > ( ninth ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 9\n> ```\n\n> ```\n(tenth lst)  →  any/c\n  lst : list?\n```\nReturns the tenth element of the list.\nExample:\n> ```racket\n> > ( tenth ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 10\n> ```\n> ```\n(eleventh lst)  →  any/c\n  lst : list?\n```\n\n\nReturns the eleventh element of the list.\n\nExample:\n\n> ```racket\n> > ( eleventh ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 11\n> ```\n\nAdded in version 8.15.0.3 of package base.\n\n> ```\n(twelfth lst)  →  any/c\n  lst : list?\n```\nReturns the twelfth element of the list.\nExample:\n> ```racket\n> > ( twelfth ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 12\n> ```\nAdded in version 8.15.0.3 of package base.\n> ```\n(thirteenth lst)  →  any/c\n  lst : list?\n```\n\n\nReturns the thirteenth element of the list.\n\nExample:\n\n> ```racket\n> > ( thirteenth ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 13\n> ```\n\nAdded in version 8.15.0.3 of package base.\n\n> ```\n(fourteenth lst)  →  any/c\n  lst : list?\n```\nReturns the fourteenth element of the list.\nExample:"} {"text": "# 4.6 Characters\n> ```racket\n> > ( fourteenth ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 14\n> ```\nAdded in version 8.15.0.3 of package base.\n> ```\n(fifteenth lst)  →  any/c\n  lst : list?\n```\n\n\nReturns the fifteenth element of the list.\n\nExample:\n\n> ```racket\n> > ( fifteenth ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 15\n> ```\n\nAdded in version 8.15.0.3 of package base.\n\n> ```\n(last lst)  →  any/c\n  lst : list?\n```\nReturns the last element of the list.\nThis function takes time proportional to the length of lst.\nExample:\n> ```racket\n> > ( last ' ( 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ) )\n> 15\n> ```\n> ```\n(last-pair p)  →  pair?\n  p : pair?\n```\n\n\nReturns the last pair of a (possibly improper) list.\n\nThis function takes time proportional to the “length” of p.\n\nExample:\n\n> ```racket\n> > ( last-pair ' ( 1 2 3 4 ) )\n> '(4)\n> ```\n\n> ```\n(make-list k v)  →  list?\n  k : exact-nonnegative-integer?\n  v : any/c\n```\nReturns a newly constructed list of length k, holding v in all positions.\nExample:\n> ```racket\n> > ( make-list 7 ' foo )\n> '(foo foo foo foo foo foo foo)\n> ```\n> ```\n(list-update lst pos updater) → list?\n  lst : list?\n  pos : (and/c (>=/c 0) ([](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) any/c any/c)```\nReturns a list that is the same as lst except at the specified index. The element at the specified index is (updater ([list-ref](#%28def._%28%28quote._~23~25kernel%29._list-ref%29%29) lst pos)).\nThis function takes time proportional to pos.\nExample:"} {"text": "# 4.6 Characters\n> ```racket\n> > ( list-update ' ( zero one two ) 1 symbol->string )\n> '(zero \"one\" two)\n> ```\nAdded in version 6.3 of package base.\n> ```\n(list-set lst pos value) → list?\n  lst : list?\n  pos : (and/c (>=/c 0) ([\n```\nReturns a list that is the same as lst except at the specified index. The element at the specified index is value.\n\nThis function takes time proportional to pos.\n\nExample:\n\n> ```racket\n> > ( list-set ' ( zero one two ) 2 \"two\" )\n> '(zero one \"two\")\n> ```\n\nAdded in version 6.3 of package base.\n\n> ```\n(index-of lst v [is-equal?) → (or/c exact-nonnegative-integer? #f)\n  lst : list?\n  v : any/c\n  is-equal? : (any/c any/c . → . any/c) = equal?```\n\n\nLike [member](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._member%29%29), but returns the index of the first element found instead of the tail of the list.\n\nExample:\n\n> ```racket\n> > ( index-of ' ( 1 2 3 4 ) 3 )\n> 2\n> ```\n\nAdded in version 6.7.0.3 of package base.\n\n> ```\n(index-where lst proc)  →  (or/c exact-nonnegative-integer? #f)\n  lst : list?\n  proc : (any/c . → . any/c)\n```\nLike index-of but with the predicate-searching behavior of memf.\nExample:\n> ```racket\n> > ( index-where ' ( 1 2 3 4 ) even? )\n> 1\n> ```\nAdded in version 6.7.0.3 of package base.\n> ```\n(indexes-of lst v [is-equal?)\n  →  (listof exact-nonnegative-integer?)\n  lst : list?\n  v : any/c\n  is-equal? : (any/c any/c . → . any/c) = equal?```\nLike [index-of](#%28def._%28%28lib._racket%2Flist..rkt%29._index-of%29%29), but returns the a list of all the indexes where the element occurs in the list instead of just the first one."} {"text": "# 4.6 Characters\nExample:\n> ```racket\n> > ( indexes-of ' ( 1 2 1 2 1 ) 2 )\n> '(1 3)\n> ```\nAdded in version 6.7.0.3 of package base.\n> ```\n(indexes-where lst proc)  →  (listof exact-nonnegative-integer?)\n  lst : list?\n  proc : (any/c . → . any/c)\n```\nLike indexes-of but with the predicate-searching behavior of index-where.\n\nExample:\n\n> ```racket\n> > ( indexes-where ' ( 1 2 3 4 ) even? )\n> '(1 3)\n> ```\n\nAdded in version 6.7.0.3 of package base.\n\n> ```\n(take lst pos)  →  list?\n  lst : list?\n  pos : exact-nonnegative-integer?\n(take lst pos)  →  list?\n  lst : any/c\n  pos : exact-nonnegative-integer?```\n\n\nReturns a fresh list whose elements are the first pos elements of lst. If lst has fewer than pos elements, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nThe lst argument need not actually be a list; lst must merely start with a chain of at least pos pairs.\n\nThis function takes time proportional to pos.\n\nExamples:\n\n> ```racket\n> > ( take ' ( 1 2 3 4 5 ) 2 )\n> '(1 2)\n> > ( take ' non-list 0 )\n> '()\n> ```\n\n> ```\n(drop lst pos)  →  list?\n  lst : list?\n  pos : exact-nonnegative-integer?\n(drop lst pos)  →  any/c\n  lst : any/c\n  pos : exact-nonnegative-integer?\n```\nJust like list-tail.\n> ```\n(split-at lst pos)   →   list?   list?\n  lst : list?\n  pos : exact-nonnegative-integer?\n(split-at lst pos)   →   list?   any/c\n  lst : any/c\n  pos : exact-nonnegative-integer?```\nReturns the same result as"} {"text": "# 4.6 Characters\n> ([values](values.html#%28def._%28%28quote._~23~25kernel%29._values%29%29) ([take](#%28def._%28%28lib._racket%2Flist..rkt%29._take%29%29) lst pos) ([drop](#%28def._%28%28lib._racket%2Flist..rkt%29._drop%29%29) lst pos))\nexcept that it can be faster, but it will still take time proportional to pos.\n> ```\n(takef lst pred)  →  list?\n  lst : list?\n  pred : procedure?\n(takef lst pred)  →  list?\n  lst : any/c\n  pred : procedure?\n```\nReturns a fresh list whose elements are taken successively from lst as long as they satisfy pred. The returned list includes up to, but not including, the first element in lst for which pred returns #f.\n\nThe lst argument need not actually be a list; the chain of pairs in lst will be traversed until a non-pair is encountered.\n\nExamples:\n\n> ```racket\n> > ( takef ' ( 2 4 5 8 ) even? )\n> '(2 4)\n> > ( takef ' ( 2 4 6 8 ) odd? )\n> '()\n> > ( takef ' ( 2 4 . 6 ) even? )\n> '(2 4)\n> ```\n\n> ```\n(dropf lst pred)  →  list?\n  lst : list?\n  pred : procedure?\n(dropf lst pred)  →  any/c\n  lst : any/c\n  pred : procedure?```\n\n\nDrops elements from the front of lst as long as they satisfy pred.\n\nExamples:\n\n> ```racket\n> > ( dropf ' ( 2 4 5 8 ) even? )\n> '(5 8)\n> > ( dropf ' ( 2 4 6 8 ) odd? )\n> '(2 4 6 8)\n> ```\n\n> ```\n(splitf-at lst pred)   →   list?   list?\n\n  lst : list?\n  pred : procedure?\n(splitf-at lst pred)   →   list?   any/c\n\n  lst : any/c\n  pred : procedure?\n```\nReturns the same result as\n> (values (takef lst pred) (dropf lst pred))\nexcept that it can be faster.\n> ```"} {"text": "# 4.6 Characters\n(take-right lst pos)  →  list?\n  lst : list?\n  pos : exact-nonnegative-integer?\n(take-right lst pos)  →  any/c\n  lst : any/c\n  pos : exact-nonnegative-integer?```\nReturns the [list](#%28def._%28%28quote._~23~25kernel%29._list%29%29)’s pos-length tail. If lst has fewer than pos elements, then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nThe lst argument need not actually be a list; lst must merely end with a chain of at least pos pairs.\nThis function takes time proportional to the length of lst.\nExamples:\n> ```racket\n> > ( take-right ' ( 1 2 3 4 5 ) 2 )\n> '(4 5)\n> > ( take-right ' non-list 0 )\n> 'non-list\n> ```\n> ```\n(drop-right lst pos)  →  list?\n  lst : list?\n  pos : exact-nonnegative-integer?\n(drop-right lst pos)  →  list?\n  lst : any/c\n  pos : exact-nonnegative-integer?"} {"text": "# 4.6 Characters\n```\nReturns a fresh list whose elements are the prefix of lst, dropping its pos-length tail. If lst has fewer than pos elements, then the exn:fail:contract exception is raised.\n\nThe lst argument need not actually be a list; lst must merely end with a chain of at least pos pairs.\n\nThis function takes time proportional to the length of lst.\n\nExamples:\n\n> ```racket\n> > ( drop-right ' ( 1 2 3 4 5 ) 2 )\n> '(1 2 3)\n> > ( drop-right ' non-list 0 )\n> '()\n> ```\n\n> ```\n(split-at-right lst pos)   →   list?   list?\n\n  lst : list?\n  pos : exact-nonnegative-integer?\n(split-at-right lst pos)   →   list?   any/c\n\n  lst : any/c\n  pos : exact-nonnegative-integer?```\n\n\nReturns the same result as\n\n> ([values](values.html#%28def._%28%28quote._~23~25kernel%29._values%29%29) ([drop-right](#%28def._%28%28lib._racket%2Flist..rkt%29._drop-right%29%29) lst pos) ([take-right](#%28def._%28%28lib._racket%2Flist..rkt%29._take-right%29%29) lst pos))\n\nexcept that it can be faster, but it will still take time proportional to the length of lst.\n\nExamples:\n\n> ```racket\n> > ( split-at-right ' ( 1 2 3 4 5 . 6 ) 4 )\n> '(1) '(2 3 4 5 . 6)\n> > ( split-at-right ' ( 1 2 3 4 5 6 ) 4 )\n> '(1 2) '(3 4 5 6)\n> ```\n\n> ```\n(takef-right lst pred)  →  list?\n  lst : list?\n  pred : procedure?\n(takef-right lst pred)  →  any/c\n  lst : any/c\n  pred : procedure?\n\n(dropf-right lst pred)  →  list?\n  lst : list?\n  pred : procedure?\n(dropf-right lst pred)  →  list?\n  lst : any/c\n  pred : procedure?\n\n(splitf-at-right lst pred)   →   list?   list?\n\n  lst : list?\n  pred : procedure?\n(splitf-at-right lst pred)   →   list?   any/c\n\n  lst : any/c\n  pred : procedure?\n```"} {"text": "# 4.6 Characters\nLike takef, dropf, and splitf-at, but combined with the from-right functionality of take-right, drop-right, and split-at-right.\n> ```\n(list-prefix? l r [same?) → boolean?\n  l : list?\n  r : list?\n  same? : (any/c any/c . → . any/c) = equal?```\nTrue if l is a prefix of r.\nExample:\n> ```racket\n> > ( list-prefix? ' ( 1 2 ) ' ( 1 2 3 4 5 ) )\n> #t\n> ```\nAdded in version 6.3 of package base.\n> ```\n(take-common-prefix l r [same?) → list?\n  l : list?\n  r : list?\n  same? : (any/c any/c . → . any/c) = equal?\n```\nReturns the longest common prefix of l and r.\n\nExample:\n\n> ```racket\n> > ( take-common-prefix ' ( a b c d ) ' ( a b x y z ) )\n> '(a b)\n> ```\n\nAdded in version 6.3 of package base.\n\n> ```\n(drop-common-prefix l r [same?) → list? list?\n\n  l : list?\n  r : list?\n  same? : (any/c any/c . → . any/c) = equal?```\n\n\nReturns the tails of l and r with the common prefix removed.\n\nExample:\n\n> ```racket\n> > ( drop-common-prefix ' ( a b c d ) ' ( a b x y z ) )\n> '(c d) '(x y z)\n> ```\n\nAdded in version 6.3 of package base.\n\n> ```\n(split-common-prefix l r [same?) → list? list? list?\n\n  l : list?\n  r : list?\n  same? : (any/c any/c . → . any/c) = equal?\n```\nReturns the longest common prefix together with the tails of l and r with the common prefix removed.\nExample:\n> ```racket\n> > ( split-common-prefix ' ( a b c d ) ' ( a b x y z ) )\n> '(a b) '(c d) '(x y z)\n> ```\nAdded in version 6.3 of package base.\n> ```"} {"text": "# 4.6 Characters\n(add-between lst\n    v        \n   [ #:before-first before-first        \n    #:before-last before-last        \n    #:after-last after-last        \n    #:splice? splice?)   →   list?\n  lst : list?\n  v : any/c\n  before-first : list? = '()\n  before-last : any/c = v\n  after-last : list? = '()\n  splice? : any/c = #f```\nReturns a list with the same elements as lst, but with v between each pair of elements in lst; the last pair of elements will have before-last between them, instead of v (but before-last defaults to v).\nIf splice? is true, then v and before-last should be lists, and the list elements are spliced into the result. In addition, when splice? is true, before-first and after-last are inserted before the first element and after the last element respectively.\nExamples:\n> ```racket\n> > ( add-between ' ( x y z ) ' and )\n> '(x and y and z)\n> > ( add-between ' ( x ) ' and )\n> '(x)\n> > ( add-between ' ( \"a\" \"b\" \"c\" \"d\" ) \",\" #:before-last \"and\" )\n> '(\"a\" \",\" \"b\" \",\" \"c\" \"and\" \"d\")\n> > ( add-between ' ( x y z ) ' ( - ) #:before-last ' ( - - ) #:before-first ' ( begin ) #:after-last ' ( end LF ) #:splice? #t )\n> '(begin x - y - - z end LF)\n> ```\n> ```\n(append* lst ... lsts) → list?\n  lst : list?\n  lsts : (listof list?)\n(append* lst ... lsts)  →  any/c\n  lst : list?\n  lsts : list?"} {"text": "# 4.6 Characters\n```\nLike append, but the last argument is used as a list of arguments for append, so (append* lst ... lsts) is the same as (apply append lst ... lsts). In other words, the relationship between append and append* is similar to the one between list and list*.\n\nExamples:\n\n> ```racket\n> > ( append* ' ( a ) ' ( b ) ' ( ( c ) ( d ) ) )\n> '(a b c d)\n> > ( cdr ( append* ( map ( lambda ( x ) ( list \", \" x ) ) ' ( \"Alpha\" \"Beta\" \"Gamma\" ) ) ) )\n> '(\"Alpha\" \", \" \"Beta\" \", \" \"Gamma\")\n> ```\n\n> ```\n(flatten v) → list?\n  v : any/c```\n\n\nFlattens an arbitrary S-expression structure of pairs into a list. More precisely, v is treated as a binary tree where pairs are interior nodes, and the resulting list contains all of the non-[null](#%28def._%28%28quote._~23~25kernel%29._null%29%29) leaves of the tree in the same order as an inorder traversal.\n\nExamples:\n\n> ```racket\n> > ( flatten ' ( ( a ) b ( c ( d ) . e ) ( ) ) )\n> '(a b c d e)\n> > ( flatten ' a )\n> '(a)\n> ```\n\n> ```\n(check-duplicates lst\n   [ same?        \n    #:key extract-key        \n    #:default failure-result)   →   any\n\n  lst : list?\n  same? : (any/c any/c . → . any/c) = equal?\n  extract-key : ( →  any/c any/c) = (lambda (x) x)\n  failure-result : failure-result/c = (lambda () #f)\n```\nReturns the first duplicate item in lst. More precisely, it returns the first x such that there was a previous y where (same? (extract-key x) (extract-key y)).\nIf no duplicate is found, then failure-result determines the result:"} {"text": "# 4.6 Characters\n- If failure-result is a procedure, it is called (through a tail call) with no arguments to produce the result.\n- Otherwise, failure-result is returned as the result.\nThe same? argument should be an equivalence predicate such as equal? or eqv?. The procedures equal?, eqv?, eq?, and equal-always? automatically use a dictionary for speed.\nExamples:\n> ```racket\n> > ( check-duplicates ' ( 1 2 3 4 ) )\n> #f\n> > ( check-duplicates ' ( 1 2 3 2 1 ) )\n> 2\n> > ( check-duplicates ' ( ( a 1 ) ( b 2 ) ( a 3 ) ) #:key car )\n> '(a 3)\n> > ( check-duplicates ' ( 1 2 3 4 5 6 ) ( lambda ( x y ) ( equal? ( modulo x 3 ) ( modulo y 3 ) ) ) )\n> 4\n> > ( check-duplicates ' ( 1 2 3 4 ) #:default \"no duplicates\" )\n> \"no duplicates\"\n> ```\nAdded in version 6.3 of package base. \nChanged in version 6.11.0.2: Added the #:default optional argument.\n> ```\n(remove-duplicates lst\n   [ same?        \n    #:key extract-key)   →   list?\n  lst : list?\n  same? : (any/c any/c . → . any/c) = equal?\n  extract-key : (any/c . → . any/c) = (lambda (x) x)```\nReturns a list that has all items in lst, but without duplicate items, where same? determines whether two elements of the list are equivalent. The resulting list is in the same order as lst, and for any item that occurs multiple times, the first one is kept.\nThe #:key argument extract-key is used to extract a key value from each list element, so two items are considered equal if (same? (extract-key x) (extract-key y)) is true."} {"text": "# 4.6 Characters\nLike [check-duplicates](#%28def._%28%28lib._racket%2Flist..rkt%29._check-duplicates%29%29), if the same? argument is one of [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29), and [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), the operation can be specialized to improve performance.\nExamples:\n> ```racket\n> > ( remove-duplicates ' ( a b b a ) )\n> '(a b)\n> > ( remove-duplicates ' ( 1 2 1.0 0 ) )\n> '(1 2 1.0 0)\n> > ( remove-duplicates ' ( 1 2 1.0 0 ) = )\n> '(1 2 0)\n> ```\n> ```\n(filter-map proc lst ...+) → list?\n  proc : procedure?\n  lst : list?"} {"text": "# 4.6 Characters\n```\nLike (map proc lst ...), except that, if proc returns #false, that element is omitted from the resulting list. In other words, filter-map is equivalent to (filter (lambda (x) x) (map proc lst ...)), but more efficient, because filter-map avoids building the intermediate list.\n\nExample:\n\n> ```racket\n> > ( filter-map ( lambda ( x ) ( and ( negative? x ) ( abs x ) ) ) ' ( 1 2 -3 -4 8 ) )\n> '(3 4)\n> ```\n\n> ```\n(count proc lst ...+) → exact-nonnegative-integer?\n  proc : procedure?\n  lst : list?```\n\n\nReturns ([length](#%28def._%28%28quote._~23~25kernel%29._length%29%29) ([filter-map](#%28def._%28%28lib._racket%2Flist..rkt%29._filter-map%29%29) proc lst [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29))), but without building the intermediate list.\n\nExample:\n\n> ```racket\n> > ( count positive? ' ( 1 -1 2 3 -2 5 ) )\n> 4\n> ```\n\n> ```\n(partition pred lst)   →   list?   list?\n\n  pred : procedure?\n  lst : list?\n```\nSimilar to filter, except that two values are returned: the items for which pred returns a true value, and the items for which pred returns #f.\nThe result is the same as\n> (values (filter pred lst) (filter (negate pred) lst))\nbut pred is applied to each item in lst only once.\nExample:\n> ```racket\n> > ( partition even? ' ( 1 2 3 4 5 6 ) )\n> '(2 4 6) '(1 3 5)\n> ```\n> ```\n(range end) → list?\n  end : real?\n(range start end [step)  →  list?\n  start : real?\n  end : real?\n  step : real? = 1```"} {"text": "# 4.6 Characters\nSimilar to [in-range](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29), but returns lists.\nThe resulting list holds numbers starting at start and whose successive elements are computed by adding step to their predecessor until end (excluded) is reached. If no starting point is provided, 0 is used. If no step argument is provided, 1 is used.\nLike [in-range](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29), a [range](#%28def._%28%28lib._racket%2Flist..rkt%29._range%29%29) application can provide better performance when it appears directly in a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) clause.\nExamples:\n> ```racket\n> > ( range 10 )\n> '(0 1 2 3 4 5 6 7 8 9)\n> > ( range 10 20 )\n> '(10 11 12 13 14 15 16 17 18 19)\n> > ( range 20 40 2 )\n> '(20 22 24 26 28 30 32 34 36 38)\n> > ( range 20 10 -1 )\n> '(20 19 18 17 16 15 14 13 12 11)\n> > ( range 10 15 1.5 )\n> '(10 11.5 13.0 14.5)\n> ```\nChanged in version 6.7.0.4 of package base: Adjusted to cooperate with [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) in the same way that [in-range](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29) does.\n> ```\n(inclusive-range start end [step) → list?\n  start : real?\n  end : real?\n  step : real? = 1"} {"text": "# 4.6 Characters\n```\nSimilar to in-inclusive-range, but returns lists.\n\nThe resulting list holds numbers starting at start and whose successive elements are computed by adding step to their predecessor until end (included) is reached. If no step argument is provided, 1 is used.\n\nLike in-inclusive-range, an inclusive-range application can provide better performance when it appears directly in a for clause.\n\nExamples:\n\n> ```racket\n> > ( inclusive-range 10 20 )\n> '(10 11 12 13 14 15 16 17 18 19 20)\n> > ( inclusive-range 20 40 2 )\n> '(20 22 24 26 28 30 32 34 36 38 40)\n> > ( inclusive-range 20 10 -1 )\n> '(20 19 18 17 16 15 14 13 12 11 10)\n> > ( inclusive-range 10 15 1.5 )\n> '(10 11.5 13.0 14.5)\n> ```\n\nAdded in version 8.0.0.13 of package base.\n\n> ```\n(append-map proc lst ...+) → list?\n  proc : procedure?\n  lst : list?```\n\n\nReturns ([append*](#%28def._%28%28lib._racket%2Flist..rkt%29._append%2A%29%29) ([map](#%28def._%28%28lib._racket%2Fprivate%2Fmap..rkt%29._map%29%29) proc lst [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29))).\n\nExample:\n\n> ```racket\n> > ( append-map vector->list ' ( # ( 1 ) # ( 2 3 ) # ( 4 ) ) )\n> '(1 2 3 4)\n> ```\n\n> ```\n(filter-not pred lst)  →  list?\n  pred : (any/c . → . any/c)\n  lst : list?\n```\nLike filter, but the meaning of the pred predicate is reversed: the result is a list of all items for which pred returns #f.\nExample:\n> ```racket\n> > ( filter-not even? ' ( 1 2 3 4 5 6 ) )\n> '(1 3 5)\n> ```\n> ```\n(shuffle lst)  →  list?\n  lst : list?```"} {"text": "# 4.6 Characters\nReturns a list with all elements from lst, randomly shuffled.\nExamples:\n> ```racket\n> > ( shuffle ' ( 1 2 3 4 5 6 ) )\n> '(6 3 1 2 4 5)\n> > ( shuffle ' ( 1 2 3 4 5 6 ) )\n> '(4 6 5 2 3 1)\n> > ( shuffle ' ( 1 2 3 4 5 6 ) )\n> '(5 4 3 6 1 2)\n> ```\n> ```\n(combinations lst)  →  list?\n  lst : list?\n(combinations lst size)  →  list?\n  lst : list?\n  size : exact-nonnegative-integer?\n```\n> > > Wikipedia combinations\n\nReturn a list of all combinations of elements in the input list (a.k.a. the powerset of lst). If size is given, limit results to combinations of size elements.\n\nExamples:\n\n> ```racket\n> > ( combinations ' ( 1 2 3 ) )\n> '(() (1) (2) (1 2) (3) (1 3) (2 3) (1 2 3))\n> > ( combinations ' ( 1 2 3 ) 2 )\n> '((1 2) (1 3) (2 3))\n> ```\n\n> ```\n(in-combinations lst)  →  sequence?\n  lst : list?\n(in-combinations lst size)  →  sequence?\n  lst : list?\n  size : exact-nonnegative-integer?```\n\n\nReturns a sequence of all combinations of elements in the input list, or all combinations of length size if size is given. Builds combinations one-by-one instead of all at once.\n\nExamples:\n\n> ```racket\n> > ( time ( begin ( combinations ( range 15 ) ) ( void ) ) )\n> cpu time: 12 real time: 2 gc time: 0\n> > ( time ( begin ( in-combinations ( range 15 ) ) ( void ) ) )\n> cpu time: 0 real time: 0 gc time: 0\n> ```\n\n> ```\n(permutations lst)  →  list?\n  lst : list?\n```"} {"text": "# 4.6 Characters\nReturns a list of all permutations of the input list. Note that this function works without inspecting the elements, and therefore it ignores repeated elements (which will result in repeated permutations). Raises an error if the input list contains more than 256 elements.\nExamples:\n> ```racket\n> > ( permutations ' ( 1 2 3 ) )\n> '((1 2 3) (2 1 3) (1 3 2) (3 1 2) (2 3 1) (3 2 1))\n> > ( permutations ' ( x x ) )\n> '((x x) (x x))\n> ```\n> ```\n(in-permutations lst)  →  sequence?\n  lst : list?\n```\n\n\nReturns a sequence of all permutations of the input list. It is equivalent to ([in-list](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-list%29%29) ([permutations](#%28def._%28%28lib._racket%2Flist..rkt%29._permutations%29%29) l)) but much faster since it builds the permutations one-by-one on each iteration. Raises an error if the input list contains more than 256 elements.\n\n> ```\n(argmin proc lst)  →  any/c\n  proc : ( →  any/c real?)\n  lst : (and/c pair? list?)\n```\nReturns the first element in the list lst that minimizes the result of proc. Signals an error on an empty list. See also min.\nExamples:\n> ```racket\n> > ( argmin car ' ( ( 3 pears ) ( 1 banana ) ( 2 apples ) ) )\n> '(1 banana)\n> > ( argmin car ' ( ( 1 banana ) ( 1 orange ) ) )\n> '(1 banana)\n> ```\n> ```\n(argmax proc lst)  →  any/c\n  proc : ( →  any/c real?)\n  lst : (and/c pair? list?)```\nReturns the first element in the list lst that maximizes the result of proc. Signals an error on an empty list. See also [max](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._max%29%29)."} {"text": "# 4.6 Characters\nExamples:\n> ```racket\n> > ( argmax car ' ( ( 3 pears ) ( 1 banana ) ( 2 apples ) ) )\n> '(3 pears)\n> > ( argmax car ' ( ( 3 pears ) ( 3 oranges ) ) )\n> '(3 pears)\n> ```\n> ```\n(group-by key lst [same?) → (listof list?)\n  key : ( →  any/c any/c)\n  lst : list?\n  same? : (any/c any/c . → . any/c) = equal?\n```\nGroups the given list into equivalence classes, with equivalence being determined by same?. Within each equivalence class, group-by preserves the ordering of the original list. Equivalence classes themselves are in order of first appearance in the input.\n\nExample:\n\n> ```racket\n> > ( group-by ( lambda ( x ) ( modulo x 3 ) ) ' ( 1 2 1 2 54 2 5 43 7 2 643 1 2 0 ) )\n> '((1 1 43 7 643 1) (2 2 2 5 2 2) (54 0))\n> ```\n\nAdded in version 6.3 of package base.\n\n> ```\n(cartesian-product lst ...) → (listof list?)\n  lst : list?```\n\n\nComputes the n-ary cartesian product of the given lists.\n\nExamples:\n\n> ```racket\n> > ( cartesian-product ' ( 1 2 3 ) ' ( a b c ) )\n> '((1 a) (1 b) (1 c) (2 a) (2 b) (2 c) (3 a) (3 b) (3 c))\n> > ( cartesian-product ' ( 4 5 6 ) ' ( d e f ) ' ( #t #f ) )\n> '((4 d #t) (4 d #f) (4 e #t) (4 e #f) (4 f #t) (4 f #f) (5 d #t) (5 d #f) (5 e #t) (5 e #f) (5 f #t) (5 f #f) (6 d #t) (6 d #f) (6 e #t) (6 e #f) (6 f #t) (6 f #f))\n> ```\n\nAdded in version 6.3 of package base.\n\n> ```\n(remf pred lst)  →  list?\n  pred : procedure?\n  lst : list?\n```\nReturns a list that is like lst, omitting the first element of lst for which pred produces a true value.\nExample:\n> ```racket\n> > ( remf negative? ' ( 1 -2 3 4 -5 ) )\n> '(1 3 4 -5)\n> ```"} {"text": "# 4.6 Characters\nAdded in version 6.3 of package base.\n> ```\n(remf* pred lst)  →  list?\n  pred : procedure?\n  lst : list?```\nLike [remf](#%28def._%28%28lib._racket%2Flist..rkt%29._remf%29%29), but removes all the elements for which pred produces a true value.\nExample:\n> ```racket\n> > ( remf* negative? ' ( 1 -2 3 4 -5 ) )\n> '(1 3 4)\n> ```\nAdded in version 6.3 of package base."} {"text": "#### 4.10.9 More List Grouping\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/list/grouping](#%28mod-path._racket%2Flist%2Fgrouping%29)) |  package: [sequence-tools-lib](https://pkgs.racket-lang.org/package/sequence-tools-lib \"Install this package using `raco pkg install sequence-tools-lib`\") |\nThe bindings documented in this section are provided by the [racket/list/grouping](#%28mod-path._racket%2Flist%2Fgrouping%29) library, not [racket/base](index.html) or [racket](index.html).\nThe bindings in this section are provided by the sequence-tools-lib package, which acts as an extension to the base sequence libraries.\n> ```\n(windows size step lst)  →  (listof list?)\n  size : exact-positive-integer?\n  step : exact-positive-integer?\n  lst : list?"} {"text": "# 4.6 Characters\n```\n\n\nReturns a list of sliding windows such that each window contains size elements with the window sliding step positions on each iteration. If the number of remaining elements is less than size, then those elements are dropped.\n\nExamples:\n\n> ```racket\n> > ( windows 3 1 ' ( 1 2 3 4 ) )\n> '((1 2 3) (2 3 4))\n> > ( windows 2 3 ' ( 1 2 3 ) )\n> '((1 2))\n> > ( windows 1 2 ' ( 1 2 3 4 ) )\n> '((1) (3))\n> ```\n\n> ```\n(slice-by proc lst)  →  (listof list?)\n  proc : ( →  any/c any/c any/c)\n  lst : list?\n```\nReturns a list such that each element is a sublist (slice) that is constructed from comparing each pair of adjacent elements. All pairs of elements that satisfy proc will be grouped together into a slice, otherwise the element will start a new slice.\nExamples:\n> ```racket\n> > ( slice-by eq? ' ( 1 1 2 1 3 3 ) )\n> '((1 1) (2) (1) (3 3))\n> > ( slice-by < ' ( 1 2 3 3 4 ) )> '((1 2 3) (3 4))\n> ```"} {"text": "#### 4.10.10 Immutable Cyclic Data\n> ```\n(make-reader-graph v)  →  any/c\n  v : any/c\n```\nReturns a value like v, with placeholders created by make-placeholder replaced with the values that they contain, and with hash placeholders created by make-hash-placeholder with an immutable hash table. No part of v is mutated; instead, parts of v are copied as necessary to construct the resulting graph, where at most one copy is created for any given value.\n\nSince the copied values can be immutable, and since the copy is also immutable, make-reader-graph can create cycles involving only immutable pairs, vectors, boxes, and hash tables.\n\nOnly the following kinds of values are copied and traversed to detect placeholders:\n\n- pairs\n\n- vectors, both mutable and immutable\n\n- boxes, both mutable and immutable\n\n- hash tables, both mutable and immutable\n\n- instances of a prefab structure type\n\n- placeholders created by make-placeholder and make-hash-placeholder\n\nDue to these restrictions, make-reader-graph creates exactly the same sort of cyclic values as read.\n\nExample:\n\n> ```racket\n> > ( let* ( [ ph ( make-placeholder #f ) ] [ x ( cons 1 ph ) ] ) ( placeholder-set! ph x ) ( make-reader-graph x ) )\n> #0='(1 . #0#)\n> ```\n\n> ```\n(placeholder? v) → boolean?\n  v : any/c```\n\n\nReturns #t if v is a [placeholder](#%28tech._placeholder%29) created by [make-placeholder](#%28def._%28%28quote._~23~25kernel%29._make-placeholder%29%29), #f otherwise.\n\n> ```\n(make-placeholder v)  →  placeholder?\n  v : any/c\n```\n(parameter)\t→```\nChanges the value of ph to v.\n> ```"} {"text": "# 4.6 Characters\n(placeholder-get ph)  →  any/c\n  ph : placeholder?\n```\n\n\nReturns the value of ph.\n\n> ```\n(hash-placeholder? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a [hash placeholder](#%28tech._hash._placeholder%29) created by [make-hash-placeholder](#%28def._%28%28quote._~23~25kernel%29._make-hash-placeholder%29%29), #f otherwise.\n> ```\n(make-hash-placeholder assocs)  →  hash-placeholder?\n  assocs : (listof pair?)\n```\nLike make-immutable-hash, but produces a hash placeholder for use with make-reader-graph.\n\n> ```\n(make-hasheq-placeholder assocs)  →  hash-placeholder?\n  assocs : (listof pair?)```\n\n\nLike [make-immutable-hasheq](hashtables.html#%28def._%28%28quote._~23~25kernel%29._make-immutable-hasheq%29%29), but produces a [hash placeholder](#%28tech._hash._placeholder%29) for use with [make-reader-graph](#%28def._%28%28quote._~23~25kernel%29._make-reader-graph%29%29).\n\n> ```\n(make-hasheqv-placeholder assocs)  →  hash-placeholder?\n  assocs : (listof pair?)\n```\nLike make-immutable-hasheqv, but produces a hash placeholder for use with make-reader-graph.\n> ```\n(make-hashalw-placeholder assocs)  →  hash-placeholder?\n  assocs : (listof pair?)```\nLike [make-immutable-hashalw](hashtables.html#%28def._%28%28quote._~23~25kernel%29._make-immutable-hashalw%29%29), but produces a [hash placeholder](#%28tech._hash._placeholder%29) for use with [make-reader-graph](#%28def._%28%28quote._~23~25kernel%29._make-reader-graph%29%29).\nAdded in version 8.5.0.3 of package base.\n------------------------------------------------------------------------"} {"text": "# 4.11 Mutable Pairs and Lists"} {"text": "### 4.11 Mutable Pairs and Lists\nA mutable pair is like a pair created by [cons](pairs.html#%28def._%28%28quote._~23~25kernel%29._cons%29%29), but it supports [set-mcar!](#%28def._%28%28quote._~23~25kernel%29._set-mcar%21%29%29) and [set-mcdr!](#%28def._%28%28quote._~23~25kernel%29._set-mcdr%21%29%29) mutation operations to change the parts of the mutable pair (like traditional Lisp and Scheme pairs).\nA mutable list is analogous to a list created with pairs, but instead created with [mutable pairs](#%28tech._mutable._pair%29).\nA [mutable pair](#%28tech._mutable._pair%29) is not a [pair](pairs.html#%28tech._pair%29); they are completely separate datatypes. Similarly, a [mutable list](#%28tech._mutable._list%29) is not a [list](pairs.html#%28tech._list%29), except that the empty list is also the empty mutable list. Instead of programming with mutable pairs and mutable lists, data structures such as pairs, lists, and hash tables are practically always better choices.\nA [mutable list](#%28tech._mutable._list%29) can be used as a single-valued sequence (see [Sequences](sequences.html)). The elements of the [mutable list](#%28tech._mutable._list%29) serve as elements of the sequence. See also [in-mlist](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-mlist%29%29)."} {"text": "#### 4.11.1 Mutable Pair Constructors and Selectors\n> ```\n(mpair? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a mutable pair, #f otherwise.\n\n> ```\n(mcons a d)  →  mpair?\n  a : any/c\n  d : any/c```\n\n\nReturns a newly allocated [mutable pair](#%28tech._mutable._pair%29) whose first element is a and second element is d.\n\n> ```\n(mcar p)  →  any/c\n  p : mpair?\n```\nReturns the first element of the mutable pair p.\n> ```\n(mcdr p)  →  any/c\n  p : mpair?```\nReturns the second element of the [mutable pair](#%28tech._mutable._pair%29) p.\n> ```\n(parameter)\t→\n```\n(parameter)\t→```\n\n\nChanges the [mutable pair](#%28tech._mutable._pair%29) p so that its second element is v.\n\n------------------------------------------------------------------------\n\n# 4.12 Vectors\n\n### 4.12 Vectors\n\n> > > \"+\"[Vectors](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=vectors.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces vectors.\n\nA vector is a fixed-length array with constant-time access and update of the vector slots, which are numbered from 0 to one less than the number of slots in the vector.\n\nTwo vectors are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) if they have the same length, and if the values in corresponding slots of the vectors are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29).\n\nA vector can be mutable or immutable. When an immutable vector is provided to a procedure like [vector-set!](#%28def._%28%28quote._~23~25kernel%29._vector-set%21%29%29), the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. Vectors generated by the default reader (see [Reading Strings](reader.html#%28part._parse-string%29)) are immutable. Use [immutable?](booleans.html#%28def._%28%28quote._~23~25kernel%29._immutable~3f%29%29) to check whether a vector is immutable.\n\nA vector can be used as a single-valued sequence (see [Sequences](sequences.html)). The elements of the vector serve as elements of the sequence. See also [in-vector](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-vector%29%29).\n\nA literal or printed vector starts with #(, optionally with a number between the # and (. See [Reading Vectors](reader.html#%28part._parse-vector%29) for information on [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29)ing vectors and [Printing Vectors](printing.html#%28part._print-vectors%29) for information on [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29)ing vectors.\n\n> ```\n(vector? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 4.11 Mutable Pairs and Lists\nReturns #t if v is a vector, #f otherwise.\nSee also immutable-vector? and mutable-vector?.\n> ```\n(make-vector size [v) → vector?\n  size : exact-nonnegative-integer?\n  v : any/c = 0```\nReturns a mutable vector with size slots, where all slots are initialized to contain v. Note that v is shared for all elements, so for mutable data, mutating an element will affect other elements.\nExamples:\n> ```racket\n> > ( make-vector 3 2 )\n> '#(2 2 2)\n> > ( define v ( make-vector 5 ( box 3 ) ) )\n> > v\n> '#(#&3 #&3 #&3 #&3 #&3)\n> > ( set-box! ( vector-ref v 0 ) 7 )\n> > v\n> '#(#&7 #&7 #&7 #&7 #&7)\n> ```\nThis function takes time proportional to size.\nA common mistake is using [make-vector](#%28def._%28%28quote._~23~25kernel%29._make-vector%29%29) to create nested vectors. The fact that v is shared for all elements means that ([make-vector](#%28def._%28%28quote._~23~25kernel%29._make-vector%29%29) 3 ([make-vector](#%28def._%28%28quote._~23~25kernel%29._make-vector%29%29) 4)) would not be a good way of representing a mutable 3x4 matrix, for example, since just one mutable vector would be shared three times. Using [for/vector](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fvector%29%29) as follows more likely produces the intended result, since it evaluates ([make-vector](#%28def._%28%28quote._~23~25kernel%29._make-vector%29%29) 4) separately for each iteration:\nExample:\n> ```racket\n> > ( for/vector ( [ i ( in-range 3 ) ] ) ( make-vector 4 ) )\n> '#(#(0 0 0 0) #(0 0 0 0) #(0 0 0 0))\n> ```\n> ```\n(vector v ...) → vector?\n  v : any/c"} {"text": "# 4.11 Mutable Pairs and Lists\n```\nReturns a newly allocated mutable vector with as many slots as provided vs, where the slots are initialized to contain the given vs in order.\n\n> ```\n(vector-immutable v ...) → (and/c vector?\n> immutable? )\n\n  v : any/c```\n\n\nReturns a newly allocated immutable vector with as many slots as provided vs, where the slots contain the given vs in order.\n\n> ```\n(vector-length vec)  →  exact-nonnegative-integer?\n  vec : vector?\n```\nReturns the length of vec (i.e., the number of slots in the vector).\nThis function takes constant time.\n> ```\n(vector-ref vec pos)  →  any/c\n  vec : vector?\n  pos : exact-nonnegative-integer?\n```\n\n\nReturns the element in slot pos of vec. The first slot is position 0, and the last slot is one less than ([vector-length](#%28def._%28%28quote._~23~25kernel%29._vector-length%29%29) vec).\n\nThis function takes constant time.\n\n> ```\n(parameter)\t→\t\n(-> and/c vector? (not/c immutable?))\n```\n(parameter)\t→\t\n(-> and/c vector? (not/c impersonator?))```\nLike [vector-length](#%28def._%28%28quote._~23~25kernel%29._vector-length%29%29), [vector-ref](#%28def._%28%28quote._~23~25kernel%29._vector-ref%29%29), and [vector-set!](#%28def._%28%28quote._~23~25kernel%29._vector-set%21%29%29), but constrained to work on vectors that are not [impersonators](chaperones.html#%28tech._impersonator%29).\nAdded in version 6.90.0.15 of package base.\n> ```\n(vector-cas! vec pos old-v new-v)  →  boolean?\n  vec : (and/c vector? (not/c immutable?) (not/c impersonator?))\n  pos : exact-nonnegative-integer?\n  old-v : any/c\n  new-v : any/c"} {"text": "# 4.11 Mutable Pairs and Lists\n```\nCompare and set operation for vectors. See box-cas!.\n\nAdded in version 6.11.0.2 of package base.\n\n> ```\n(vector → list vec)  →  list?\n  vec : vector?```\n\n\nReturns a list with the same length and elements as vec.\n\nThis function takes time proportional to the size of vec.\n\n> ```\n(list → vector lst)  →  vector?\n  lst : list?\n```\nReturns a mutable vector with the same length and elements as lst.\nThis function takes time proportional to the length of lst.\n> ```\n(vector → immutable-vector vec)  →  (and/c vector? immutable?)\n  vec : vector?\n```\n\n\nReturns an immutable vector with the same length and elements as vec. If vec is itself immutable, then it is returned as the result.\n\nThis function takes time proportional to the size of vec when vec is mutable.\n\n> ```\n(parameter)\t→\t\n(-> and/c vector? (not/c immutable?))\n```\n(parameter)\t→\t\n(-> and/c vector? (not/c immutable?))```\nChanges the elements of dest starting at position dest-start to match the elements in src from src-start (inclusive) to src-end (exclusive). The vectors dest and src can be the same vector, and in that case the destination region can overlap with the source region; the destination elements after the copy match the source elements from before the copy. If any of dest-start, src-start, or src-end are out of range (taking into account the sizes of the vectors and the source and destination regions), the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised."} {"text": "# 4.11 Mutable Pairs and Lists\nThis function takes time proportional to ([-](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._-%29%29) src-end src-start).\nExamples:\n> ```racket\n> > ( define v ( vector ' A ' p ' p ' l ' e ) )\n> > ( vector-copy! v 4 # ( y ) )\n> > ( vector-copy! v 0 v 3 4 )\n> > v\n> '#(l p p l y)\n> ```\n> ```\n(vector → values vec [start-pos end-pos) → any\n  vec : vector?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : exact-nonnegative-integer? = (vector-length vec)\n```\nReturns end-pos - start-pos values, which are the elements of vec from start-pos (inclusive) to end-pos (exclusive). If start-pos or end-pos are greater than (vector-length vec), or if end-pos is less than start-pos, the exn:fail:contract exception is raised.\n\nThis function takes time proportional to the size of vec.\n\n> ```\n(build-vector n proc)  →  vector?\n  n : exact-nonnegative-integer?\n  proc : (exact-nonnegative-integer? . → . any/c)```\n\n\nCreates a vector of n elements by applying proc to the integers from 0 to ([sub1](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._sub1%29%29) n) in order. If vec is the resulting vector, then ([vector-ref](#%28def._%28%28quote._~23~25kernel%29._vector-ref%29%29) vec i) is the value produced by (proc i).\n\nExample:\n\n> ```racket\n> > ( build-vector 5 add1 )\n> '#(1 2 3 4 5)\n> ```\n\n#### 4.12.1 Additional Vector Functions\n\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/vector](#%28mod-path._racket%2Fvector%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/vector](#%28mod-path._racket%2Fvector%29) and [racket](index.html) libraries, but not [racket/base](index.html).\n\n> ```\n(vector-empty? v)  →  boolean?\n  v : vector?\n```"} {"text": "# 4.11 Mutable Pairs and Lists\n(parameter)\t→\t\n(-> and/c vector? (not/c immutable?))```\nUpdates each slot pos of vec to contain each v. The update takes place from the left so later updates overwrite earlier updates.\n> ```\n(vector-map proc vec ...+) → vector?\n  proc : procedure?\n  vec : vector?\n```\nApplies proc to the elements of the vecs from the first elements to the last. The proc argument must accept the same number of arguments as the number of supplied vecs, and all vecs must have the same number of elements. The result is a fresh vector containing each result of proc in order.\n\nExample:\n\n> ```racket\n> > ( vector-map + # ( 1 2 ) # ( 3 4 ) )\n> '#(4 6)\n> ```\n\n> ```\n(vector-map! proc vec ...+) → vector?\n  proc : procedure?\n  vec : (and/c vector? (not/c immutable?))```\n\n\nLike [vector-map](#%28def._%28%28lib._racket%2Fvector..rkt%29._vector-map%29%29), but result of proc is inserted into the first vec at the index that the arguments to proc were taken from. The result is the first vec.\n\nExamples:\n\n> ```racket\n> > ( define v ( vector 1 2 3 4 ) )\n> > ( vector-map! add1 v )\n> '#(2 3 4 5)\n> > v\n> '#(2 3 4 5)\n> ```\n\n> ```\n(vector-append vec ...) → vector?\n  vec : vector?\n```\nCreates a fresh vector that contains all of the elements of the given vectors in order.\nExample:\n> ```racket\n> > ( vector-append # ( 1 2 ) # ( 3 4 ) )\n> '#(1 2 3 4)\n> ```\n> ```\n(vector-take vec pos)  →  vector?\n  vec : vector?\n  pos : exact-nonnegative-integer?"} {"text": "# 4.11 Mutable Pairs and Lists\n```\n\n\nReturns a fresh vector whose elements are the first pos elements of vec. If vec has fewer than pos elements, then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nExample:\n\n> ```racket\n> > ( vector-take # ( 1 2 3 4 ) 2 )\n> '#(1 2)\n> ```\n\n> ```\n(vector-take-right vec pos)  →  vector?\n  vec : vector?\n  pos : exact-nonnegative-integer?\n```\nReturns a fresh vector whose elements are the last pos elements of vec. If vec has fewer than pos elements, then the exn:fail:contract exception is raised.\nExample:\n> ```racket\n> > ( vector-take-right # ( 1 2 3 4 ) 2 )\n> '#(3 4)\n> ```\n> ```\n(vector-drop vec pos)  →  vector?\n  vec : vector?\n  pos : exact-nonnegative-integer?```\nReturns a fresh vector whose elements are the elements of vec after the first pos elements. If vec has fewer than pos elements, then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nExample:\n> ```racket\n> > ( vector-drop # ( 1 2 3 4 ) 2 )\n> '#(3 4)\n> ```\n> ```\n(vector-drop-right vec pos)  →  vector?\n  vec : vector?\n  pos : exact-nonnegative-integer?"} {"text": "# 4.11 Mutable Pairs and Lists\n```\nReturns a fresh vector whose elements are the prefix of vec, dropping its pos-length tail. If vec has fewer than pos elements, then the exn:fail:contract exception is raised.\n\nExamples:\n\n> ```racket\n> > ( vector-drop-right # ( 1 2 3 4 ) 1 )\n> '#(1 2 3)\n> > ( vector-drop-right # ( 1 2 3 4 ) 3 )\n> '#(1)\n> ```\n\n> ```\n(vector-split-at vec pos)   →   vector?   vector?\n\n  vec : vector?\n  pos : exact-nonnegative-integer?```\n\n\nReturns the same result as\n\n> ([values](values.html#%28def._%28%28quote._~23~25kernel%29._values%29%29) ([vector-take](#%28def._%28%28lib._racket%2Fvector..rkt%29._vector-take%29%29) vec pos) ([vector-drop](#%28def._%28%28lib._racket%2Fvector..rkt%29._vector-drop%29%29) vec pos))\n\nexcept that it can be faster.\n\nExample:\n\n> ```racket\n> > ( vector-split-at # ( 1 2 3 4 5 ) 2 )\n> '#(1 2) '#(3 4 5)\n> ```\n\n> ```\n(vector-split-at-right vec pos)   →   vector?   vector?\n\n  vec : vector?\n  pos : exact-nonnegative-integer?\n```\nReturns the same result as\n> (values (vector-take-right vec pos) (vector-drop-right vec pos))\nexcept that it can be faster.\nExample:\n> ```racket\n> > ( vector-split-at-right # ( 1 2 3 4 5 ) 2 )\n> '#(1 2 3) '#(4 5)\n> ```\n> ```\n(vector-copy vec [start end) → vector?\n  vec : vector?\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (vector-length v)```\nCreates a fresh vector of size ([-](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._-%29%29) end start), with all of the elements of vec from start (inclusive) to end (exclusive).\nExamples:"} {"text": "# 4.11 Mutable Pairs and Lists\n> ```racket\n> > ( vector-copy # ( 1 2 3 4 ) )\n> '#(1 2 3 4)\n> > ( vector-copy # ( 1 2 3 4 ) 3 )\n> '#(4)\n> > ( vector-copy # ( 1 2 3 4 ) 2 3 )\n> '#(3)\n> ```\n> ```\n(vector-set/copy vec pos val)  →  vector?\n  vec : vector?\n  pos : exact-nonnegative-integer?\n  val : any/c\n```\nCreates a fresh vector with the same content as vec, except that val is the element at index pos.\n\nExamples:\n\n> ```racket\n> > ( vector-set/copy # ( 1 2 3 ) 0 ' x )\n> '#(x 2 3)\n> > ( vector-set/copy # ( 1 2 3 ) 2 ' x )\n> '#(1 2 x)\n> ```\n\nAdded in version 8.11.1.10 of package base.\n\n> ```\n(vector-extend vec new-size [val) → vector?\n  vec : vector?\n  new-size : (and/c exact-nonnegative-integer? (>=/c (vector-length vec)))\n  val : any/c = 0```\n\n\nCreates a fresh vector of length new-size where the prefix is filled with the elements of vec and the remainder with val.\n\nExamples:\n\n> ```racket\n> > ( vector-extend # ( 1 2 3 ) 10 )\n> '#(1 2 3 0 0 0 0 0 0 0)\n> > ( vector-extend # ( 1 2 3 ) 10 #f )\n> '#(1 2 3 #f #f #f #f #f #f #f)\n> > ( vector-extend # ( 1 2 3 ) 3 #f )\n> '#(1 2 3)\n> ```\n\nAdded in version 8.12.0.10 of package base.\n\n> ```\n(vector-filter pred vec)  →  vector?\n  pred : procedure?\n  vec : vector?\n```\nReturns a fresh vector with the elements of vec for which pred produces a true value. The pred procedure is applied to each element from first to last.\nExample:\n> ```racket\n> > ( vector-filter even? # ( 1 2 3 4 5 6 ) )\n> '#(2 4 6)\n> ```\n> ```\n(vector-filter-not pred vec)  →  vector?\n  pred : procedure?\n  vec : vector?```"} {"text": "# 4.11 Mutable Pairs and Lists\nLike [vector-filter](#%28def._%28%28lib._racket%2Fvector..rkt%29._vector-filter%29%29), but the meaning of the pred predicate is reversed: the result is a vector of all items for which pred returns #f.\nExample:\n> ```racket\n> > ( vector-filter-not even? # ( 1 2 3 4 5 6 ) )\n> '#(1 3 5)\n> ```\n> ```\n(vector-count proc vec ...+) → exact-nonnegative-integer?\n  proc : procedure?\n  vec : vector?\n```\nReturns the number of elements of the vec ... (taken in parallel) on which proc does not evaluate to #f.\n\nExamples:\n\n> ```racket\n> > ( vector-count even? # ( 1 2 3 4 5 ) )\n> 2\n> > ( vector-count = # ( 1 2 3 4 5 ) # ( 5 4 3 2 1 ) )\n> 1\n> ```\n\n> ```\n(vector-argmin proc vec) → any/c\n  proc : ( →  any/c real?)\n  vec : vector?```\n\n\nThis returns the first element in the non-empty vector vec that minimizes the result of proc.\n\nExamples:\n\n> ```racket\n> > ( vector-argmin car # ( ( 3 pears ) ( 1 banana ) ( 2 apples ) ) )\n> '(1 banana)\n> > ( vector-argmin car # ( ( 1 banana ) ( 1 orange ) ) )\n> '(1 banana)\n> ```\n\n> ```\n(vector-argmax proc vec)  →  any/c\n  proc : ( →  any/c real?)\n  vec : vector?\n```\nThis returns the first element in the non-empty vector vec that maximizes the result of proc.\nExamples:\n> ```racket\n> > ( vector-argmax car # ( ( 3 pears ) ( 1 banana ) ( 2 apples ) ) )\n> '(3 pears)\n> > ( vector-argmax car # ( ( 3 pears ) ( 3 oranges ) ) )\n> '(3 pears)\n> ```\n> ```\n(vector-member v vec [is-equal?) → (or/c natural-number/c #f)\n  v : any/c\n  vec : vector?\n  is-equal? : ( →  any/c any/c any/c) = equal?```"} {"text": "# 4.11 Mutable Pairs and Lists\nLocates the first element of vec that is equal to v according to is-equal?. If such an element exists, the index of that element in vec is returned. Otherwise, the result is #f.\nExamples:\n> ```racket\n> > ( vector-member 2 ( vector 1 2 3 4 ) )\n> 1\n> > ( vector-member 9 ( vector 1 2 3 4 ) )\n> #f\n> > ( vector-member 1.0 ( vector 1 2 3 4 ) = )\n> 0\n> ```\nChanged in version 8.15.0.1 of package base: Added the is-equal? argument.\n> ```\n(vector-memv v vec)  →  (or/c natural-number/c #f)\n  v : any/c\n  vec : vector?\n```\nLike vector-member, but finds an element using eqv?.\n\nExamples:\n\n> ```racket\n> > ( vector-memv 2 ( vector 1 2 3 4 ) )\n> 1\n> > ( vector-memv 9 ( vector 1 2 3 4 ) )\n> #f\n> ```\n\n> ```\n(vector-memq v vec)  →  (or/c natural-number/c #f)\n  v : any/c\n  vec : vector?```\n\n\nLike [vector-member](#%28def._%28%28lib._racket%2Fvector..rkt%29._vector-member%29%29), but finds an element using [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29).\n\nExamples:\n\n> ```racket\n> > ( vector-memq 2 ( vector 1 2 3 4 ) )\n> 1\n> > ( vector-memq 9 ( vector 1 2 3 4 ) )\n> #f\n> ```\n\n> ```\n(vector-sort vec\n    less-than?        \n   [ start        \n    end        \n    #:key key        \n    #:cache-keys? cache-keys?)   →   vector?\n\n  vec : vector?\n  less-than? : (any/c any/c . → . any/c)\n  start : exact-nonnegative-integer? = 0\n  end : (or/c #f exact-nonnegative-integer?) = #f\n  key : (or/c #f (any/c . → . any/c)) = #f\n  cache-keys? : boolean? = #f\n```\n(inclusive)\t→\t\n(-> and/c vector? (not/c immutable?))```"} {"text": "# 4.11 Mutable Pairs and Lists\nLike [vector-sort](#%28def._%28%28lib._racket%2Fvector..rkt%29._vector-sort%29%29), but updates indices start (inclusive) through end (exclusive) of vec by sorting them according to the less-than? procedure.\nExamples:\n> ```racket\n> > ( define v1 ( vector 4 3 2 1 ) )\n> > v1\n> '#(4 3 2 1)\n> > ( vector-sort! v1 < )> > v1\n> '#(1 2 3 4)\n> > ( define v2 ( vector 4 3 2 1 ) )\n> > v2\n> '#(4 3 2 1)\n> > ( vector-sort! v2 < 2 #f #:key #f )> > v2\n> '#(4 3 1 2)\n> > ( define v3 ( vector ' ( 4 ) ' ( 3 ) ' ( 2 ) ' ( 1 ) ) )\n> > v3\n> '#((4) (3) (2) (1))\n> > ( vector-sort! v3 < 1 3 #:key car )> > v3\n> '#((4) (2) (3) (1))\n> ```\nAdded in version 6.6.0.5 of package base.\n> ```\n(vector*-copy vec [start end) → vector?\n  vec : (and/c vector? (not/c impersonator?))\n  start : exact-nonnegative-integer? = 0\n  end : exact-nonnegative-integer? = (vector-length v)\n(vector*-append vec ...)  →  vector?\n  vec : (and/c vector? (not/c impersonator?))\n(vector*-set/copy vec pos val)  →  vector?\n  vec : (and/c vector? (not/c impersonator?))\n  pos : exact-nonnegative-integer?\n  val : any/c\n(vector*-extend vec pos [val)  →  vector?\n  vec : (and/c vector? (not/c impersonator?))\n  pos : exact-nonnegative-integer?\n  val : any/c = 0"} {"text": "# 4.11 Mutable Pairs and Lists\n```\nLike vector-copy, vector-append, vector-set/copy, and vector-extend but constrained to work on vectors that are not impersonators.\n\nAdded in version 8.11.1.10 of package base. \nChanged in version 8.12.0.10: Added vector*-extend.\n\n------------------------------------------------------------------------\n\n# 4.13 Stencil Vectors\n\n### 4.13 Stencil Vectors\n\nA stencil vector is like a vector, but it has an associated mask fixnum where the number of bits set in the mask determines the length of the vector. A stencil vector is useful for implementing some data structures \\[Torosyan21\\], such as a hash array mapped trie (HAMT).\n\nConceptually, a stencil vector’s mask indicates which virtual elements of a full-sized stencil vector are present, but mask bits have no effect on access or mutation via stencil-vector-ref and stencil-vector-set!. For example, such a stencil vector has a mask 25, which could also be written #b11001; reading from low bit to high, that mask represents values present at the virtual slots 0, 3, and 4. If that stencil vector’s elements are 'a, 'b, and 'c, then 'a is at virtual slot 0 and accessed with index 0, 'b is at virtual slot 3 and accessed with index 1, and 'c is at virtual slot 4 and accessed with index 2.\n\nThe relative order of bits in a mask is relevant for a functional-update operation with stencil-vector-update. Elements to remove are specified with a removal mask, and elements to add are ordered relative to remaining elements through an addition mask. For example, starting with the stencil vector whose mask is #b11001 with elements 'a, 'b, and 'c, adding new elements 'd and 'e using the addition mask #b100100 produces a stencil vector whose mask is #b111101 and whose elements in order are 'a, 'd, 'b, 'c, and 'e.\n\nThe maximum size of a stencil vector is 58 elements on a 64-bit platform and 26 elements on a 32-bit platform. This limited size enables a compact internal representation and ensures that update operations are relatively simple. Stencil vectors are mutable, although they are intended primarily for use without mutation to implement a persistent data structure.\n\nTwo stencil vectors are equal? if they have the same mask, and if the values in corresponding slots of the stencil vectors are equal?.\n\nA printed vector starts with #\\, and this printed form cannot be parsed by read. The s-exp → fasl and serialize functions do not support stencil vectors, in part because a stencil vector on a 64-bit platform might not be representable on a 32-bit platform. The intent is that stencil vectors are used as an in-memory representation for a datatype implementation.\n\nAdded in version 8.5.0.7 of package base.\n\n> ```\n(stencil-vector? v) → boolean?\n  v : any/c```\n\n\nReturns #t if v is a [stencil vector](#%28tech._stencil._vector%29), #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( stencil-vector #b10010 ' a ' b )\n> #\n> > ( stencil-vector #b111 ' a ' b ' c )\n> #\n> ```\n\nAdded in version 8.5.0.7 of package base.\n\n> ```\n(stencil-vector-mask-width)  →  exact-nonnegative-integer?\n```"} {"text": "# 4.11 Mutable Pairs and Lists\nReturns the maximum number of elements allowed in a stencil vector on the current platform. The result is 58 on a 64-bit platform or 26 on a 32-bit platform.\n> ```\n(stencil-vector mask v ...) → stencil-vector?\n  mask : (integer-in 0 (sub1 (expt 2 (stencil-vector-mask-width))))\n  v : any/c```\nReturns a stencil vector combining mask with elements v. The number of supplied vs must match the number of bits set in mask’s two’s complement representation.\nAdded in version 8.5.0.7 of package base.\n> ```\n(stencil-vector-mask vec)\n  →  (integer-in 0 (sub1 (expt 2 (stencil-vector-mask-width))))\n  vec : stencil-vector?\n```\n\n\nReturns the mask of vec. Note that the mask of a stencil vector is determined at creation time and cannot be changed later.\n\nExample:\n\n> ```racket\n> > ( stencil-vector-mask ( stencil-vector #b10010 ' a ' b ) )\n> 18\n> ```\n\nAdded in version 8.5.0.7 of package base.\n\n> ```\n(stencil-vector-length vec)\n  →  (integer-in 0 (sub1 (stencil-vector-mask-width)))\n  vec : stencil-vector?\n```\nReturns the length of vec (i.e., the number of slots in the vector). The result is the same as ([fxpopcount](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxpopcount%29%29) ([stencil-vector-mask](#%28def._%28%28quote._~23~25kernel%29._stencil-vector-mask%29%29) vec)).\nExample:\n> ```racket\n> > ( stencil-vector-length ( stencil-vector #b10010 ' a ' b ) )\n> 2\n> ```\nAdded in version 8.5.0.7 of package base.\n> ```\n(stencil-vector-ref vec pos)  →  any/c\n  vec : stencil-vector?\n  pos : exact-nonnegative-integer?"} {"text": "# 4.11 Mutable Pairs and Lists\n```\n(parameter)\t→```\n\n\nUpdates the slot pos of vec to contain v.\n\nExamples:\n\n> ```racket\n> > ( define st-vec ( stencil-vector #b101 ' a ' b ) )\n> > st-vec\n> #\n> > ( stencil-vector-set! st-vec 1 ' c )\n> > st-vec\n> #\n> ```\n\nAdded in version 8.5.0.7 of package base.\n\n> ```\n(stencil-vector-update vec\n    remove-mask        \n    add-mask        \n    v ...)   →   stencil-vector?\n\n  vec : stencil-vector?\n  remove-mask : (integer-in 0 (sub1 (expt 2 (stencil-vector-mask-width))))\n  add-mask : (integer-in 0 (sub1 (expt 2 (stencil-vector-mask-width))))\n  v : any/c\n```\nReturns a stencil vector that is like vec, but with elements corresponding to remove-mask removed, and with the given vs added at positions relative to existing (unremoved) elements determined by add-mask.\nExamples:\n> ```racket\n> > ( define st-vec ( stencil-vector #b101 ' a ' b ) )\n> > ( stencil-vector-update st-vec #b0 #b10 ' c )\n> #\n> > ( stencil-vector-update st-vec #b0 #b1000 ' c )\n> #\n> > st-vec ; unchanged by updates\n> #\n> > ( stencil-vector-update st-vec #b1 #b1 ' c )\n> #\n> > ( stencil-vector-update st-vec #b100 #b100 ' c )\n> #\n> > ( stencil-vector-update st-vec #b100 #b0 )\n> #\n> ```\nAdded in version 8.5.0.7 of package base.\n------------------------------------------------------------------------"} {"text": "# 4.14 Boxes"} {"text": "### 4.14 Boxes\n> > > \"+\"Boxes in The Racket Guide introduces boxes.\nA box is like a single-element vector, normally used as minimal mutable storage.\nA box can be mutable or immutable. When an immutable box is provided to a procedure like set-box!, the exn:fail:contract exception is raised. Box constants generated by the default reader (see Reading Strings) are immutable. Use immutable? to check whether a box is immutable.\nA literal or printed box starts with #&. See Reading Boxes for information on reading boxes and Printing Boxes for information on printing boxes.\n> ```\n(box? v) → boolean?\n  v : any/c```\nReturns #t if v is a box, #f otherwise.\nSee also [immutable-box?](booleans.html#%28def._%28%28lib._racket%2Fmutability..rkt%29._immutable-box~3f%29%29) and [mutable-box?](booleans.html#%28def._%28%28lib._racket%2Fmutability..rkt%29._mutable-box~3f%29%29).\n> ```\n(box v)  →  box?\n  v : any/c\n```\n\n\nReturns a new mutable box that contains v.\n\n> ```\n(box-immutable v)  →  (and/c box? immutable?)\n  v : any/c\n```\nReturns a new immutable box that contains v.\n> ```\n(unbox box)  →  any/c\n  box : box?\n```\n(parameter)\t→\t\n(-> and/c box? (not/c immutable?))```\n\n\nSets the content of box to v.\n\n> ```\n(parameter)\t→\t\n(-> and box? (not/c impersonator?))\n```\nLike unbox and set-box!, but constrained to work on boxes that are not impersonators.\nAdded in version 6.90.0.15 of package base.\n> ```\n(box-cas! box old new)  →  boolean?\n  box : (and/c box? (not/c immutable?) (not/c impersonator?))\n  old : any/c\n  new : any/c```"} {"text": "# 4.14 Boxes\nAtomically updates the contents of box to new, provided that box currently contains a value that is [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to old, and returns #t in that case. If box does not contain old, then the result is #f.\nIf no other [threads](eval-model.html#%28tech._thread%29) or [futures](futures.html#%28tech._future%29) attempt to access box, the operation is equivalent to\n> ([and](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29) ([eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) old ([unbox](#%28def._%28%28quote._~23~25kernel%29._unbox%29%29) box)) ([set-box!](#%28def._%28%28quote._~23~25kernel%29._set-box%21%29%29) box new) #t)\nexcept that [box-cas!](#%28def._%28%28quote._~23~25kernel%29._box-cas%21%29%29) can spuriously fail on some platforms. That is, with low probability, the result can be #f with the value in box left unchanged, even if box contains old.\nWhen Racket is compiled with support for [futures](futures.html#%28tech._future%29), [box-cas!](#%28def._%28%28quote._~23~25kernel%29._box-cas%21%29%29) is guaranteed to use a hardware compare and set operation. Uses of [box-cas!](#%28def._%28%28quote._~23~25kernel%29._box-cas%21%29%29) can be performed safely in a [future](futures.html#%28tech._future%29) (i.e., allowing the future thunk to continue in parallel). See also [Machine Memory Order](memory-order.html).\n------------------------------------------------------------------------"} {"text": "# 4.15 Hash Tables"} {"text": "### 4.15 Hash Tables\n> > > \"+\"[Hash Tables](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=hash-tables.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces hash tables.\nA hash table (or simply hash) maps each of its keys to a single value. For a given hash table, keys are equivalent via [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29), and keys are retained either strongly, weakly (see [Weak Boxes](weakbox.html)), or like [ephemerons](ephemerons.html#%28tech._ephemeron%29). A hash table is also either mutable or immutable. Immutable hash tables support effectively constant-time access and update, just like mutable hash tables; the constant on immutable operations is usually larger, but the functional nature of immutable hash tables can pay off in certain algorithms. Use [immutable?](booleans.html#%28def._%28%28quote._~23~25kernel%29._immutable~3f%29%29) to check whether a hash table is immutable."} {"text": "# 4.15 Hash Tables\n> > > Immutable hash tables actually provide O(log N) access and update. Since N is limited by the address space so that log N is limited to less than 30 or 62 (depending on the platform), log N can be treated reasonably as a constant.\nFor [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29)-based hashing, the built-in hash functions on [strings](strings.html#%28tech._string%29), [pairs](pairs.html#%28tech._pair%29), [lists](pairs.html#%28tech._list%29), [vectors](vectors.html#%28tech._vector%29), [prefab](structures.html#%28tech._prefab%29) or transparent [structures](structures.html#%28tech._structure%29), etc., take time proportional to the size of the value. The hash code for a compound data structure, such as a list or vector, depends on hashing each item of the container, but the depth of such recursive hashing is limited (to avoid potential problems with cyclic data). For a non-[list](pairs.html#%28tech._list%29) [pair](pairs.html#%28tech._pair%29), both [car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) and [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) hashing is treated as a deeper hash, but the [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) of a [list](pairs.html#%28tech._list%29) is treated as having the same hashing depth as the list."} {"text": "# 4.15 Hash Tables\nA hash table can be used as a two-valued [sequence](sequences.html#%28tech._sequence%29) (see [Sequences](sequences.html)). The keys and values of the hash table serve as elements of the sequence (i.e., each element is a key and its associated value). If a mapping is added to or removed from a mutable hash table during iteration, then an iteration step may fail with [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29), or the iteration may skip or duplicate keys and values. See also [in-hash](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash%29%29), [in-hash-keys](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash-keys%29%29), [in-hash-values](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash-values%29%29), and [in-hash-pairs](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash-pairs%29%29)."} {"text": "# 4.15 Hash Tables\nTwo hash tables cannot be [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) unless they have the same mutability, use the same key-comparison procedure ([equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)), both hold keys strongly, weakly, or like [ephemerons](ephemerons.html#%28tech._ephemeron%29). Empty immutable hash tables are [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) when they are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29).\nChanged in version 7.2.0.9 of package base: Made empty immutable hash tables [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) when they are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29).\nCaveats concerning concurrent modification: A mutable hash table can be manipulated with [hash-ref](#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29), [hash-set!](#%28def._%28%28quote._~23~25kernel%29._hash-set%21%29%29), and [hash-remove!](#%28def._%28%28quote._~23~25kernel%29._hash-remove%21%29%29) concurrently by multiple threads, and the operations are protected by a table-specific semaphore as needed. Several caveats apply, however:"} {"text": "# 4.15 Hash Tables\n- If a thread is terminated while applying [hash-ref](#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29), [hash-ref-key](#%28def._%28%28quote._~23~25kernel%29._hash-ref-key%29%29), [hash-set!](#%28def._%28%28quote._~23~25kernel%29._hash-set%21%29%29), [hash-remove!](#%28def._%28%28quote._~23~25kernel%29._hash-remove%21%29%29), [hash-ref!](#%28def._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._hash-ref%21%29%29), [hash-update!](#%28def._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._hash-update%21%29%29), or [hash-clear!](#%28def._%28%28quote._~23~25kernel%29._hash-clear%21%29%29) to a hash table that uses [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), or [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29) key comparisons, all current and future operations on the hash table may block indefinitely.\n- The [hash-map](#%28def._%28%28quote._~23~25kernel%29._hash-map%29%29), [hash-for-each](#%28def._%28%28quote._~23~25kernel%29._hash-for-each%29%29), and [hash-clear!](#%28def._%28%28quote._~23~25kernel%29._hash-clear%21%29%29) procedures do not use the table’s semaphore to guard the traversal as a whole (if a traversal is needed, in the case of [hash-clear!](#%28def._%28%28quote._~23~25kernel%29._hash-clear%21%29%29)). Changes by one thread to a hash table can affect the keys and values seen by another thread part-way through its traversal of the same hash table."} {"text": "# 4.15 Hash Tables\n- The [hash-update!](#%28def._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._hash-update%21%29%29) and [hash-ref!](#%28def._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._hash-ref%21%29%29) functions use a table’s semaphore independently for the [hash-ref](#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29) and [hash-set!](#%28def._%28%28quote._~23~25kernel%29._hash-set%21%29%29) parts of their functionality, which means that the update as a whole is not “atomic.”\n- Adding a mutable hash table as a key in itself is trouble on the grounds that the key is being mutated (see the caveat below), but it is also a kind of concurrent use of the hash table: computing a hash table’s hash code may require waiting on the table’s semaphore, but the semaphore is already held for modifying the hash table, so the hash-table addition can block indefinitely.\nCaveat concerning mutable keys: If a key in an [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29)-based hash table is mutated (e.g., a key string is modified with [string-set!](strings.html#%28def._%28%28quote._~23~25kernel%29._string-set%21%29%29)), then the hash table’s behavior for insertion and lookup operations becomes unpredictable."} {"text": "# 4.15 Hash Tables\nA literal or printed hash table starts with #hash, #hashalw, #hasheqv, or #hasheq. See [Reading Hash Tables](reader.html#%28part._parse-hashtable%29) for information on [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29)ing hash tables and [Printing Hash Tables](printing.html#%28part._print-hashtable%29) for information on [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29)ing hash tables.\n> ```\n(hash? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a hash table, #f otherwise.\n\nSee also immutable-hash? and mutable-hash?.\n\n> ```\n(hash-equal? ht)  →  boolean?\n  ht : hash?```\n\n\nReturns #t if ht compares keys with [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), #f if it compares with [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29).\n\n> ```\n(hash-equal-always? ht)  →  boolean?\n  ht : hash?\n```\nReturns #t if ht compares keys with equal-always?, #f if it compares with eq?, eqv?, or equal?.\nAdded in version 8.5.0.3 of package base.\n> ```\n(hash-eqv? ht)  →  boolean?\n  ht : hash?```"} {"text": "# 4.15 Hash Tables\nReturns #t if ht compares keys with [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), #f if it compares with [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29).\n> ```\n(hash-eq? ht)  →  boolean?\n  ht : hash?\n```\nReturns #t if ht compares keys with eq?, #f if it compares with equal?, equal-always?, or eqv?.\n\n> ```\n(hash-strong? ht)  →  boolean?\n  ht : hash?```\n\n\nReturns #t if ht retains its keys strongly, #f if it retains keys weakly or like [ephemerons](ephemerons.html#%28tech._ephemeron%29).\n\nAdded in version 8.0.0.10 of package base.\n\n> ```\n(hash-weak? ht)  →  boolean?\n  ht : hash?\n```\nReturns #t if ht retains its keys weakly, #f if it retains keys strongly or like ephemerons.\n> ```\n(hash-ephemeron? ht)  →  boolean?\n  ht : hash?```\nReturns #t if ht retains its keys like [ephemerons](ephemerons.html#%28tech._ephemeron%29), #f if it retains keys strongly or merely weakly.\nAdded in version 8.0.0.10 of package base.\n> ```\n(hash key val ... ...)\n  →  (and/c hash? hash-equal? immutable? hash-strong?)\n  key : any/c\n  val : any/c\n(hashalw key val ... ...)\n  →  (and/c hash? hash-equal-always? immutable? hash-strong?)\n  key : any/c\n  val : any/c\n(hasheq key val ... ...)\n  →  (and/c hash? hash-eq? immutable? hash-strong?)\n  key : any/c\n  val : any/c"} {"text": "# 4.15 Hash Tables\n(hasheqv key val ... ...)\n  →  (and/c hash? hash-eqv? immutable? hash-strong?)\n  key : any/c\n  val : any/c\n```\nCreates an immutable hash table with each given key mapped to the following val; each key must have a val, so the total number of arguments to hash must be even.\n\nThe hash procedure creates a table where keys are compared with equal?, hashalw creates a table where keys are compared with equal-always?, hasheq procedure creates a table where keys are compared with eq?, hasheqv procedure creates a table where keys are compared with eqv?.\n\nThe key to val mappings are added to the table in the order that they appear in the argument list, so later mappings can hide earlier mappings if the keys are equal.\n\nChanged in version 8.5.0.3 of package base: Added hashalw.\n\n> ```\n(make-hash [assocs)\n  →  (and/c hash? hash-equal? (not/c immutable?) hash-strong?)\n  assocs : (listof pair?) = null\n\n(make-hashalw [assocs)\n  →  (and/c hash? hash-equal-always? (not/c immutable?) hash-strong?)\n  assocs : (listof pair?) = null\n\n(make-hasheqv [assocs)\n  →  (and/c hash? hash-eqv? (not/c immutable?) hash-strong?)\n  assocs : (listof pair?) = null\n\n(make-hasheq [assocs)\n  →  (and/c hash? hash-eq? (not/c immutable?) hash-strong?)\n  assocs : (listof pair?) = null```\n\n\nCreates a mutable hash table that holds keys strongly.\n\nThe [make-hash](#%28def._%28%28quote._~23~25kernel%29._make-hash%29%29) procedure creates a table where keys are compared with [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [make-hasheq](#%28def._%28%28quote._~23~25kernel%29._make-hasheq%29%29) procedure creates a table where keys are compared with [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29), [make-hasheqv](#%28def._%28%28quote._~23~25kernel%29._make-hasheqv%29%29) procedure creates a table where keys are compared with [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), and [make-hashalw](#%28def._%28%28quote._~23~25kernel%29._make-hashalw%29%29) creates a table where keys are compared with [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29).\n\nThe table is initialized with the content of assocs. In each element of assocs, the [car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) is a key, and the [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) is the corresponding value. The mappings are added to the table in the order that they appear in assocs, so later mappings can hide earlier mappings.\n\nSee also [make-custom-hash](dicts.html#%28def._%28%28lib._racket%2Fdict..rkt%29._make-custom-hash%29%29).\n\nExamples:\n\n> ```racket\n> > ( make-hash )\n> '#hash()\n> > ( make-hash ' ( [ 0 . 1 ] [ 42 . \"meaning of life\" ] [ 2 . 3 ] ) )\n> '#hash((0 . 1) (2 . 3) (42 . \"meaning of life\"))\n> > ( make-hash ' ( [ 0 . 1 ] [ 1 . 2 ] [ 0 . 3 ] ) )\n> '#hash((0 . 3) (1 . 2))\n> > ( make-hash ( list ( cons 0 1 ) ( cons ' apple ' orange ) ( cons #t #f ) ) )\n> '#hash((#t . #f) (0 . 1) (apple . orange))\n> > ( make-hash ' ( ( 0 1 ) ( 1 2 ) ( 2 3 ) ) )\n> '#hash((0 . (1)) (1 . (2)) (2 . (3)))\n> > ( make-hash ( list ( cons + - ) ) )\n> '#hash((# . #))\n> ```\n\nChanged in version 8.5.0.3 of package base: Added [make-hashalw](#%28def._%28%28quote._~23~25kernel%29._make-hashalw%29%29).\n\n> ```\n(make-weak-hash [assocs)\n  →  (and/c hash? hash-equal? (not/c immutable?) hash-weak?)\n  assocs : (listof pair?) = null\n\n(make-weak-hashalw [assocs)\n  →  (and/c hash? hash-equal-always? (not/c immutable?) hash-weak?)\n  assocs : (listof pair?) = null\n\n(make-weak-hasheqv [assocs)\n  →  (and/c hash? hash-eqv? (not/c immutable?) hash-weak?)\n  assocs : (listof pair?) = null\n\n(make-weak-hasheq [assocs)\n  →  (and/c hash? hash-eq? (not/c immutable?) hash-weak?)\n  assocs : (listof pair?) = null\n```"} {"text": "# 4.15 Hash Tables\nLike make-hash, make-hasheq, make-hasheqv, and make-hashalw, but creates a mutable hash table that holds keys weakly.\nBeware that values in a weak hash table are retained normally. If a value in the table refers back to its key, then the table will retain the value and therefore the key; the mapping will never be removed from the table even if the key becomes otherwise inaccessible. To avoid that problem, use an ephemeron hash table as created by make-ephemeron-hash, make-ephemeron-hashalw, make-ephemeron-hasheqv, or make-ephemeron-hasheq. For values that do not refer to keys, there is a modest extra cost to using an ephemeron hash table instead of a weak hash table, but prefer an ephemeron hash table when in doubt.\nChanged in version 8.5.0.3 of package base: Added make-weak-hashalw.\n> ```\n(make-ephemeron-hash [assocs)\n  →  (and/c hash? hash-equal? (not/c immutable?) hash-ephemeron?)\n  assocs : (listof pair?) = null\n(make-ephemeron-hashalw [assocs)\n  →  (and/c hash? hash-equal-always? (not/c immutable?) hash-ephemeron?)\n  assocs : (listof pair?) = null\n(make-ephemeron-hasheqv [assocs)\n  →  (and/c hash? hash-eqv? (not/c immutable?) hash-ephemeron?)\n  assocs : (listof pair?) = null\n(make-ephemeron-hasheq [assocs)\n  →  (and/c hash? hash-eq? (not/c immutable?) hash-ephemeron?)\n  assocs : (listof pair?) = null```"} {"text": "# 4.15 Hash Tables\nLike [make-hash](#%28def._%28%28quote._~23~25kernel%29._make-hash%29%29), [make-hasheq](#%28def._%28%28quote._~23~25kernel%29._make-hasheq%29%29), [make-hasheqv](#%28def._%28%28quote._~23~25kernel%29._make-hasheqv%29%29), and [make-hashalw](#%28def._%28%28quote._~23~25kernel%29._make-hashalw%29%29), but creates a mutable hash table that holds key-value combinations in the same way as an [ephemeron](ephemerons.html#%28tech._ephemeron%29).\nUsing an ephemeron hash table is like using a weak hash table and mapping each key to a [ephemeron](ephemerons.html#%28tech._ephemeron%29) that pairs the key and value. An advantage of an ephemeron hash table is that the value need not be extracted with [ephemeron-value](ephemerons.html#%28def._%28%28quote._~23~25kernel%29._ephemeron-value%29%29) from the result of functions like [hash-ref](#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29). An ephemeron hash table might also be represented more compactly than a weak hash table with explicit [ephemeron](ephemerons.html#%28tech._ephemeron%29) values.\nAdded in version 8.0.0.10 of package base. \nChanged in version 8.5.0.3: Added [make-ephemeron-hashalw](#%28def._%28%28quote._~23~25kernel%29._make-ephemeron-hashalw%29%29).\n> ```\n(make-immutable-hash [assocs)\n  →  (and/c hash? hash-equal? immutable? hash-strong?)\n  assocs : (listof pair?) = null\n(make-immutable-hashalw [assocs)\n  →  (and/c hash? hash-equal-always? immutable? hash-strong?)\n  assocs : (listof pair?) = null"} {"text": "# 4.15 Hash Tables\n(make-immutable-hasheqv [assocs)\n  →  (and/c hash? hash-eqv? immutable? hash-strong?)\n  assocs : (listof pair?) = null\n(make-immutable-hasheq [assocs)\n  →  (and/c hash? hash-eq? immutable? hash-strong?)\n  assocs : (listof pair?) = null\n```\n(parameter)\t→\t\n(-> and/c hash? (not/c immutable?))```\n\n\nMaps key to v in ht, overwriting any existing mapping for key.\n\nSee also the [caveats concerning concurrent modification](#%28elem._%28caveat._concurrency%29%29) and the [caveat concerning mutable keys](#%28elem._%28caveat._mutable-keys%29%29) above.\n\n> ```\n(parameter)\t→\t\n(-> and/c hash? (not/c immutable?))\n```\nMaps each key to each v in ht, overwriting any existing mapping for each key. Mappings are added from the left, so later mappings overwrite earlier mappings.\nSee also the caveats concerning concurrent modification and the caveat concerning mutable keys above.\n> ```\n(hash-set ht key v)  →  (and/c hash? immutable?)\n  ht : (and/c hash? immutable?)\n  key : any/c\n  v : any/c```\nFunctionally extends ht by mapping key to v, overwriting any existing mapping for key, and returning the extended hash table.\nSee also the [caveat concerning mutable keys](#%28elem._%28caveat._mutable-keys%29%29) above.\n> ```\n(hash-set* ht key v ... ...) → (and/c hash? immutable?)\n  ht : (and/c hash? immutable?)\n  key : any/c\n  v : any/c"} {"text": "# 4.15 Hash Tables\n```\nFunctionally extends ht by mapping each key to v, overwriting any existing mapping for each key, and returning the extended hash table. Mappings are added from the left, so later mappings overwrite earlier mappings.\n\nSee also the caveat concerning mutable keys above.\n\n> ```\n(hash-ref ht key [failure-result) → any\n  ht : hash?\n  key : any/c\n   failure-result   :   failure-result/c\n      =   ( lambda ( )\n> ( raise ( make-exn:fail:contract .... ) ) )```\n\n\nReturns the value for key in ht. If no value is found for key, then failure-result determines the result:\n\n- If failure-result is a procedure, it is called (through a tail call) with no arguments to produce the result.\n\n- Otherwise, failure-result is returned as the result.\n\nExamples:\n\n> ```racket\n> > ( hash-ref ( hash ) \"hi\" )\n> hash-ref: no value found for key\n> key: \"hi\"\n> > ( hash-ref ( hash ) \"hi\" 5 )\n> 5\n> > ( hash-ref ( hash ) \"hi\" ( lambda ( ) \"flab\" ) )\n> \"flab\"\n> > ( hash-ref ( hash \"hi\" \"bye\" ) \"hi\" )\n> \"bye\"\n> > ( hash-ref ( hash \"hi\" \"bye\" ) \"no\" )\n> hash-ref: no value found for key\n> key: \"no\"\n> ```\n\nSee also the [caveats concerning concurrent modification](#%28elem._%28caveat._concurrency%29%29) and the [caveat concerning mutable keys](#%28elem._%28caveat._mutable-keys%29%29) above.\n\n> ```\n(hash-ref-key ht key [failure-result) → any\n  ht : hash?\n  key : any/c\n   failure-result   :   failure-result/c\n      =   ( lambda ( )\n> ( raise ( make-exn:fail:contract .... ) ) )\n```"} {"text": "# 4.15 Hash Tables\nReturns the key held by ht that is equivalent to key according to ht’s key-comparison function. If no key is found, then failure-result is used as in hash-ref to determine the result.\nIf ht is not an impersonator, then the returned key, assuming it is found, will be eq?-equivalent to the one actually retained by ht:\nExamples:\n> ```racket\n> > ( define original-key \"hello\" )\n> > ( define key-copy ( string-copy original-key ) )\n> > ( equal? original-key key-copy )\n> #t\n> > ( eq? original-key key-copy )\n> #f\n> > ( define table ( make-hash ) )\n> > ( hash-set! table original-key ' value )\n> > ( eq? ( hash-ref-key table \"hello\" ) original-key )\n> #t\n> > ( eq? ( hash-ref-key table \"hello\" ) key-copy )\n> #f\n> ```\nIf a mutable hash is updated multiple times using keys that are not eq?-equivalent but are equivalent according to the hash’s key-comparison procedure, the hash retains the first one:\nExamples:\n> ```racket\n> > ( define original-key \"hello\" )\n> > ( define key-copy ( string-copy original-key ) )\n> > ( define table ( make-hash ) )\n> > ( hash-set! table original-key ' one )\n> > ( hash-set! table key-copy ' two )\n> > ( eq? ( hash-ref-key table \"hello\" ) original-key )\n> #t\n> > ( eq? ( hash-ref-key table \"hello\" ) key-copy )\n> #f\n> ```\nConversely, an immutable hash retains the key that was most-recently used to update it:\nExamples:"} {"text": "# 4.15 Hash Tables\n> ```racket\n> > ( define original-key \"hello\" )\n> > ( define key-copy ( string-copy original-key ) )\n> > ( define table0 ( hash ) )\n> > ( define table1 ( hash-set table0 original-key ' one ) )\n> > ( define table2 ( hash-set table1 key-copy ' two ) )\n> > ( eq? ( hash-ref-key table2 \"hello\" ) original-key )\n> #f\n> > ( eq? ( hash-ref-key table2 \"hello\" ) key-copy )\n> #t\n> ```\nIf ht is an impersonator, then the returned key will be determined as described in the documentation to impersonate-hash.\nSee also the caveats concerning concurrent modification and the caveat concerning mutable keys above.\nAdded in version 7.4.0.3 of package base.\n> ```\n(hash-ref! ht key to-set)  →  any\n  ht : hash?\n  key : any/c\n  to-set : failure-result/c```\nReturns the value for key in ht. If no value is found for key, then to-set determines the result as in [hash-ref](#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29) (i.e., it is either a thunk that computes a value or a plain value), and this result is stored in ht for the key. (Note that if to-set is a thunk, it is not invoked in tail position.)\nSee also the [caveats concerning concurrent modification](#%28elem._%28caveat._concurrency%29%29) and the [caveat concerning mutable keys](#%28elem._%28caveat._mutable-keys%29%29) above.\n> ```\n(hash-has-key? ht key)  →  boolean?\n  ht : hash?\n  key : any/c"} {"text": "# 4.15 Hash Tables\n```\n(parameter)\t→\t\n(-> and/c hash? (not/c immutable?))```\n\n\nUpdates the value mapped by key in ht by applying updater to the value. The value returned by updater becomes the new mapping for key, overwriting the original value in ht.\n\nExamples:\n\n> ```racket\n> ( define h ( make-hash ) ) ( hash-set! h ' a 5 )\n> > ( hash-update! h ' a add1 )\n> > h\n> '#hash((a . 6))\n> ```\n\nThe optional failure-result argument is used when no mapping exists for key already, in the same manner as in [hash-ref](#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29).\n\nExamples:\n\n> ```racket\n> ( define h ( make-hash ) )\n> > ( hash-update! h ' b add1 )\n> hash-update!: no value found for key: 'b\n> > ( hash-update! h ' b add1 0 )\n> > h\n> '#hash((b . 1))\n> ```\n\nSee also the [caveats concerning concurrent modification](#%28elem._%28caveat._concurrency%29%29) and the [caveat concerning mutable keys](#%28elem._%28caveat._mutable-keys%29%29) above.\n\n> ```\n(hash-update ht key updater [failure-result)\n  →  (and/c hash? immutable?)\n  ht : (and/c hash? immutable?)\n  key : any/c\n  updater : (any/c . → . any/c)\n   failure-result   :   failure-result/c\n      =   ( lambda ( )\n> ( raise ( make-exn:fail:contract .... ) ) )\n```\n(parameter)\t→\t\n(-> and/c hash? (not/c immutable?))```\nRemoves any existing mapping for key in ht.\nSee also the [caveats concerning concurrent modification](#%28elem._%28caveat._concurrency%29%29) and the [caveat concerning mutable keys](#%28elem._%28caveat._mutable-keys%29%29) above.\n> ```"} {"text": "# 4.15 Hash Tables\n(hash-remove ht key)  →  (and/c hash? immutable?)\n  ht : (and/c hash? immutable?)\n  key : any/c\n```\n(parameter)\t→\t\n(-> and/c hash? (not/c immutable?))```\n\n\nRemoves all mappings from ht.\n\nIf ht is not an [impersonator](chaperones.html#%28tech._impersonator%29), then all mappings are removed in constant time. If ht is an [impersonator](chaperones.html#%28tech._impersonator%29), then each key is removed one-by-one using [hash-remove!](#%28def._%28%28quote._~23~25kernel%29._hash-remove%21%29%29).\n\nSee also the [caveats concerning concurrent modification](#%28elem._%28caveat._concurrency%29%29) and the [caveat concerning mutable keys](#%28elem._%28caveat._mutable-keys%29%29) above.\n\n> ```\n(hash-clear ht)  →  (and/c hash? immutable?)\n  ht : (and/c hash? immutable?)\n```\nFunctionally removes all mappings from ht.\nIf ht is not a chaperone, then clearing is equivalent to creating a new hash table, and the operation is performed in constant time. If ht is a chaperone, then each key is removed one-by-one using hash-remove.\n> ```\n(hash-copy-clear ht [#:kind kind) → hash?\n  ht : hash?\n  kind : (or/c #f 'immutable 'mutable 'weak 'ephemeron) = #f```\nProduces an empty [hash table](#%28tech._hash._table%29) with the same key-comparison procedure as ht, with either the given kind or the same kind as the given ht."} {"text": "# 4.15 Hash Tables\nIf kind is not supplied or #f, produces a hash table of the same kind and mutability as the given ht. If kind is 'immutable, 'mutable, 'weak, or 'ephemeron, produces a table that’s immutable, mutable with strongly-held keys, mutable with weakly-held keys, or mutable with ephemeron-held keys respectively.\nChanged in version 8.5.0.2 of package base: Added the kind argument.\n> ```\n(hash-map ht proc [try-order?) → (listof any/c)\n  ht : hash?\n  proc : (any/c any/c . → . any/c)\n  try-order? : any/c = #f\n```\nApplies the procedure proc to each element in ht in an unspecified order, accumulating the results into a list. The procedure proc is called each time with a key and its value, and the procedure’s individual results appear in order in the result list.\n\nIf a hash table is extended with new keys (either through proc or by another thread) while a hash-map or hash-for-each traversal is in process, arbitrary key–value pairs can be dropped or duplicated in the traversal. Key mappings can be deleted or remapped (by any thread) with no adverse affects; the change does not affect a traversal if the key has been seen already, otherwise the traversal skips a deleted key or uses the remapped key’s new value.\n\nSee also the caveats concerning concurrent modification above.\n\nIf try-order? is true, then the order of keys and values passed to proc is normalized under certain circumstances—including when every key is one of the following and with the following order (earlier bullets before later):\n\n- booleans sorted #f before #t;\n\n- characters sorted by char; and\n\n- eof.\n\nChanged in version 6.3 of package base: Added the try-order? argument. \nChanged in version 7.1.0.7: Added guarantees for try-order?.\n\nExamples:\n\n> ```racket\n> > ( hash-map ( make-hash ' ( [ 0 . 1 ] [ 1 . 2 ] [ 2 . 3 ] ) ) ( λ ( k v ) k ) )\n> '(0 1 2)\n> > ( hash-map ( make-hash ' ( [ 0 . 1 ] [ 1 . 2 ] [ 2 . 3 ] ) ) ( λ ( k v ) v ) )\n> '(1 2 3)\n> ```\n\n> ```\n(hash-map/copy ht proc [#:kind kind) → hash?\n  ht : hash?\n  proc : (any/c any/c . → . (values any/c any/c))\n  kind : (or/c #f 'immutable 'mutable 'weak 'ephemeron) = #f```\n\n\nApplies the procedure proc to each element in ht in an unspecified order, accumulating the results into a new hash with the same key-comparison procedure as ht, with either the given kind or the same kind as the given ht.\n\nIf kind is not supplied or #f, produces a hash table of the same kind and mutability as the given ht. If kind is 'immutable, 'mutable, 'weak, or 'ephemeron, produces a table that’s immutable, mutable with strongly-held keys, mutable with weakly-held keys, or mutable with ephemeron-held keys respectively.\n\nExamples:\n\n> ```racket\n> > ( hash-map/copy #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) ( lambda ( k v ) ( values k ( string-upcase v ) ) ) )\n> '#hash((a . \"APPLE\") (b . \"BANANA\"))\n> > ( define frozen-capital ( hash-map/copy ( make-hash ' ( ( a . \"apple\" ) ( b . \"banana\" ) ) ) ( lambda ( k v ) ( values k ( string-upcase v ) ) ) #:kind ' immutable ) )\n> > frozen-capital\n> '#hash((a . \"APPLE\") (b . \"BANANA\"))\n> > ( immutable? frozen-capital )\n> #t\n> ```\n\nAdded in version 8.5.0.2 of package base.\n\n> ```\n(hash-keys ht [try-order?) → (listof any/c)\n  ht : hash?\n  try-order? : any/c = #f\n```"} {"text": "# 4.15 Hash Tables\nReturns a list of the keys of ht in an unspecified order.\nIf try-order? is true, then the order of keys is normalized under certain circumstances. See hash-map for further explanations on try-order? and on information about modifying ht during hash-keys.\nSee also the caveats concerning concurrent modification above.\nChanged in version 8.3.0.11 of package base: Added the try-order? argument.\n> ```\n(hash-values ht [try-order?) → (listof any/c)\n  ht : hash?\n  try-order? : any/c = #f```\nReturns a list of the values of ht in an unspecified order.\nIf try-order? is true, then the order of values is normalized under certain circumstances, based on the ordering of the associated keys. See [hash-map](#%28def._%28%28quote._~23~25kernel%29._hash-map%29%29) for further explanations on try-order? and on information about modifying ht during [hash-values](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._hash-values%29%29).\nSee also the [caveats concerning concurrent modification](#%28elem._%28caveat._concurrency%29%29) above.\nChanged in version 8.3.0.11 of package base: Added the try-order? argument.\n> ```\n(hash → list ht [try-order?) → (listof (cons/c any/c any/c))\n  ht : hash?\n  try-order? : any/c = #f"} {"text": "# 4.15 Hash Tables\n```\nReturns a list of the key–value pairs of ht in an unspecified order.\n\nIf try-order? is true, then the order of keys and values is normalized under certain circumstances. See hash-map for further explanations on try-order? and on information about modifying ht during hash → list.\n\nSee also the caveats concerning concurrent modification above.\n\nChanged in version 8.3.0.11 of package base: Added the try-order? argument.\n\n> ```\n(hash-keys-subset? ht1 ht2)  →  boolean?\n  ht1 : hash?\n  ht2 : hash?```\n\n\nReturns #t if the keys of ht1 are a subset of or the same as the keys of ht2. The hash tables must both use the same key-comparison function ([equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nUsing [hash-keys-subset?](#%28def._%28%28quote._~23~25kernel%29._hash-keys-subset~3f%29%29) on immutable hash tables can be much faster than iterating through the keys of ht1 to make sure that each is in ht2.\n\nAdded in version 6.5.0.8 of package base.\n\n> ```\n(parameter)\t→\t\n(-> any/c any/c . → . any)\n```\nApplies proc to each element in ht (for the side-effects of proc) in an unspecified order. The procedure proc is called each time with a key and its value."} {"text": "# 4.15 Hash Tables\nSee hash-map for information about try-order? and about modifying ht within proc.\nSee also the caveats concerning concurrent modification above.\nChanged in version 6.3 of package base: Added the try-order? argument. \nChanged in version 7.1.0.7: Added guarantees for try-order?.\n> ```\n(hash-count ht)  →  exact-nonnegative-integer?\n  ht : hash?```\nReturns the number of keys mapped by ht.\nFor the [CS](implementations.html#%28tech._c%29) implementation of Racket, the result is always computed in constant time and atomically. For the [BC](implementations.html#%28tech._bc%29) implementation of Racket, the result is computed in constant time and atomically only if ht does not retain keys weakly or like an [ephemeron](ephemerons.html#%28tech._ephemeron%29), otherwise, a traversal is required to count the keys.\n> ```\n(hash-empty? ht)  →  boolean?\n  ht : hash?"} {"text": "# 4.15 Hash Tables\n```\nEquivalent to (zero? (hash-count ht)).\n\n> ```\n(hash-iterate-first ht)  →  (or/c #f exact-nonnegative-integer?)\n  ht : hash?```\n\n\nReturns #f if ht contains no elements, otherwise it returns an integer that is an index to the first element in the hash table; “first” refers to an unspecified ordering of the table elements, and the index values are not necessarily consecutive integers.\n\nFor a mutable ht, this index is guaranteed to refer to the first item only as long as no items are added to or removed from ht. More generally, an index is guaranteed to be a valid hash index for a given hash table only as long it comes from [hash-iterate-first](#%28def._%28%28quote._~23~25kernel%29._hash-iterate-first%29%29) or [hash-iterate-next](#%28def._%28%28quote._~23~25kernel%29._hash-iterate-next%29%29), and only as long as the hash table is not modified. In the case of a hash table with weakly held keys or keys held like [ephemerons](ephemerons.html#%28tech._ephemeron%29), the hash table can be implicitly modified by the garbage collector (see [Garbage Collection](eval-model.html#%28part._gc-model%29)) when it discovers that the key is not reachable.\n\n> ```\n(hash-iterate-next ht pos)\n  →  (or/c #f exact-nonnegative-integer?)\n  ht : hash?\n  pos : exact-nonnegative-integer?\n```\nReturns either an integer that is an index to the element in ht after the element indexed by pos (which is not necessarily one more than pos) or #f if pos refers to the last element in ht."} {"text": "# 4.15 Hash Tables\nIf pos is not a valid hash index of ht, then the result may be #f or it may be the next later index that remains valid. The latter result is guaranteed if a hash table has been modified only by the removal of keys.\nChanged in version 7.0.0.10 of package base: Handle an invalid index by returning #f instead of raising exn:fail:contract.\n> ```\n(hash-iterate-key ht pos)  →  any/c\n  ht : hash?\n  pos : exact-nonnegative-integer?\n(hash-iterate-key ht pos bad-index-v)  →  any/c\n  ht : hash?\n  pos : exact-nonnegative-integer?\n  bad-index-v : any/c```\nReturns the key for the element in ht at index pos.\nIf pos is not a [valid hash index](#%28tech._valid._hash._index%29) for ht, the result is bad-index-v if provided, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nChanged in version 7.0.0.10 of package base: Added the optional bad-index-v argument.\n> ```\n(hash-iterate-value ht pos)  →  any/c\n  ht : hash?\n  pos : exact-nonnegative-integer?\n(hash-iterate-value ht pos bad-index-v)  →  any/c\n  ht : hash?\n  pos : exact-nonnegative-integer?\n  bad-index-v : any/c"} {"text": "# 4.15 Hash Tables\n```\nReturns the value for the element in ht at index pos.\n\nIf pos is not a valid hash index for ht, the result is bad-index-v if provided, otherwise the exn:fail:contract exception is raised.\n\nChanged in version 7.0.0.10 of package base: Added the optional bad-index-v argument.\n\n> ```\n(hash-iterate-pair ht pos)  →  (cons/c any/c any/c)\n  ht : hash?\n  pos : exact-nonnegative-integer?\n\n(hash-iterate-pair ht pos bad-index-v)  →  (cons/c any/c any/c)\n  ht : hash?\n  pos : exact-nonnegative-integer?\n  bad-index-v : any/c```\n\n\nReturns a pair containing the key and value for the element in ht at index pos.\n\nIf pos is not a [valid hash index](#%28tech._valid._hash._index%29) for ht, the result is ([cons](pairs.html#%28def._%28%28quote._~23~25kernel%29._cons%29%29) bad-index-v bad-index-v) if bad-index-v is provided, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nAdded in version 6.4.0.5 of package base. \nChanged in version 7.0.0.10: Added the optional bad-index-v argument.\n\n> ```\n(hash-iterate-key+value ht pos)   →   any/c   any/c\n\n  ht : hash?\n  pos : exact-nonnegative-integer?\n\n(hash-iterate-key+value ht pos bad-index-v)   →   any/c   any/c\n\n  ht : hash?\n  pos : exact-nonnegative-integer?\n  bad-index-v : any/c\n```\nReturns the key and value for the element in ht at index pos.\nIf pos is not a valid hash index for ht, the result is (values bad-index-v bad-index-v) if bad-index-v is provided, otherwise the exn:fail:contract exception is raised."} {"text": "# 4.15 Hash Tables\nAdded in version 6.4.0.5 of package base. \nChanged in version 7.0.0.10: Added the optional bad-index-v argument.\n> ```\n(hash-copy ht)  →  (and/c hash? (not/c immutable?))\n  ht : hash?```\nReturns a mutable hash table with the same mappings, same key-comparison mode, and same key-holding strength as ht."} {"text": "#### 4.15.1 Additional Hash Table Functions\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/hash](#%28mod-path._racket%2Fhash%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/hash](#%28mod-path._racket%2Fhash%29) library, not [racket/base](index.html) or [racket](index.html).\n> ```\n(hash-union ht0\n    ht ...  \n   [ #:combine combine  \n    #:combine/key combine/key)  \n  →  (and/c hash? immutable?)\n  ht0 : (and/c hash? immutable?)\n  ht : hash?\n   combine   :   ( →  any/c any/c any/c)\n      =   (lambda _ (error 'hash-union ....))\n   combine/key   :   ( →  any/c any/c any/c any/c)\n      =   (lambda (k a b) (combine a b))"} {"text": "# 4.15 Hash Tables\n```\n(parameter)\t→\t\n(-> and/c hash? (not/c immutable?))```\n\n\nComputes the union of ht0 with each hash table ht by mutable update, adding each element of each ht to ht0 in turn. For each key k and value v, if a mapping from k to some value v0 already exists, it is replaced with a mapping from k to (combine/key k v0 v).\n\nExamples:\n\n> ```racket\n> > ( define h ( make-hash ) )\n> > h\n> '#hash()\n> > ( hash-union! h ( make-immutable-hash ' ( [ 1 one uno ] [ 2 two dos ] ) ) )\n> > h\n> '#hash((1 . (one uno)) (2 . (two dos)))\n> > ( hash-union! h ( make-immutable-hash ' ( [ 1 eins un ] [ 2 zwei deux ] ) ) #:combine/key ( lambda ( k v1 v2 ) ( append v1 v2 ) ) )\n> > h\n> '#hash((1 . (one uno eins un)) (2 . (two dos zwei deux)))\n> ```\n\n> ```\n(hash-intersect ht0\n    ht ...  \n   [ #:combine combine  \n    #:combine/key combine/key)  \n\n  →  (and/c hash? immutable?)\n  ht0 : (and/c hash? immutable?)\n  ht : hash?\n   combine   :   ( →  any/c any/c any/c)\n      =   (lambda _ (error 'hash-intersect ...))\n\n   combine/key   :   ( →  any/c any/c any/c any/c)\n      =   (lambda (k a b) (combine a b))\n```"} {"text": "# 4.15 Hash Tables\nConstructs the hash table which is the intersection of ht0 with every hash table ht. In the resulting hash table, a key k is mapped to a combination of the values to which k is mapped in each of the hash tables. The final values are computed by stepwise combination of the values appearing in each of the hash tables by applying (combine/key k v vi), where vi is the value to which k is mapped in the i-th hash table ht, and v is the accumulation of the values from the previous steps. The comparison predicate of the first argument (eq?, eqv?, equal-always?, equal?) determines the one for the result.\nExamples:\n> ```racket\n> > ( hash-intersect ( make-immutable-hash ' ( ( a . 1 ) ( b . 2 ) ( c . 3 ) ) ) ( make-immutable-hash ' ( ( a . 4 ) ( b . 5 ) ) ) #:combine + )\n> '#hash((a . 5) (b . 7))\n> > ( hash-intersect ( make-immutable-hash ' ( ( a . 1 ) ( b . 2 ) ( c . 3 ) ) ) ( make-immutable-hash ' ( ( a . 4 ) ( b . 5 ) ) ) #:combine/key ( lambda ( k v1 v2 ) ( if ( eq? k ' a ) ( + v1 v2 ) ( - v1 v2 ) ) ) )\n> '#hash((a . 5) (b . -3))\n> ```\nAdded in version 7.9.0.1 of package base.\n> ```\n(hash-filter ht pred)  →  hash?\n  ht : hash?\n  pred : ( →  any/c any/c boolean?)```"} {"text": "# 4.15 Hash Tables\nFilters the [hash?](#%28def._%28%28quote._~23~25kernel%29._hash~3f%29%29) ht based on a predicate pred applied to both its keys and values. This function constructs a new hash table that includes only those key-value pairs from the input ht for which the predicate pred returns true when applied simultaneously to the keys and values of ht. The output hash table retains the mutability and the key comparison predicate (e.g., [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29)) of the input hash table ht, ensuring that the structural and operational properties of the original hash are preserved in the output.\nExamples:\n> ```racket\n> > ( hash-filter ( for/hash ( [ num ' ( 1 2 3 4 5 ) ] ) ( values num ( * num 2 ) ) ) ( λ ( k v ) ( and ( < k 3 ) ( even? v ) ) ) )> '#hash((1 . 2) (2 . 4))\n> > ( hash-filter ( make-hash ) ( λ ( k v ) ( < k 3 ) ) )> '#hash()\n> > ( hash-filter ( make-hasheq ' ( [ #f . \"false\" ] [ #t . \"true\" ] ) ) ( λ ( k v ) ( and ( eq? k #t ) ( string=? v \"true\" ) ) ) )\n> '#hasheq((#t . \"true\"))\n> > ( hash-filter ( hash ( list 1 2 ) ' pair ( vector 3 4 ) ' vector ) ( λ ( k v ) ( and ( list? k ) ( symbol? v ) ) ) )\n> '#hash(((1 2) . pair))\n> > ( hash-filter ( hash \"one\" 1 2 \"two\" \"three\" 3 ) ( λ ( k v ) ( and ( not ( number? k ) ) ( number? v ) ( > v 1 ) ) ) )\n> '#hash((\"three\" . 3))\n> ```\nAdded in version 8.13.0.4 of package base.\n> ```"} {"text": "# 4.15 Hash Tables\n(hash-filter-keys ht pred)  →  hash?\n  ht : hash?\n  pred : procedure?\n```\n(parameter)\t→```\n\n\nFilters the [hash?](#%28def._%28%28quote._~23~25kernel%29._hash~3f%29%29) ht based on a predicate pred applied to its values. This function returns a new hash table containing only the key-value pairs for which the predicate pred returns true when applied to the values of ht. The resulting hash table retains the mutability and the key comparison predicate (e.g., [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29)) of the input hash table ht.\n\nExamples:\n\n> ```racket\n> > ( hash-filter-values ( for/hash ( [ num ' ( 1 2 3 4 5 ) ] ) ( values num num ) ) ( λ ( v ) ( < v 3 ) ) )> '#hash((1 . 1) (2 . 2))\n> > ( hash-filter-values ( make-hash ) ( λ ( v ) ( < v 3 ) ) )> '#hash()\n> > ( hash-filter-values ( make-hasheqv ' ( [ 1 . \"one\" ] [ 2 . \"two\" ] ) ) ( λ ( v ) ( eqv? v \"two\" ) ) )\n> '#hasheqv((2 . \"two\"))\n> > ( hash-filter-values ( hash ' one \"1\" ' two 2 ' three \"3\" ) ( lambda ( v ) ( string? v ) ) )\n> '#hash((one . \"1\") (three . \"3\"))\n> > ( hash-filter-values ( hash ' list ( list 1 2 3 ) ' vector # ( 4 5 6 ) ' string \"hello\" ) ( lambda ( v ) ( vector? v ) ) )\n> '#hash((vector . #(4 5 6)))\n> > ( hash-filter-values ( hash ' nested-hash ( hash ' a 1 ' b 2 ) ' nested-list ( list ' x ' y ' z ) ) ( lambda ( v ) ( hash? v ) ) )\n> '#hash((nested-hash . #hash((a . 1) (b . 2))))\n> ```\n\nAdded in version 8.12.0.9 of package base.\n\n------------------------------------------------------------------------\n\n# 4.16 Treelists\n\n8.18.0.13\n\n### 4.16 Treelists\n\nA treelist represents a sequence of elements in a way that supports many operations in O(log N) time: accessing an element of the list by index, adding to the front of the list, adding to the end of the list, removing an element by index, replacing an element by index, appending lists, dropping elements from the start or end of the list, and extracting a sublist. More generally, unless otherwise specified, operations on a treelist of length N take O(log N) time. The base for the log in O(log N) is large enough that it’s effectively constant-time for many purposes. Treelists are currently implemented as RRB trees \\[[Stucki15](doc-bibliography.html#%28cite._.Stucki15%29)\\].\n\nTreelists are primarily intended to be used in immutable form via [racket/treelist](#%28mod-path._racket%2Ftreelist%29), where an operation such as adding to the treelist produces a new treelist while the old one remains intact. A mutable variant of treelists is provided by [racket/mutable-treelist](#%28mod-path._racket%2Fmutable-treelist%29), where a mutable treelist can be a convenient alternative to putting an immutable treelist into a [box](boxes.html#%28tech._box%29). Mutable treelist operations take the same time as immutable treelist operations, unless otherwise specified. Where the term “treelist” is used by itself, it refers to an immutable treelist.\n\nAn immutable or mutable treelist can be used as a single-valued sequence (see [Sequences](sequences.html)). The elements of the list serve as elements of the sequence. See also [in-treelist](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._in-treelist%29%29) and [in-mutable-treelist](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._in-mutable-treelist%29%29). An immutable treelist can also be used as a [stream](streams.html#%28tech._stream%29).\n\nChanged in version 8.15.0.3 of package base: Made treelists serializable.\n\n#### 4.16.1 Immutable Treelists\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/treelist](#%28mod-path._racket%2Ftreelist%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/treelist](#%28mod-path._racket%2Ftreelist%29) library, not [racket/base](index.html) or [racket](index.html).\n\nAdded in version 8.12.0.7 of package base.\n\n> ```\n(treelist? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 4.15 Hash Tables\nReturns #t if v is a treelist, #f otherwise.\n> ```\n(treelist v ...) → treelist?\n  v : any/c```\nReturns a [treelist](#%28tech._treelist%29) with vs as its elements in order.\nThis operation takes O(N log N) time to construct a treelist of N elements.\nExample:\n> ```racket\n> > ( treelist 1 \"a\" ' apple )\n> (treelist 1 \"a\" 'apple)\n> ```\n> ```\n(make-treelist size v)  →  treelist?\n  size : exact-nonnegative-integer?\n  v : any/c\n```\nReturns a treelist with size size, where every element is v. This operation takes O(log N) time to construct a treelist of N elements.\n\nExamples:\n\n> ```racket\n> > ( make-treelist 0 ' pear )\n> (treelist)\n> > ( make-treelist 3 ' pear )\n> (treelist 'pear 'pear 'pear)\n> ```\n\nAdded in version 8.12.0.11 of package base.\n\n> ```\n(treelist-empty? tl)  →  boolean?\n  tl : treelist?\n\nvalue\n\nempty-treelist : (and/c treelist? treelist-empty?)```\n\n\nA predicate and constant for a [treelist](#%28tech._treelist%29) of length 0.\n\nAlthough every empty treelist is [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) to [empty-treelist](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._empty-treelist%29%29), since a treelist can be chaperoned via [chaperone-treelist](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._chaperone-treelist%29%29), not every empty treelist is [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to [empty-treelist](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._empty-treelist%29%29).\n\n> ```\n(treelist-length tl)  →  exact-nonnegative-integer?\n  tl : treelist?\n```"} {"text": "# 4.15 Hash Tables\nReturns the number of elements in tl. This operation takes O(1) time.\nExamples:\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-length items )\n> 3\n> ```\n> ```\n(treelist-ref tl pos)  →  any/c\n  tl : treelist?\n  pos : exact-nonnegative-integer?\n```\n\n\nReturns the posth element of tl. The first element is position 0, and the last position is one less than ([treelist-length](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-length%29%29) tl).\n\nExamples:\n\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-ref items 0 )\n> 1\n> > ( treelist-ref items 2 )\n> 'apple\n> > ( treelist-ref items 3 )\n> treelist-ref: index is out of range\n> index: 3\n> valid range: [0, 2]\n> treelist: (treelist 1 \"a\" 'apple)\n> ```\n\n> ```\n(treelist-first tl)  →  any/c\n  tl : treelist?\n\n(treelist-last tl)  →  any/c\n  tl : treelist?\n```\nShorthands for using treelist-ref to access the first or last element of a treelist.\nExamples:\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-first items )\n> 1\n> > ( treelist-last items )\n> 'apple\n> ```\n> ```\n(treelist-insert tl pos v)  →  treelist?\n  tl : treelist?\n  pos : exact-nonnegative-integer?\n  v : any/c```\nProduces a treelist like tl, except that v is inserted as an element before the element at pos. If pos is ([treelist-length](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-length%29%29) tl), then v is added to the end of the treelist.\nExamples:"} {"text": "# 4.15 Hash Tables\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-insert items 1 \"alpha\" )\n> (treelist 1 \"alpha\" \"a\" 'apple)\n> > ( treelist-insert items 3 \"alpha\" )\n> (treelist 1 \"a\" 'apple \"alpha\")\n> ```\n> ```\n(treelist-add tl v)  →  treelist?\n  tl : treelist?\n  v : any/c\n(treelist-cons tl v)  →  treelist?\n  tl : treelist?\n  v : any/c\n```\nShorthands for using treelist-insert to insert at the end or beginning of a treelist.\n\nAlthough the main operation to extend a pair list is cons to add to the front, treelists are intended to be extended by adding to the end with treelist-add, and treelist-add tends to be faster than treelist-cons.\n\nExamples:\n\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-add items \"alpha\" )\n> (treelist 1 \"a\" 'apple \"alpha\")\n> > ( treelist-cons items \"alpha\" )\n> (treelist \"alpha\" 1 \"a\" 'apple)\n> ```\n\n> ```\n(treelist-delete tl pos)  →  treelist?\n  tl : treelist?\n  pos : exact-nonnegative-integer?```\n\n\nProduces a treelist like tl, except that the element at pos is removed.\n\nExamples:\n\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-delete items 1 )\n> (treelist 1 'apple)\n> > ( treelist-delete items 3 )\n> treelist-delete: index is out of range\n> index: 3\n> valid range: [0, 2]\n> treelist: (treelist 1 \"a\" 'apple)\n> ```\n\n> ```\n(treelist-set tl pos v)  →  treelist?\n  tl : treelist?\n  pos : exact-nonnegative-integer?\n  v : any/c\n```"} {"text": "# 4.15 Hash Tables\nProduces a treelist like tl, except that the element at pos is replaced with v. The result is equivalent to (treelist-insert (treelist-delete tl pos) pos v).\nExamples:\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-set items 1 \"b\" )\n> (treelist 1 \"b\" 'apple)\n> ```\n> ```\n(treelist-append tl ...) → treelist?\n  tl : treelist?```\nAppends the elements of the given tls into a single [treelist](#%28tech._treelist%29). If M treelists are given and the resulting treelist’s length is N, then appending takes O(M log N) time.\nExamples:\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-append items items )\n> (treelist 1 \"a\" 'apple 1 \"a\" 'apple)\n> > ( treelist-append items ( treelist \"middle\" ) items )\n> (treelist 1 \"a\" 'apple \"middle\" 1 \"a\" 'apple)\n> ```\n> ```\n(treelist-take tl n)  →  treelist?\n  tl : treelist?\n  n : exact-nonnegative-integer?\n(treelist-drop tl n)  →  treelist?\n  tl : treelist?\n  n : exact-nonnegative-integer?\n(treelist-take-right tl n)  →  treelist?\n  tl : treelist?\n  n : exact-nonnegative-integer?\n(treelist-drop-right tl n)  →  treelist?\n  tl : treelist?\n  n : exact-nonnegative-integer?"} {"text": "# 4.15 Hash Tables\n```\nProduces a treelist like tl but with only the first n elements, without the first n elements, with only the last n elements, or without the last n elements, respectively.\n\nExamples:\n\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-take items 2 )\n> (treelist 1 \"a\")\n> > ( treelist-drop items 2 )\n> (treelist 'apple)\n> > ( treelist-take-right items 2 )\n> (treelist \"a\" 'apple)\n> > ( treelist-drop-right items 2 )\n> (treelist 1)\n> ```\n\n> ```\n(treelist-sublist tl n m)  →  treelist?\n  tl : treelist?\n  n : exact-nonnegative-integer?\n  m : exact-nonnegative-integer?```\n\n\nProduces a [treelist](#%28tech._treelist%29) like tl but with only elements at position n (inclusive) through position m (exclusive).\n\nExamples:\n\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-sublist items 1 3 )\n> (treelist \"a\" 'apple)\n> ```\n\n> ```\n(treelist-reverse tl)  →  treelist?\n  tl : treelist?\n```\nProduces a treelist like tl but with its elements reversed, equivalent to using treelist-take to keep 0 elements (but also any chaperone on the treelist) and then adding each element back in reverse order. Reversing takes O(N log N) time.\nExamples:\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-reverse items )\n> (treelist 'apple \"a\" 1)\n> ```\n> ```\n(treelist-rest tl)  →  treelist?\n  tl : treelist?```\nA shorthand for using [treelist-drop](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-drop%29%29) to drop the first element of a [treelist](#%28tech._treelist%29)."} {"text": "# 4.15 Hash Tables\nThe [treelist-rest](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-rest%29%29) operation is efficient, but not as fast as [rest](pairs.html#%28def._%28%28lib._racket%2Flist..rkt%29._rest%29%29) or [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29). For iterating through a treelist, consider using [treelist-ref](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-ref%29%29) or a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) form with [in-treelist](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._in-treelist%29%29), instead.\nExamples:\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-rest items )\n> (treelist \"a\" 'apple)\n> ```\n> ```\n(treelist → vector tl)  →  vector?\n  tl : treelist?\n(treelist → list tl)  →  list?\n  tl : treelist?\n(vector → treelist vec)  →  treelist?\n  vec : vector?\n(list → treelist lst)  →  treelist?\n  lst : list?"} {"text": "# 4.15 Hash Tables\n```\nConvenience functions for converting between treelists, lists, and vectors. Each conversion takes O(N) time.\n\nExamples:\n\n> ```racket\n> > ( define items ( list → treelist ' ( 1 \"a\" ' apple ) ) )\n> > ( treelist → vector items )\n> '#(1 \"a\" 'apple)\n> ```\n\n> ```\n(treelist-map tl proc)  →  treelist?\n  tl : treelist?\n  proc : (any/c . → . any/c)```\n\n\nProduces a [treelist](#%28tech._treelist%29) by applying proc to each element of tl and gathering the results into a new treelist. For a constant-time proc, this operation takes O(N) time.\n\nExamples:\n\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-map items box )\n> (treelist '#&1 '#&\"a\" '#&apple)\n> ```\n\n> ```\n(parameter)\t→\t\n(-> any/c . → . any)\n```\nApplies proc to each element of tl, ignoring the results. For a constant-time proc, this operation takes O(N) time.\nExamples:\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-for-each items println )\n> 1 \"a\" 'apple\n> ```\n> ```\n(treelist-filter keep tl)  →  treelist?\n  keep : (any/c . → . any/c)\n  tl : treelist?"} {"text": "# 4.15 Hash Tables\n```\n\n\nProduces a treelist with only members of tl that satisfy keep.\n\nExamples:\n\n> ```racket\n> > ( treelist-filter even? ( treelist 1 2 3 2 4 5 2 ) )\n> (treelist 2 2 4 2)\n> > ( treelist-filter odd? ( treelist 1 2 3 2 4 5 2 ) )\n> (treelist 1 3 5)\n> > ( treelist-filter ( λ ( x ) ( not ( even? x ) ) ) ( treelist 1 2 3 2 4 5 2 ) )\n> (treelist 1 3 5)\n> > ( treelist-filter ( λ ( x ) ( not ( odd? x ) ) ) ( treelist 1 2 3 2 4 5 2 ) )\n> (treelist 2 2 4 2)\n> ```\n\nAdded in version 8.15.0.6 of package base.\n\n> ```\n(treelist-member? tl v [eql?) → boolean?\n  tl : treelist?\n  v : any/c\n  eql? : (any/c any/c . → . any/c) = equal?\n```\nChecks each element of tl with eql? and v (with v the second argument) until the result is a true value, and then returns #t. If no such element is found, the result is #f. For a constant-time eql?, this operation takes O(N) time.\nExamples:\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-member? items \"a\" )\n> #t\n> > ( treelist-member? items 1.0 = )\n> #t\n> > ( treelist-member? items 2.0 = )\n> =: contract violation\n> expected: number?\n> given: \"a\"\n> ```\n> ```\n(treelist-find tl pred) → any/c\n  tl : treelist?\n  pred : (any/c . → . any/c)```\nChecks each element of tl with pred until the result is a true value, and then returns that element. If no such element is found, the result is #f. For a constant-time pred, this operation takes O(N) time.\nExamples:"} {"text": "# 4.15 Hash Tables\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-find items string? )\n> \"a\"\n> > ( treelist-find items symbol? )\n> 'apple\n> > ( treelist-find items number->string )\n> 1\n> ```\n> ```\n(treelist-index-of tl v [eql?)\n  →  (or/c exact-nonnegative-integer? #f)\n  tl : treelist?\n  v : any/c\n  eql? : (any/c any/c . → . any/c) = equal?\n```\n\n\nReturns the index of the first element in tl that is eql? to v. If no such element is found, the result is #f.\n\nExamples:\n\n> ```racket\n> > ( define items ( treelist 1 \"a\" ' apple ) )\n> > ( treelist-index-of items 1 )\n> 0\n> > ( treelist-index-of items \"a\" )\n> 1\n> > ( treelist-index-of items ' apple )\n> 2\n> > ( treelist-index-of items ' unicorn )\n> #f\n> ```\n\nAdded in version 8.15.0.6 of package base.\n\n> ```\n(treelist-flatten v)  →  treelist?\n  v : any/c\n```\nFlattens a tree of nested treelists into a single treelist.\nExamples:\n> ```racket\n> > ( treelist-flatten ( treelist ( treelist \"a\" ) \"b\" ( treelist \"c\" ( treelist \"d\" ) \"e\" ) ( treelist ) ) )\n> (treelist \"a\" \"b\" \"c\" \"d\" \"e\")\n> > ( treelist-flatten \"a\" )\n> (treelist \"a\")\n> ```\nAdded in version 8.15.0.6 of package base.\n> ```\n(treelist-append* tlotl)  →  treelist?\n  tlotl : (treelist/c treelist?)"} {"text": "# 4.15 Hash Tables\n```\nAppends elements of a treelist of treelists together into one treelist, leaving any further nested treelists alone.\n\nExample:\n\n> ```racket\n> > ( treelist-append* ( treelist ( treelist \"a\" \"b\" ) ( treelist \"c\" ( treelist \"d\" ) \"e\" ) ( treelist ) ) )\n> (treelist \"a\" \"b\" \"c\" (treelist \"d\") \"e\")\n> ```\n\nAdded in version 8.15.0.6 of package base.\n\n> ```\n(treelist-sort tl\n    less-than?        \n   [ #:key key        \n    #:cache-keys? cache-keys?)   →   treelist?\n\n  tl : treelist?\n  less-than? : (any/c any/c . → . any/c)\n  key : (or/c #f (any/c . → . any/c)) = #f\n  cache-keys? : boolean? = #f```\n\n\nLike [sort](pairs.html#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._sort%29%29), but operates on a [treelist](#%28tech._treelist%29) to produce a sorted treelist. Sorting takes O(N log N) time.\n\nExamples:\n\n> ```racket\n> > ( define items ( treelist \"x\" \"a\" \"q\" ) )\n> > ( treelist-sort items string (treelist \"a\" \"q\" \"x\")\n> ```\n\n> ```\n(in-treelist tl)  →  sequence?\n  tl : treelist?\n```\nReturns a sequence equivalent to tl.\nAn in-treelist application can provide better performance for treelist iteration when it appears directly in a for clause.\nExamples:\n> ```racket\n> > ( define items ( treelist \"x\" \"a\" \"q\" ) )\n> > ( for/list ( [ e ( in-treelist items ) ] ) ( string-append e \"!\" ) )\n> '(\"x!\" \"a!\" \"q!\")\n> ```\n> ```\n(sequence → treelist s) → treelist?\n  s : sequence?```\nReturns a treelist whose elements are the elements of s, each of which must be a single value. If s is infinite, this function does not terminate.\nExamples:"} {"text": "# 4.15 Hash Tables\n> ```racket\n> > ( sequence->treelist ( list 1 \"a\" ' apple ) )\n> (treelist 1 \"a\" 'apple)\n> > ( sequence->treelist ( vector 1 \"a\" ' apple ) )\n> (treelist 1 \"a\" 'apple)\n> > ( sequence->treelist ( stream 1 \"a\" ' apple ) )\n> (treelist 1 \"a\" 'apple)\n> > ( sequence->treelist ( open-input-bytes ( bytes 1 2 3 4 5 ) ) )\n> (treelist 1 2 3 4 5)\n> > ( sequence->treelist ( in-range 0 10 ) )\n> (treelist 0 1 2 3 4 5 6 7 8 9)\n> ```\nAdded in version 8.15.0.6 of package base.\n>
\n

syntax

\n

([for/treelist](#%28form._%28%28lib._racket%2Ftreelist..rkt%29._for%2Ftreelist%29%29) (for-clause ...) body-or-break ... body)

\n

syntax

\n

([for*/treelist](#%28form._%28%28lib._racket%2Ftreelist..rkt%29._for%2A%2Ftreelist%29%29) (for-clause ...) body-or-break ... body)

\nLike [for/list](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29) and [for*/list](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%2Flist%29%29), but generating [treelists](#%28tech._treelist%29).\nExample:"} {"text": "# 4.15 Hash Tables\n> ```racket\n> > ( for/treelist ( [ i ( in-range 10 ) ] ) i )\n> (treelist 0 1 2 3 4 5 6 7 8 9)\n> ```\n> ```\n(chaperone-treelist tl\n    #:state state  \n   [ #:state-key state-key]  \n    #:ref ref-proc  \n    #:set set-proc  \n    #:insert insert-proc  \n    #:delete delete-proc  \n    #:take take-proc  \n    #:drop drop-proc  \n    #:append append-proc  \n    #:prepend prepend-proc  \n   [ #:append2 append2-proc]  \n    prop  \n    prop-val ...  \n    ...)  \n  →  (and/c treelist? chaperone?)\n  tl : treelist?\n  state : any/c\n  state-key : any/c = (list 'fresh)\n   ref-proc   :   ( treelist? exact-nonnegative-integer? any/c any/c\n> . → . any/c )\n   set-proc   :   ( treelist? exact-nonnegative-integer? any/c any/c\n> . → . ( values any/c any/c ) )\n   insert-proc   :   ( treelist? exact-nonnegative-integer? any/c any/c\n> . → . ( values any/c any/c ) )\n   delete-proc   :   ( treelist? exact-nonnegative-integer? any/c\n> . → . any/c )\n   take-proc   :   ( treelist? exact-nonnegative-integer? any/c\n> . → . any/c )\n   drop-proc   :   ( treelist? exact-nonnegative-integer? any/c\n> . → . any/c )\n   append-proc   :   ( treelist? treelist? any/c\n> . → . ( values treelist? any/c ) )\n   prepend-proc   :   ( treelist? treelist? any/c\n> . → . ( values treelist? any/c ) )\n   append2-proc   :   ( or/c #f ( treelist? treelist? any/c any/c\n> . → . ( values treelist? any/c any/c ) ) )\n      =   #f\n  prop : impersonator-property?\n  prop-val : any/c"} {"text": "# 4.15 Hash Tables\n```\nAnalogous to chaperone-vector, returns a chaperone of tl, which redirects the treelist-ref, treelist-set, treelist-insert, treelist-append, treelist-delete, treelist-take, and treelist-drop operations, as well as operations derived from those. The state argument is an initial state, where a state value is passed to each procedure that redirects an operation, and except for ref-proc (which corresponds to the one operation that does not update a treelist), a new state is returned to be associated with the updated treelist. When state-key is provided, it can be used with treelist-chaperone-state to extract the state from the original treelist or an updated treelist.\n\nThe ref-proc procedure must accept tl, an index passed to treelist-ref, the value that treelist-ref on tl produces for the given index, and the current chaperone state; it must produce a chaperone replacement for the value, which is the result of treelist-ref on the chaperone.\n\nThe set-proc procedure must accept tl, an index passed to treelist-set, the value provided to treelist-set, and the current chaperone state; it must produce two values: a chaperone replacement for the value, which is used in the result of treelist-set on the chaperone, and an updated state. The result of treelist-set is chaperoned with the same procedures and properties as tl, but with the updated state.\n\nThe insert-proc procedure is like set-proc, but for inserting via treelist-insert.\n\nThe delete-proc, take-proc, and drop-proc procedures must accept tl, the index or count for deleting, taking or dropping, and the current chaperone state; they must produce an updated state. The result of treelist-delete, treelist-take, or treelist-drop is chaperoned with the same procedures and properties as tl, but with the updated state.\n\nThe append-proc procedure must accept tl, a treelist to append onto tl, and the current chaperone state; it must produce a chaperone replacement for the second treelist, which is appended for the result of treelist-append on the chaperone, and an updated state. The result of treelist-append is chaperoned with the same procedures and properties as tl, but with the updated state.\n\nThe prepend-proc procedure must accept a treelist being append with tl, tl, and the current chaperone state; it must produce a chaperone replacement for the first treelist, which is prepended for the result of treelist-append on the chaperone, and an updated state. The result of treelist-append is chaperoned with the same procedures and properties as tl, but with the updated state.\n\nThe append2-proc procedure is optional and similar to append-proc, but when it is non-#f, append2-proc is used instead of append-proc when a second argument to treelist-append is chaperoned with the same state-key. In that case, the second argument to append2-proc is the second argument with a state-key chaperone wrapper removed, and with that chaperone’s state as the last argument to append2-proc.\n\nWhen two chaperoned treelists are given to treelist-append and append2-proc is not used, then the append-proc of the first treelist is used, and the result of append-proc will still be a chaperone whose prepend-proc is used. If the result of prepend-proc is a chaperone, then that chaperone’s append-proc is used, and so on. If prepend-proc and append-proc keep returning chaperones, it is possible that no progress will be made.\n\nExample:\n\n> ```racket\n> > ( chaperone-treelist ( treelist 1 \"a\" ' apple ) #:state ' ignored-state #:ref ( λ ( tl pos v state ) v ) #:set ( λ ( tl pos v state ) ( values v state ) ) #:insert ( λ ( tl pos v state ) ( values v state ) ) #:delete ( λ ( tl pos state ) state ) #:take ( λ ( tl pos state ) state ) #:drop ( λ ( tl pos state ) state ) #:append2 ( λ ( tl other state other-state ) ; or #f ( values other state ) ) #:append ( λ ( tl other state ) ( values other state ) ) #:prepend ( λ ( other tl state ) ( values other state ) ) )\n> (treelist 1 \"a\" 'apple)\n> ```\n\n> ```\n(treelist-chaperone-state tl\n    state-key        \n   [ fail-k)   →   any/c\n\n  tl : treelist?\n  state-key : any/c\n  fail-k : (procedure-arity-includes/c 0) = key-error```\n\n\nExtracts state associated with a treelist chaperone where state-key (compared using [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)) was provided along with the initial state to [chaperone-treelist](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._chaperone-treelist%29%29). If tl is not a chaperone with state keyed by state-key, then fail-k is called, and the default fail-k raises [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29).\n\n#### 4.16.2 Mutable Treelists\n\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/mutable-treelist](#%28mod-path._racket%2Fmutable-treelist%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/mutable-treelist](#%28mod-path._racket%2Fmutable-treelist%29) library, not [racket/base](index.html) or [racket](index.html).\n\nA mutable treelist is like an immutable [treelist](#%28tech._treelist%29) in a box, where operations that change the mutable treelist replace the treelist in the box. As a special case, [mutable-treelist-set!](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._mutable-treelist-set%21%29%29) on an unimpersonated mutable treelist modifies the treelist representation within the boxed value. This model of a mutable treelist explains its behavior in the case of concurrent modification: concurrent [mutable-treelist-set!](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._mutable-treelist-set%21%29%29) operations for different positions will not interefere, but races with other operations or on impersonated mutable treelists will sometimes negate one of the modifications. Concurrent modification is thus somewhat unpredictable but still safe, and it is not managed by a lock.\n\nA mutable treelist is not a treelist in the sense of [treelist?](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist~3f%29%29), which recognizes only immutable treelists. Operations on a mutable treelist have the same time complexity as corresponding operations on an immutable treelist unless otherwise noted.\n\nAdded in version 8.12.0.7 of package base.\n\n> ```\n(mutable-treelist? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 4.15 Hash Tables\nReturns #t if v is a mutable treelist, #f otherwise.\n> ```\n(mutable-treelist v ...) → mutable-treelist?\n  v : any/c```\nReturns a [mutable treelist](#%28tech._mutable._treelist%29) with vs as its elements in order.\nExample:\n> ```racket\n> > ( mutable-treelist 1 \"a\" ' apple )\n> (mutable-treelist 1 \"a\" 'apple)\n> ```\n> ```\n(make-mutable-treelist n [v) → mutable-treelist?\n  n : exact-nonnegative-integer?\n  v : any/c = #f\n```\nCreates a mutable treelist that contains n elements, each initialized as v. Creating the mutable treelist takes O(N) time for N elements.\n\nExample:\n\n> ```racket\n> > ( make-mutable-treelist 3 \"a\" )\n> (mutable-treelist \"a\" \"a\" \"a\")\n> ```\n\n> ```\n(treelist-copy tl)  →  mutable-treelist?\n  tl : treelist?\n\n(mutable-treelist-copy tl)  →  mutable-treelist?\n  tl : mutable-treelist?```\n\n\nCreates a [mutable treelist](#%28tech._mutable._treelist%29) that contains the same elements as tl. Creating the mutable treelist takes O(N) time for N elements.\n\nExamples:\n\n> ```racket\n> > ( treelist-copy ( treelist 3 \"a\" ) )\n> (mutable-treelist 3 \"a\")\n> > ( mutable-treelist-copy ( mutable-treelist 3 \"a\" ) )\n> (mutable-treelist 3 \"a\")\n> ```\n\n> ```\n(mutable-treelist-snapshot tl [n m) → treelist?\n  tl : mutable-treelist?\n  n : exact-nonnegative-integer? = 0\n  m : (or/c #f exact-nonnegative-integer?) = #f\n```"} {"text": "# 4.15 Hash Tables\nProduces an immutable treelist that has the same elements as tl at position n (inclusive) through position m (exclusive). If m is #f, then the length of tl is used, instead. Creating the immutable treelist takes O(N) time for N elements of the resulting treelist, on top of the cost of treelist-sublist if the result is a sublist.\nExamples:\n> ```racket\n> > ( define items ( mutable-treelist 1 \"a\" ' apple ) )\n> > ( define snap ( mutable-treelist-snapshot items ) )\n> > snap\n> (treelist 1 \"a\" 'apple)\n> > ( mutable-treelist-snapshot items 1 )\n> (treelist \"a\" 'apple)\n> > ( mutable-treelist-snapshot items 1 2 )\n> (treelist \"a\")\n> > ( mutable-treelist-drop! items 2 )\n> > items\n> (mutable-treelist 'apple)\n> > snap\n> (treelist 1 \"a\" 'apple)\n> ```\n> ```\n(mutable-treelist-empty? tl)  →  boolean?\n  tl : mutable-treelist?```\nReturns #t for [mutable treelist](#%28tech._mutable._treelist%29) that is currently of length 0, #f otherwise.\n> ```\n(mutable-treelist-length tl)  →  exact-nonnegative-integer?\n  tl : mutable-treelist?\n```\n\n\nReturns the number of elements currently in tl.\n\nExamples:\n\n> ```racket\n> > ( define items ( mutable-treelist 1 \"a\" ' apple ) )\n> > ( mutable-treelist-length items )\n> 3\n> > ( mutable-treelist-add! items ' extra )\n> > ( mutable-treelist-length items )\n> 4\n> ```\n\n> ```\n(mutable-treelist-ref tl pos)  →  any/c\n  tl : mutable-treelist?\n  pos : exact-nonnegative-integer?\n```"} {"text": "# 4.15 Hash Tables\nReturns the posth element of tl. The first element is position 0, and the last position is one less than ([mutable-treelist-length](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._mutable-treelist-length%29%29) tl).\nExamples:\n> ```racket\n> > ( define items ( mutable-treelist 1 \"a\" ' apple ) )\n> > ( mutable-treelist-ref items 0 )\n> 1\n> > ( mutable-treelist-ref items 2 )\n> 'apple\n> > ( mutable-treelist-ref items 3 )\n> mutable-treelist-ref: index is out of range\n> index: 3\n> valid range: [0, 2]\n> mutable treelist: (mutable-treelist 1 \"a\" 'apple)\n> ```\n> ```\n(mutable-treelist-first tl)  →  any/c\n  tl : mutable-treelist?\n(mutable-treelist-last tl)  →  any/c\n  tl : mutable-treelist?\n```\n(parameter)\t→```\n\n\nModifies tl to insert v into the list before position pos. If pos is ([mutable-treelist-length](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._mutable-treelist-length%29%29) tl), then v is added to the end of the treelist.\n\nExamples:\n\n> ```racket\n> > ( define items ( mutable-treelist 1 \"a\" ' apple ) )\n> > ( mutable-treelist-insert! items 1 \"alpha\" )\n> > items\n> (mutable-treelist 1 \"alpha\" \"a\" 'apple)\n> ```\n\n> ```\n(parameter)\t→\t\n(-> mutable-treelist-add! tl v)\n```\n(parameter)\t→```\nModifies tl to remove the element at pos.\nExamples:\n> ```racket\n> > ( define items ( mutable-treelist 1 \"a\" ' apple ) )\n> > ( mutable-treelist-delete! items 1 )\n> > items\n> (mutable-treelist 1 'apple)\n> ```\n> ```\n(parameter)\t→"} {"text": "# 4.15 Hash Tables\n```\n(parameter)\t→\t\n(-> or/c treelist? mutable-treelist?)```\n\n\nModifies tl by appending or prepending all of the elements of other-tl. If other-tl is a [mutable treelist](#%28tech._mutable._treelist%29), it is first converted to an immutable [treelist](#%28tech._treelist%29) with [mutable-treelist-snapshot](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._mutable-treelist-snapshot%29%29), which takes O(N) time if other-tl has N elements. If other-tl is an immutable treelist but chaperoned, then appending or prepending takes O(N) time for N elements.\n\nExamples:\n\n> ```racket\n> > ( define items ( mutable-treelist 1 \"a\" ' apple ) )\n> > ( mutable-treelist-append! items ( treelist ' more ' things ) )\n> > items\n> (mutable-treelist 1 \"a\" 'apple 'more 'things)\n> > ( mutable-treelist-prepend! items ( treelist 0 \"b\" ' banana ) )\n> > items\n> (mutable-treelist 0 \"b\" 'banana 1 \"a\" 'apple 'more 'things)\n> > ( mutable-treelist-append! items items )\n> > items\n> (mutable-treelist 0 \"b\" 'banana 1 \"a\" 'apple 'more 'things 0 \"b\" 'banana 1 \"a\" 'apple 'more 'things)\n> ```\n\nChanged in version 8.15.0.11 of package base: Added [mutable-treelist-prepend!](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._mutable-treelist-prepend%21%29%29).\n\n> ```\n(parameter)\t→\t\n(-> mutable-treelist-drop! tl n)\n```\n(parameter)\t→```\nModifies tl to remove elements other than elements at position n (inclusive) through position m (exclusive).\nExamples:"} {"text": "# 4.15 Hash Tables\n> ```racket\n> > ( define items ( mutable-treelist 1 \"a\" ' apple ' pie ) )\n> > ( mutable-treelist-sublist! items 1 3 )\n> > items\n> (mutable-treelist \"a\" 'apple)\n> ```\n> ```\n(parameter)\t→\n```\n\n\nModifies tl to reverse all of its elements.\n\nExamples:\n\n> ```racket\n> > ( define items ( mutable-treelist 1 \"a\" ' apple ' pie ) )\n> > ( mutable-treelist-reverse! items )\n> > items\n> (mutable-treelist 'pie 'apple \"a\" 1)\n> ```\n\n> ```\n(mutable-treelist → vector tl)  →  vector?\n  tl : mutable-treelist?\n\n(mutable-treelist → list tl)  →  list?\n  tl : mutable-treelist?\n\n(vector → mutable-treelist vec)  →  mutable-treelist?\n  vec : vector?\n\n(list → mutable-treelist lst)  →  mutable-treelist?\n  lst : list?\n```\nConvenience functions for converting between [mutable treelists](#%28tech._mutable._treelist%29), [lists](pairs.html#%28tech._list%29), and [vectors](vectors.html#%28tech._vector%29). Each conversion takes O(N) time.\nExamples:\n> ```racket\n> > ( define items ( list->mutable-treelist ' ( 1 \"a\" ' apple ) ) )\n> > ( mutable-treelist->vector items )\n> '#(1 \"a\" 'apple)\n> ```\n> ```\n(parameter)\t→\t\n(-> any/c . → . any/c)"} {"text": "# 4.15 Hash Tables\n```\n(parameter)\t→\t\n(-> any/c . → . any)```\n\n\nLike [treelist-for-each](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-for-each%29%29), but for a [mutable treelist](#%28tech._mutable._treelist%29).\n\nExamples:\n\n> ```racket\n> > ( define items ( mutable-treelist 1 \"a\" ' apple ) )\n> > ( mutable-treelist-for-each items println )\n> 1 \"a\" 'apple\n> ```\n\n> ```\n(mutable-treelist-member? tl v [eql?) → boolean?\n  tl : mutable-treelist?\n  v : any/c\n  eql? : (any/c any/c . → . any/c) = equal?\n```\nLike treelist-member?, but for a mutable treelist.\nExamples:\n> ```racket\n> > ( define items ( mutable-treelist 1 \"a\" ' apple ) )\n> > ( mutable-treelist-member? items \"a\" )\n> #t\n> > ( mutable-treelist-member? items 1.0 = )\n> #t\n> ```\n> ```\n(mutable-treelist-find tl pred) → any/c\n  tl : mutable-treelist?\n  pred : (any/c . → . any/c)```\nLike [treelist-find](#%28def._%28%28lib._racket%2Ftreelist..rkt%29._treelist-find%29%29), but for a [mutable treelist](#%28tech._mutable._treelist%29).\nExamples:\n> ```racket\n> > ( define items ( mutable-treelist 1 \"a\" ' apple ) )\n> > ( mutable-treelist-find items string? )\n> \"a\"\n> > ( mutable-treelist-find items symbol? )\n> 'apple\n> ```\n> ```\n(parameter)\t→\t\n(-> any/c any/c . → . any/c)"} {"text": "# 4.15 Hash Tables\n```\nLike vector-sort!, but operates on a mutable treelist.\n\nExamples:\n\n> ```racket\n> > ( define items ( mutable-treelist \"x\" \"a\" \"q\" ) )\n> > ( mutable-treelist-sort! items string > items\n> (mutable-treelist \"a\" \"q\" \"x\")\n> ```\n\n> ```\n(in-mutable-treelist tl)  →  sequence?\n  tl : mutable-treelist?```\n\n\nReturns a [sequence](sequences.html#%28tech._sequence%29) equivalent to tl.\n\nAn [in-mutable-treelist](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._in-mutable-treelist%29%29) application can provide better performance for mutable treelist iteration when it appears directly in a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) clause.\n\nExamples:\n\n> ```racket\n> > ( define items ( mutable-treelist \"x\" \"a\" \"q\" ) )\n> > ( for/list ( [ e ( in-mutable-treelist items ) ] ) ( string-append e \"!\" ) )\n> '(\"x!\" \"a!\" \"q!\")\n> ```\n\n>
\n\n

syntax

\n\n

([for/mutable-treelist](#%28form._%28%28lib._racket%2Fmutable-treelist..rkt%29._for%2Fmutable-treelist%29%29) maybe-length (for-clause ...) body-or-break ... body)

\n\n

syntax

\n\n

([for*/mutable-treelist](#%28form._%28%28lib._racket%2Fmutable-treelist..rkt%29._for%2A%2Fmutable-treelist%29%29) maybe-length (for-clause ...) body-or-break ... body)

\n\nLike [for/vector](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Fvector%29%29) and [for*/vector](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%2Fvector%29%29), but generating [mutable treelists](#%28tech._mutable._treelist%29).\n\nExamples:\n\n> ```racket\n> > ( for/mutable-treelist ( [ i ( in-range 10 ) ] ) i )\n> (mutable-treelist 0 1 2 3 4 5 6 7 8 9)\n> > ( for/mutable-treelist #:length 15 ( [ i ( in-range 10 ) ] ) i )\n> (mutable-treelist 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0)\n> > ( for/mutable-treelist #:length 15 #:fill ' a ( [ i ( in-range 10 ) ] ) i )\n> (mutable-treelist 0 1 2 3 4 5 6 7 8 9 'a 'a 'a 'a 'a)\n> ```\n\n> ```\n(chaperone-mutable-treelist tl\n    #:ref ref-proc  \n    #:set set-proc  \n    #:insert insert-proc  \n    #:append append-proc  \n   [ #:prepend prepend-proc]  \n    prop  \n    prop-val ...  \n    ...)  \n\n  →  (and/c mutable-treelist? chaperone?)\n  tl : mutable-treelist?\n   ref-proc   :   ( mutable-treelist? exact-nonnegative-integer? any/c\n> . → . any/c )\n\n   set-proc   :   ( mutable-treelist? exact-nonnegative-integer? any/c\n> . → . any/c )\n\n   insert-proc   :   ( mutable-treelist? exact-nonnegative-integer? any/c\n> . → . any/c )\n\n   append-proc   :   ( mutable-treelist? treelist?\n> . → . treelist? )\n\n   prepend-proc   :   ( treelist? mutable-treelist?\n> . → . treelist? )\n      =   (λ (o t) (append-proc t o))\n\n  prop : impersonator-property?\n  prop-val : any/c\n```"} {"text": "# 4.15 Hash Tables\nSimilar to chaperone-treelist, but for mutable treelists. For example, the given set-proc is used for mutable-treelist-set!, and the resulting value is installed into the mutable treelist instead of the one provided to set-proc. Mutable treelist chaperones do not have state separate from the treelist itself, and procedures like set-proc do not consume or return a state.\n> ```\n(impersonate-mutable-treelist tl\n    #:ref ref-proc  \n    #:set set-proc  \n    #:insert insert-proc  \n    #:append append-proc  \n   [ #:prepend prepend-proc]  \n    prop  \n    prop-val ...  \n    ...)  \n  →  (and/c mutable-treelist? impersonator?)\n  tl : mutable-treelist?\n   ref-proc   :   ( mutable-treelist? exact-nonnegative-integer? any/c\n> . → . any/c )\n   set-proc   :   ( mutable-treelist? exact-nonnegative-integer? any/c\n> . → . any/c )\n   insert-proc   :   ( mutable-treelist? exact-nonnegative-integer? any/c\n> . → . any/c )\n   append-proc   :   ( mutable-treelist? treelist?\n> . → . treelist? )\n   prepend-proc   :   ( treelist? mutable-treelist?\n> . → . treelist? )\n      =   (λ (o t) (append-proc t o))\n  prop : impersonator-property?\n  prop-val : any/c```\nLike [chaperone-mutable-treelist](#%28def._%28%28lib._racket%2Fmutable-treelist..rkt%29._chaperone-mutable-treelist%29%29), but ref-proc, set-proc, insert-proc, and append-proc are not obligated to produce chaperones.\n------------------------------------------------------------------------"} {"text": "# 4.17 Sequences and Streams"} {"text": "### 4.17 Sequences and Streams\n[Sequences](sequences.html#%28tech._sequence%29) and [streams](streams.html#%28tech._stream%29) abstract over iteration of elements in a collection. Sequences allow iteration with [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) macros or with sequence operations such as [sequence-map](sequences.html#%28def._%28%28lib._racket%2Fsequence..rkt%29._sequence-map%29%29). Streams are functional sequences that can be used either in a generic way or a stream-specific way. [Generators](Generators.html#%28tech._generator%29) are closely related stateful objects that can be converted to a sequence and vice-versa."} {"text": "# 4.17 Sequences and Streams\n| |\n|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n|     [4.17.1 Sequences](sequences.html) |\n|       [4.17.1.1 Sequence Predicate and Constructors](sequences.html#%28part._.Sequence_.Predicate_and_.Constructors%29) |\n|       [4.17.1.2 Sequence Conversion](sequences.html#%28part._.Sequence_.Conversion%29) |\n|       [4.17.1.3 Additional Sequence Operations](sequences.html#%28part._more-sequences%29) |\n|         [4.17.1.3.1 Additional Sequence Constructors and Functions](sequences.html#%28part._.Additional_.Sequence_.Constructors_and_.Functions%29) |\n|     [4.17.2 Streams](streams.html) |\n|     [4.17.3 Generators](Generators.html) |\n------------------------------------------------------------------------"} {"text": "# 4.17.1 Sequences"} {"text": "#### 4.17.1 Sequences\n> > > \"+\"[Sequence Constructors](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=for.html%23%2528part._sequences%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces sequences.\nA sequence encapsulates an ordered collection of values. The elements of a sequence can be extracted with one of the [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) syntactic forms, with the procedures returned by [sequence-generate](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-generate%29%29), or by converting the sequence into a [stream](streams.html#%28tech._stream%29).\nThe sequence datatype overlaps with many other datatypes. Among built-in datatypes, the sequence datatype includes the following:\n- exact nonnegative integers (see below)\n- strings (see [Strings](strings.html))\n- byte strings (see [Byte Strings](bytestrings.html))\n- lists (see [Pairs and Lists](pairs.html))\n- mutable lists (see [Mutable Pairs and Lists](mpairs.html))\n- vectors (see [Vectors](vectors.html))\n- flvectors (see [Flonum Vectors](flonums.html#%28part._flvectors%29))\n- fxvectors (see [Fixnum Vectors](fixnums.html#%28part._fxvectors%29))\n- hash tables (see [Hash Tables](hashtables.html))\n- dictionaries (see [Dictionaries](dicts.html))\n- sets (see [Sets](sets.html))"} {"text": "# 4.17.1 Sequences\n- input ports (see [Ports](ports.html))\n- streams (see [Streams](streams.html))\nAn [exact number](numbers.html#%28tech._exact._number%29) k that is a non-negative [integer](numbers.html#%28tech._integer%29) acts as a sequence similar to ([in-range](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29) k), except that k by itself is not a [stream](streams.html#%28tech._stream%29).\nCustom sequences can be defined using structure type properties. The easiest method to define a custom sequence is to use the [gen:stream](streams.html#%28def._%28%28lib._racket%2Fstream..rkt%29._gen~3astream%29%29) [generic interface](struct-generics.html#%28tech._generic._interface%29). Streams are a suitable abstraction for data structures that are directly iterable. For example, a list is directly iterable with [first](pairs.html#%28def._%28%28lib._racket%2Flist..rkt%29._first%29%29) and [rest](pairs.html#%28def._%28%28lib._racket%2Flist..rkt%29._rest%29%29). On the other hand, vectors are not directly iterable: iteration has to go through an index. For data structures that are not directly iterable, the iterator for the data structure can be defined to be a stream (e.g., a structure containing the index of a vector).\nFor example, unrolled linked lists (represented as a list of vectors) themselves do not fit the stream abstraction, but have index-based iterators that can be represented as streams:\nExamples:"} {"text": "# 4.17.1 Sequences\n> ```racket\n> > ( struct unrolled-list-iterator ( idx lst ) #:methods gen:stream [ ( define ( stream-empty? iter ) ( define lst ( unrolled-list-iterator-lst iter ) ) ( or ( null? lst ) ( and ( >= ( unrolled-list-iterator-idx iter ) ( vector-length ( first lst ) ) ) ( null? ( rest lst ) ) ) ) ) ( define ( stream-first iter ) ( vector-ref ( first ( unrolled-list-iterator-lst iter ) ) ( unrolled-list-iterator-idx iter ) ) ) ( define ( stream-rest iter ) ( define idx ( unrolled-list-iterator-idx iter ) ) ( define lst ( unrolled-list-iterator-lst iter ) ) ( if ( >= idx ( sub1 ( vector-length ( first lst ) ) ) ) ( unrolled-list-iterator 0 ( rest lst ) ) ( unrolled-list-iterator ( add1 idx ) lst ) ) ) ] )\n> > ( define ( make-unrolled-list-iterator ul ) ( unrolled-list-iterator 0 ( unrolled-list-lov ul ) ) )\n> > ( struct unrolled-list ( lov ) #:property prop:sequence make-unrolled-list-iterator )\n> > ( define ul1 ( unrolled-list ' ( # ( cracker biscuit ) # ( cookie scone ) ) ) )\n> > ( for/list ( [ x ul1 ] ) x )\n> '(cracker biscuit cookie scone)\n> ```"} {"text": "# 4.17.1 Sequences\nThe [prop:sequence](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._prop~3asequence%29%29) property provides more flexibility in specifying iteration, such as when a pre-processing step is needed to prepare the data for iteration. The [make-do-sequence](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-do-sequence%29%29) function creates a sequence given a thunk that returns procedures to implement a sequence, and the [prop:sequence](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._prop~3asequence%29%29) property can be associated with a structure type to implement its implicit conversion to a sequence."} {"text": "# 4.17.1 Sequences\nFor most sequence types, extracting elements from a sequence has no side-effect on the original sequence value; for example, extracting the sequence of elements from a list does not change the list. For other sequence types, each extraction implies a side effect; for example, extracting the sequence of bytes from a port causes the bytes to be read from the port. A sequence’s state may either span all uses of the sequence, as for a port, or it may be confined to each distinct time that a sequence is initiated by a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) form, [sequence->stream](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-~3estream%29%29), [sequence-generate](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-generate%29%29), or [sequence-generate*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-generate%2A%29%29). Concretely, the thunk passed to [make-do-sequence](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-do-sequence%29%29) is called to [initiate](#%28tech._initiate%29) the sequence each time the sequence is used. Accordingly, different sequences behave differently when they are [initiate](#%28tech._initiate%29)d multiple times."} {"text": "# 4.17.1 Sequences\n> ```racket\n> > ( define ( double-initiate s1 ) ; initiate the sequence twice ( define-values ( more?.1 next.1 ) ( sequence-generate s1 ) ) ( define-values ( more?.2 next.2 ) ( sequence-generate s1 ) ) ; alternate fetching from sequence via the two initiations ( list ( next.1 ) ( next.2 ) ( next.1 ) ( next.2 ) ) )\n> > ( double-initiate ( open-input-string \"abcdef\" ) )\n> '(97 98 99 100)\n> > ( double-initiate ( list 97 98 99 100 ) )\n> '(97 97 98 98)\n> > ( double-initiate ( in-naturals 97 ) )\n> '(97 97 98 98)\n> ```\nAlso, subsequent elements in a sequence may be “consumed” just by calling the first result of [sequence-generate](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-generate%29%29), even if the second result is never called.\n> ```racket\n> > ( define ( double-initiate-and-use-more? s1 ) ; initiate the sequence twice ( define-values ( more?.1 next.1 ) ( sequence-generate s1 ) ) ( define-values ( more?.2 next.2 ) ( sequence-generate s1 ) ) ; alternate fetching from sequence via the two initiations ; but this time call `more?` in between ( list ( next.1 ) ( more?.1 ) ( next.2 ) ( more?.2 ) ( next.1 ) ( more?.1 ) ( next.2 ) ( more?.2 ) ) )\n> > ( double-initiate-and-use-more? ( open-input-string \"abcdef\" ) )\n> '(97 #t 99 #t 98 #t 100 #t)\n> ```\nIn this example, the state embedded in the first call to [sequence-generate](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-generate%29%29) “takes” the 98 just by virtue of the invocation of more?.1."} {"text": "# 4.17.1 Sequences\nIndividual elements of a sequence typically correspond to single values, but an element may also correspond to multiple values. For example, a hash table generates two values—a key and its value—for each element in the sequence."} {"text": "##### 4.17.1.1 Sequence Predicate and Constructors\n> ```\n(sequence? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v can be used as a sequence, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( sequence? 42 )\n> #t\n> > ( sequence? ' ( a b c ) )\n> #t\n> > ( sequence? \"word\" )\n> #t\n> > ( sequence? #\\x )\n> #f\n> ```\n\n> ```\n(in-range end) → stream?\n  end : real?\n(in-range start end [step)  →  stream?\n  start : real?\n  end : real?\n  step : real? = 1```\n\n\nReturns a sequence (that is also a [stream](streams.html#%28tech._stream%29)) whose elements are numbers. The single-argument case ([in-range](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29) end) is equivalent to ([in-range](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29) 0 end 1). The first number in the sequence is start, and each successive element is generated by adding step to the previous element. The sequence stops before an element that would be greater or equal to end if step is non-negative, or less or equal to end if step is negative.\n\nAn [in-range](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29) application can provide better performance for number iteration when it appears directly in a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) clause.\n\nExample: gaussian sum\n\n> ```racket\n> > ( for/sum ( [ x ( in-range 10 ) ] ) x )\n> 45\n> ```\n\nExample: sum of even numbers\n\n> ```racket\n> > ( for/sum ( [ x ( in-range 0 100 2 ) ] ) x )\n> 2450\n> ```\n\nWhen given zero as step, [in-range](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-range%29%29) returns an infinite sequence. It may also return infinite sequences when step is a very small number, and either step or the sequence elements are floating-point numbers.\n\n> ```\n(in-inclusive-range start end [step) → stream?\n  start : real?\n  end : real?\n  step : real? = 1\n```"} {"text": "# 4.17.1 Sequences\nSimilar to in-range, but the sequence stopping condition is changed so that the last element is allowed to be equal to end.\nAn in-inclusive-range application can provide better performance for number iteration when it appears directly in a for clause.\nExamples:\n> ```racket\n> > ( sequence → list ( in-inclusive-range 7 11 ) )\n> '(7 8 9 10 11)\n> > ( sequence → list ( in-inclusive-range 7 11 2 ) )\n> '(7 9 11)\n> > ( sequence → list ( in-inclusive-range 7 10 2 ) )\n> '(7 9)\n> ```\nAdded in version 8.0.0.13 of package base.\n> ```\n(in-naturals [start) → stream?\n  start : exact-nonnegative-integer? = 0```\nReturns an infinite sequence (that is also a [stream](streams.html#%28tech._stream%29)) of exact integers starting with start, where each element is one more than the preceding element.\nAn [in-naturals](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-naturals%29%29) application can provide better performance for integer iteration when it appears directly in a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) clause.\nExample:\n> ```racket\n> > ( for/list ( [ k ( in-naturals ) ] [ x ( in-range 10 ) ] ) ( list k x ) )\n> '((0 0) (1 1) (2 2) (3 3) (4 4) (5 5) (6 6) (7 7) (8 8) (9 9))\n> ```\n> ```\n(in-list lst)  →  stream?\n  lst : list?"} {"text": "# 4.17.1 Sequences\n```\nReturns a sequence (that is also a stream) that is equivalent to using lst directly as a sequence.\n\n> > > See Pairs and Lists for information on using lists as sequences.\n\nAn in-list application can provide better performance for list iteration when it appears directly in a for clause.\n\nSee for for information on the reachability of list elements during an iteration.\n\nExample:\n\n> ```racket\n> > ( for/list ( [ x ( in-list ' ( 3 1 4 ) ) ] ) ` ( , x , ( * x x ) ) )\n> '((3 9) (1 1) (4 16))\n> ```\n\nChanged in version 6.7.0.4 of package base: Improved element-reachability guarantee for lists in for.\n\n> ```\n(in-mlist mlst) → sequence?\n  mlst : mlist?```\n\n\nReturns a sequence equivalent to mlst. Although the expectation is that mlst is [mutable list](mpairs.html#%28tech._mutable._list%29), [in-mlist](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-mlist%29%29) initially checks only whether mlst is a [mutable pair](mpairs.html#%28tech._mutable._pair%29) or [null](pairs.html#%28def._%28%28quote._~23~25kernel%29._null%29%29), since it could change during iteration.\n\n> > > See [Mutable Pairs and Lists](mpairs.html) for information on using mutable lists as sequences.\n\nAn [in-mlist](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-mlist%29%29) application can provide better performance for mutable list iteration when it appears directly in a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) clause.\n\nExample:\n\n> ```racket\n> > ( for/list ( [ x ( in-mlist ( mcons \"RACKET\" ( mcons \"LANG\" ' ( ) ) ) ) ] ) ( string-length x ) )\n> '(6 4)\n> ```\n\n> ```\n(in-vector vec [start stop step) → sequence?\n  vec : vector?\n  start : exact-nonnegative-integer? = 0\n  stop : (or/c exact-integer? #f) = #f\n  step : (and/c exact-integer? (not/c zero?)) = 1\n```"} {"text": "# 4.17.1 Sequences\nReturns a sequence equivalent to vec when no optional arguments are supplied.\n> > > See Vectors for information on using vectors as sequences.\nThe optional arguments start, stop, and step are analogous to in-range, except that a #f value for stop is equivalent to (vector-length vec). That is, the first element in the sequence is (vector-ref vec start), and each successive element is generated by adding step to index of the previous element. The sequence stops before an index that would be greater or equal to end if step is non-negative, or less or equal to end if step is negative.\nIf start is not a valid index, then the exn:fail:contract exception is raised, except when start, stop, and (vector-length vec) are equal, in which case the result is an empty sequence.\nExamples:\n> ```racket\n> > ( for ( [ x ( in-vector ( vector 1 ) 1 ) ] ) x )\n> > ( for ( [ x ( in-vector ( vector 1 ) 2 ) ] ) x )\n> in-vector: starting index is out of range\n> starting index: 2\n> valid range: [0, 0]\n> vector: '#(1)\n> > ( for ( [ x ( in-vector ( vector ) 0 0 ) ] ) x )\n> > ( for ( [ x ( in-vector ( vector 1 ) 1 1 ) ] ) x )\n> ```\nIf stop is not in \\[-1, (vector-length vec)\\], then the exn:fail:contract exception is raised.\nIf start is less than stop and step is negative, then the exn:fail:contract exception is raised. Similarly, if start is more than stop and step is positive, then the exn:fail:contract exception is raised.\nAn in-vector application can provide better performance for vector iteration when it appears directly in a for clause.\nExamples:"} {"text": "# 4.17.1 Sequences\n> ```racket\n> > ( define ( histogram vector-of-words ) ( define a-hash ( make-hash ) ) ( for ( [ word ( in-vector vector-of-words ) ] ) ( hash-set! a-hash word ( add1 ( hash-ref a-hash word 0 ) ) ) ) a-hash )\n> > ( histogram # ( \"hello\" \"world\" \"hello\" \"sunshine\" ) )\n> '#hash((\"hello\" . 2) (\"sunshine\" . 1) (\"world\" . 1))\n> ```\n> ```\n(in-string str [start stop step) → sequence?\n  str : string?\n  start : exact-nonnegative-integer? = 0\n  stop : (or/c exact-integer? #f) = #f\n  step : (and/c exact-integer? (not/c zero?)) = 1```\nReturns a sequence equivalent to str when no optional arguments are supplied.\n> > > See [Strings](strings.html) for information on using strings as sequences.\nThe optional arguments start, stop, and step are as in [in-vector](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-vector%29%29).\nAn [in-string](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-string%29%29) application can provide better performance for string iteration when it appears directly in a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) clause.\nExamples:\n> ```racket\n> > ( define ( line-count str ) ( for/sum ( [ ch ( in-string str ) ] ) ( if ( char=? #\\newline ch ) 1 0 ) ) )\n> > ( line-count \"this string\\nhas\\nthree \\nnewlines\" )\n> 3\n> ```\n> ```\n(in-bytes bstr [start stop step) → sequence?\n  bstr : bytes?\n  start : exact-nonnegative-integer? = 0\n  stop : (or/c exact-integer? #f) = #f\n  step : (and/c exact-integer? (not/c zero?)) = 1"} {"text": "# 4.17.1 Sequences\n```\n(current-input-port)\t→\t\n(-> input-port? . → . any/c)```\n\n\nReturns a sequence whose elements are produced by calling r on in until it produces [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29).\n\n> ```\n(in-input-port-bytes in)  →  sequence?\n  in : input-port?\n```\nReturns a sequence equivalent to (in-port read-byte in).\n> ```\n(in-input-port-chars in)  →  sequence?\n  in : input-port?```\nReturns a sequence whose elements are read as characters from in (equivalent to ([in-port](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-port%29%29) [read-char](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-char%29%29) in)).\n> ```\n(current-input-port)\t→\t\n(-> current-input-port)\n```\n(p)\t→\t\n(-> current-input-port)```\n\n\nReturns a sequence equivalent to ([in-port](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-port%29%29) ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) (p) ([read-bytes-line](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-bytes-line%29%29) p mode)) in). Note that the default mode is 'any, whereas the default mode of [read-bytes-line](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-bytes-line%29%29) is 'linefeed.\n\n> ```\n(in-hash hash)  →  sequence?\n  hash : hash?\n(in-hash hash bad-index-v)  →  sequence?\n  hash : hash?\n  bad-index-v : any/c\n```\nReturns a sequence equivalent to hash, except when bad-index-v is supplied."} {"text": "# 4.17.1 Sequences\nLike hash-map, iteration via in-hash can adapt to certain modifications to a mutable hash table while a traversal is in progress. Keys removes or remapped by the traversing thread have no immediate adverse affects; the change does not affect a traversal if the key has been seen already, otherwise the traversal skips a deleted key or uses the remapped key’s new value.\nOther concurrent modifications, including key removal by a different thread, can lead to skipped entries or an exception if an expected entry key was removed before its key or value could be fetched. If bad-index-v is supplied, then bad-index-v is returned as both the key and the value in the case that the hash is modified concurrently so that iteration does not have a valid hash index. Providing bad-index-v is particularly useful when iterating through a hash table with weakly held keys, since entries can be removed asynchronously (i.e., after in-hash has committed to another iteration, but before it can access the entry for the next iteration).\nExamples:\n> ```racket\n> > ( define table ( hash ' a 1 ' b 2 ) )\n> > ( for ( [ ( key value ) ( in-hash table ) ] ) ( printf \"key: ~a value: ~a\\n\" key value ) )\n> key: b value: 2 key: a value: 1\n> ```\n> > > See Hash Tables for information on using hash tables as sequences.\nChanged in version 7.0.0.10 of package base: Added the optional bad-index-v argument. \nChanged in version 8.18.0.11: Strengthened the guarantees about traversal with same-thread modifications to a mutable hash table.\n> ```"} {"text": "# 4.17.1 Sequences\n(in-hash-keys hash) → sequence?\n  hash : hash?\n(in-hash-keys hash bad-index-v)  →  sequence?\n  hash : hash?\n  bad-index-v : any/c```\nReturns a sequence whose elements are the keys of hash, using bad-index-v in the same way as [in-hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash%29%29), and with concurrent-modification guarantees analogous to those of [in-hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash%29%29).\nExamples:\n> ```racket\n> > ( define table ( hash ' a 1 ' b 2 ) )\n> > ( for ( [ key ( in-hash-keys table ) ] ) ( printf \"key: ~a\\n\" key ) )\n> key: b key: a\n> ```\nChanged in version 7.0.0.10 of package base: Added the optional bad-index-v argument. \nChanged in version 8.18.0.11: Strengthened the guarantees about traversal with same-thread modifications to a mutable hash table.\n> ```\n(in-hash-values hash)  →  sequence?\n  hash : hash?\n(in-hash-values hash bad-index-v)  →  sequence?\n  hash : hash?\n  bad-index-v : any/c"} {"text": "# 4.17.1 Sequences\n```\nReturns a sequence whose elements are the values of hash, using bad-index-v in the same way as in-hash, and with concurrent-modification guarantees analogous to those of in-hash.\n\nExamples:\n\n> ```racket\n> > ( define table ( hash ' a 1 ' b 2 ) )\n> > ( for ( [ value ( in-hash-values table ) ] ) ( printf \"value: ~a\\n\" value ) )\n> value: 2 value: 1\n> ```\n\nChanged in version 7.0.0.10 of package base: Added the optional bad-index-v argument. \nChanged in version 8.18.0.11: Strengthened the guarantees about traversal with same-thread modifications to a mutable hash table.\n\n> ```\n(in-hash-pairs hash) → sequence?\n  hash : hash?\n(in-hash-pairs hash bad-index-v)  →  sequence?\n  hash : hash?\n  bad-index-v : any/c```\n\n\nReturns a sequence whose elements are pairs, each containing a key and its value from hash (as opposed to using hash directly as a sequence to get the key and value as separate values for each element).\n\nThe bad-index-v argument, if supplied, is used in the same way as by [in-hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash%29%29). When an invalid index is encountered, the pair in the sequence with have bad-index-v as both its [car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) and [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29). The concurrent-modification guarantees for [in-hash-pairs](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash-pairs%29%29) are analogous to those of [in-hash](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-hash%29%29).\n\nExamples:\n\n> ```racket\n> > ( define table ( hash ' a 1 ' b 2 ) )\n> > ( for ( [ key+value ( in-hash-pairs table ) ] ) ( printf \"key and value: ~a\\n\" key+value ) )\n> key and value: (b . 2) key and value: (a . 1)\n> ```\n\nChanged in version 7.0.0.10 of package base: Added the optional bad-index-v argument. \nChanged in version 8.18.0.11: Strengthened the guarantees about traversal with same-thread modifications to a mutable hash table.\n\n> ```\n(in-mutable-hash hash)  →  sequence?\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n\n(in-mutable-hash hash bad-index-v)  →  sequence?\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  bad-index-v : any/c\n\n(in-mutable-hash-keys hash)  →  sequence?\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n\n(in-mutable-hash-keys hash bad-index-v)  →  sequence?\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  bad-index-v : any/c\n\n(in-mutable-hash-values hash)  →  sequence?\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n\n(in-mutable-hash-values hash bad-index-v)  →  sequence?\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  bad-index-v : any/c\n\n(in-mutable-hash-pairs hash)  →  sequence?\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n\n(in-mutable-hash-pairs hash bad-index-v)  →  sequence?\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  bad-index-v : any/c\n\n(in-immutable-hash hash)  →  sequence?\n  hash : (and/c hash? immutable?)\n\n(in-immutable-hash hash bad-index-v)  →  sequence?\n  hash : (and/c hash? immutable?)\n  bad-index-v : any/c\n\n(in-immutable-hash-keys hash)  →  sequence?\n  hash : (and/c hash? immutable?)\n\n(in-immutable-hash-keys hash bad-index-v)  →  sequence?\n  hash : (and/c hash? immutable?)\n  bad-index-v : any/c\n\n(in-immutable-hash-values hash)  →  sequence?\n  hash : (and/c hash? immutable?)\n\n(in-immutable-hash-values hash bad-index-v)  →  sequence?\n  hash : (and/c hash? immutable?)\n  bad-index-v : any/c\n\n(in-immutable-hash-pairs hash)  →  sequence?\n  hash : (and/c hash? immutable?)\n\n(in-immutable-hash-pairs hash bad-index-v)  →  sequence?\n  hash : (and/c hash? immutable?)\n  bad-index-v : any/c\n\n(in-weak-hash hash)  →  sequence?\n  hash : (and/c hash? hash-weak?)\n\n(in-weak-hash hash bad-index-v)  →  sequence?\n  hash : (and/c hash? hash-weak?)\n  bad-index-v : any/c\n\n(in-weak-hash-keys hash)  →  sequence?\n  hash : (and/c hash? hash-weak?)\n\n(in-weak-hash-keys hash bad-index-v)  →  sequence?\n  hash : (and/c hash? hash-weak?)\n  bad-index-v : any/c\n\n(in-weak-hash-values hash)  →  sequence?\n  hash : (and/c hash? hash-weak?)\n\n(in-weak-hash-keys hash bad-index-v)  →  sequence?\n  hash : (and/c hash? hash-weak?)\n  bad-index-v : any/c\n\n(in-weak-hash-pairs hash)  →  sequence?\n  hash : (and/c hash? hash-weak?)\n\n(in-weak-hash-pairs hash bad-index-v)  →  sequence?\n  hash : (and/c hash? hash-weak?)\n  bad-index-v : any/c\n\n(in-ephemeron-hash hash)  →  sequence?\n  hash : (and/c hash? hash-ephemeron?)\n\n(in-ephemeron-hash hash bad-index-v)  →  sequence?\n  hash : (and/c hash? hash-ephemeron?)\n  bad-index-v : any/c\n\n(in-ephemeron-hash-keys hash)  →  sequence?\n  hash : (and/c hash? hash-ephemeron?)\n\n(in-ephemeron-hash-keys hash bad-index-v)  →  sequence?\n  hash : (and/c hash? hash-ephemeron?)\n  bad-index-v : any/c\n\n(in-ephemeron-hash-values hash)  →  sequence?\n  hash : (and/c hash? hash-ephemeron?)\n\n(in-ephemeron-hash-keys hash bad-index-v)  →  sequence?\n  hash : (and/c hash? hash-ephemeron?)\n  bad-index-v : any/c\n\n(in-ephemeron-hash-pairs hash)  →  sequence?\n  hash : (and/c hash? hash-ephemeron?)\n\n(in-ephemeron-hash-pairs hash bad-index-v)  →  sequence?\n  hash : (and/c hash? hash-ephemeron?)\n  bad-index-v : any/c\n```"} {"text": "# 4.17.1 Sequences\nSequence constructors for specific kinds of hash tables. These may perform better than the analogous in-hash forms.\nAdded in version 6.4.0.6 of package base. \nChanged in version 7.0.0.10: Added the optional bad-index-v argument. \nChanged in version 8.0.0.10: Added ephemeron variants.\n> ```\n(in-directory [dir use-dir?) → (sequence/c path?)\n  dir : (or/c #f path-string?) = #f\n   use-dir?   :   ((and/c path? complete-path?) . → . any/c)\n      =   (lambda (dir-path) #t)```\nReturns a sequence that produces all of the paths for files, directories, and links within dir, except for the contents of any directory for which use-dir? returns #f. If dir is not #f, then every produced path starts with dir as its prefix. If dir is #f, then paths in and relative to the current directory are produced.\nAn [in-directory](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-directory%29%29) sequence traverses nested subdirectories recursively (filtered by use-dir?). To generate a sequence that includes only the immediate content of a directory, use the result of [directory-list](Filesystem.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._directory-list%29%29) as a sequence.\nThe immediate content of each directory is reported as sorted by [path ```racket\n> > ( current-directory ( path-only ( collection-file-path \"main.rkt\" \"info\" ) ) )\n> > ( for/list ( [ f ( in-directory ) ] ) f )\n> '(# # # #)\n> > ( for/list ( [ f ( in-directory \"compiled\" ) ] ) f )\n> '(# #)\n> > ( for/list ( [ f ( in-directory #f ( lambda ( p ) ( not ( regexp-match? #rx\"compiled\" p ) ) ) ) ] ) f )\n> '(# #)\n> ```\nChanged in version 6.0.0.1 of package base: Added use-dir? argument. \nChanged in version 6.6.0.4: Added guarantee of sorted results.\n> ```\n(in-producer producer) → sequence?\n  producer : procedure?\n(in-producer producer stop arg ...)  →  sequence?\n  producer : procedure?\n  stop : any/c\n  arg : any/c"} {"text": "# 4.17.1 Sequences\n```\nReturns a sequence that contains values from sequential calls to producer, which would usually use some state to do its work.\n\nIf a stop value is not given, the sequence goes on infinitely, and therefore it is common to use it with a finite sequence or using #:break etc. If a stop value is given, it is used to identify a value that marks the end of the sequence (and the stop value is not included in the sequence); stop can be a predicate that is applied to the results of producer, or it can be a value that is tested against the result of with eq?. (The stop argument must be a predicate if the stop value is itself a function or if producer returns multiple values.)\n\nIf additional args are specified, they are passed to every call to producer.\n\nExamples:\n\n> ```racket\n> > ( define ( counter ) ( define n 0 ) ( lambda ( [ d 1 ] ) ( set! n ( + d n ) ) n ) )\n> > ( for/list ( [ x ( in-producer ( counter ) ) ] [ y ( in-range 4 ) ] ) x )\n> '(1 2 3 4)\n> > ( for/list ( [ x ( in-producer ( counter ) ) ] #:break ( = x 5 ) ) x )\n> '(1 2 3 4)\n> > ( for/list ( [ x ( in-producer ( counter ) 5 ) ] ) x )\n> '(1 2 3 4)\n> > ( for/list ( [ x ( in-producer ( counter ) 5 1/2 ) ] ) x )\n> '(1/2 1 3/2 2 5/2 3 7/2 4 9/2)\n> > ( for/list ( [ x ( in-producer read eof ( open-input-string \"1 2 3\" ) ) ] ) x )\n> '(1 2 3)\n> ```\n\n> ```\n(in-value v) → sequence?\n  v : any/c```\n\n\nReturns a sequence that produces a single value: v.\n\nThis form is mostly useful for [let](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%29%29)-like bindings in forms such as [for*/list](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%2Flist%29%29)—but a #:do clause form, added more recently, covers many of the same uses.\n\n> ```\n(in-indexed seq)  →  sequence?\n  seq : sequence?\n```"} {"text": "# 4.17.1 Sequences\nReturns a sequence where each element has two values: the value produced by seq, and a non-negative exact integer starting with 0. The elements of seq must be single-valued.\nExample:\n> ```racket\n> > ( for ( [ ( ch i ) ( in-indexed \"hello\" ) ] ) ( printf \"The char at position ~a is: ~a\\n\" i ch ) )\n> The char at position 0 is: h The char at position 1 is: e The char at position 2 is: l The char at position 3 is: l The char at position 4 is: o\n> ```\n> ```\n(in-sequences seq ...) → sequence?\n  seq : sequence?```\nReturns a sequence that is made of all input sequences, one after the other. Each seq is [initiate](#%28tech._initiate%29)d only after the preceding seq is exhausted. If a single seq is provided, then seq is returned; otherwise, the elements of each seq must all have the same number of values.\n> ```\n(in-cycle seq ...) → sequence?\n  seq : sequence?\n```\nSimilar to in-sequences, but the sequences are repeated in an infinite cycle, where each seq is initiated afresh in each iteration. Beware that if no seqs are provided or if all seqs become empty, then the sequence produced by in-cycle never returns when an element is demanded—or even when the sequence is initiated, if all seqs are initially empty.\n\n> ```\n(in-parallel seq ...) → sequence?\n  seq : sequence?```\n\n\nReturns a sequence where each element has as many values as the number of supplied seqs; the values, in order, are the values of each seq. The elements of each seq must be single-valued.\n\n> ```\n(in-values-sequence seq)  →  sequence?\n  seq : sequence?\n```"} {"text": "# 4.17.1 Sequences\nReturns a sequence that is like seq, but it combines multiple values for each element from seq as a list of elements.\n> ```\n(in-values*-sequence seq)  →  sequence?\n  seq : sequence?\n```\n\n\nReturns a sequence that is like seq, but when an element of seq has multiple values or a single list value, then the values are combined in a list. In other words, [in-values*-sequence](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-values%2A-sequence%29%29) is like [in-values-sequence](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-values-sequence%29%29), except that non-list, single-valued elements are not wrapped in a list.\n\n> ```\n(stop-before seq pred)  →  sequence?\n  seq : sequence?\n  pred : (any/c . → . any)\n```\nReturns a sequence that contains the elements of seq (which must be single-valued), but only until the last element for which applying pred to the element produces #t, after which the sequence ends.\n> ```\n(stop-after seq pred)  →  sequence?\n  seq : sequence?\n  pred : (any/c . → . any)"} {"text": "# 4.17.1 Sequences\n```\n\n\nReturns a sequence that contains the elements of seq (which must be single-valued), but only until the element (inclusive) for which applying pred to the element produces #t, after which the sequence ends.\n\n> ```\n(make-do-sequence thunk) → sequence?\n   thunk   :   ( or/c ( → ( values ( any/c . → . any )\n> ( any/c . → . any/c )\n> any/c\n> ( or/c ( any/c . → . any/c ) #f )\n> ( or/c ( any/c ... . → . any/c ) #f )\n> ( or/c ( any/c any/c ... . → . any/c ) #f ) ) )\n> ( → ( values ( any/c . → . any )\n> ( or/c ( any/c . → . any/c ) #f )\n> ( any/c . → . any/c )\n> any/c\n> ( or/c ( any/c . → . any/c ) #f )\n> ( or/c ( any/c ... . → . any/c ) #f )\n> ( or/c ( any/c any/c ... . → . any/c ) #f ) ) ) )\n```\nReturns a sequence whose elements are generated according to thunk.\nThe sequence is initiated when thunk is called. The initiated sequence is defined in terms of a position, which is initialized to init-pos, and the element, which may consist of multiple values.\nThe thunk procedure must return either six or seven values. However, use initiate-sequence to return these multiple values, as opposed to listing the values directly.\nIf thunk returns six values:\n- The first result is a pos → element procedure that takes the current position and returns the value(s) for the current element.\n- The second result is a next-pos procedure that takes the current position and returns the next position.\n- The third result is a init-pos value, which is the initial position."} {"text": "# 4.17.1 Sequences\n- The fourth result is a continue-with-pos? function that takes the current position and returns a true result if the sequence includes the value(s) for the current position, and false if the sequence should end instead of including the value(s). Alternatively, continue-with-pos? can be #f to indicate that the sequence should always include the current value(s). This function is checked on each position before pos → element is used.\n- The fifth result is a continue-with-val? function that is like continue-with-pos?, but it takes the current element value(s) as arguments instead of the current position. Alternatively, continue-with-val? can be #f to indicate that the sequence should always include the value(s) at the current position.\n- The sixth result is a continue-after-pos+val? procedure that takes both the current position and the current element value(s) and determines whether the sequence ends after the current element is already included in the sequence. Alternatively, continue-after-pos+val? can be #f to indicate that the sequence can always continue after the current value(s).\nIf thunk returns seven values, the first result is still the pos → element procedure. However, the second result is now an early-next-pos procedure that is described further below. Alternatively, early-next-pos can be #f, which is equivalent to the identity function. Other results’ positions are shifted by one, so the third result is now next-pos, and the fourth result is now init-pos, etc."} {"text": "# 4.17.1 Sequences\nThe early-next-pos procedure takes the current position and returns an updated position. This updated position is used for next-pos and continue-after-pos+val?, but not with continue-with-pos? (which uses the original current position). The intent of early-next-pos is to support a sequence where the position must be incremented to avoid keeping a value reachable while a loop processes the sequence value, so early-next-pos is applied just after pos → element. The continue-after-pos+val? function needs to be #f to avoid retaining values to supply to that function.\nEach of the procedures listed above is called only once per position. Among the procedures continue-with-pos?, continue-with-val?, and continue-after-pos+val?, as soon as one of the procedures returns #f, the sequence ends, and none are called again. Typically, one of the functions determines the end condition, and #f is used in place of the other two functions.\nChanged in version 6.7.0.4 of package base: Added support for the optional second result.\n>
\n

value

\n

prop:sequence : struct-type-property?

\nAssociates a procedure to a structure type that takes an instance of the structure and returns a sequence. If v is an instance of a structure type with this property, then (sequence? v) produces #t.\nUsing a pre-existing sequence:\nExamples:"} {"text": "# 4.17.1 Sequences\n> ```racket\n> > ( struct my-set ( table ) #:property prop:sequence ( lambda ( s ) ( in-hash-keys ( my-set-table s ) ) ) )\n> > ( define ( make-set . xs ) ( my-set ( for/hash ( [ x ( in-list xs ) ] ) ( values x #t ) ) ) )\n> > ( for/list ( [ c ( make-set ' celeriac ' carrot ' potato ) ] ) c )\n> '(potato celeriac carrot)\n> ```\nUsing make-do-sequence:\nExamples:\n> ```racket\n> > ( require racket/sequence )\n> > ( struct train ( car next ) #:property prop:sequence ( lambda ( t ) ( make-do-sequence ( lambda ( ) ( initiate-sequence #:pos → element train-car #:next-pos train-next #:init-pos t #:continue-with-pos? ( lambda ( t ) t ) ) ) ) ) )\n> > ( for/list ( [ c ( train ' engine ( train ' boxcar ( train ' caboose #f ) ) ) ] ) c )\n> '(engine boxcar caboose)\n> ```"} {"text": "##### 4.17.1.2 Sequence Conversion\n> ```\n(sequence → stream seq) → stream?\n  seq : sequence?```\nConverts a sequence to a [stream](streams.html#%28tech._stream%29), which supports the [stream-first](streams.html#%28def._%28%28lib._racket%2Fstream..rkt%29._stream-first%29%29) and [stream-rest](streams.html#%28def._%28%28lib._racket%2Fstream..rkt%29._stream-rest%29%29) operations. Creation of the stream eagerly [initiates](#%28tech._initiate%29) the sequence, but the stream lazily draws elements from the sequence, caching each element so that [stream-first](streams.html#%28def._%28%28lib._racket%2Fstream..rkt%29._stream-first%29%29) produces the same result each time is applied to a stream.\nIf extracting an element from seq involves a side-effect, then the effect is performed each time that either [stream-first](streams.html#%28def._%28%28lib._racket%2Fstream..rkt%29._stream-first%29%29) or [stream-rest](streams.html#%28def._%28%28lib._racket%2Fstream..rkt%29._stream-rest%29%29) is first used to access or skip an element.\nNote that a [sequence itself can have state](#%28elem._sequence-state%29), so multiple calls to [sequence->stream](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-~3estream%29%29) on the same seq are not necessarily independent.\nExamples:"} {"text": "# 4.17.1 Sequences\n> ```racket\n> > ( define inport ( open-input-bytes ( bytes 1 2 3 4 5 ) ) )\n> > ( define strm ( sequence->stream inport ) )\n> > ( stream-first strm )\n> 1\n> > ( stream-first ( stream-rest strm ) )\n> 2\n> > ( stream-first strm )\n> 1\n> > ( define strm2 ( sequence->stream inport ) )\n> > ( stream-first strm2 )\n> 3\n> > ( stream-first ( stream-rest strm2 ) )\n> 4\n> ```\n> ```\n(sequence-generate seq)   →   ( →  boolean?)   ( →  any)\n  seq : sequence?\n```\nInitiates a sequence and returns two thunks to extract elements from the sequence. The first returns #t if more values are available for the sequence. The second returns the next element (which may be multiple values) from the sequence; if no more elements are available, the exn:fail:contract exception is raised.\n\nNote that a sequence itself can have state, so multiple calls to sequence-generate on the same seq are not necessarily independent.\n\nExamples:\n\n> ```racket\n> > ( define inport ( open-input-bytes ( bytes 1 2 3 4 5 ) ) )\n> > ( define-values ( more? get ) ( sequence-generate inport ) )\n> > ( more? )\n> #t\n> > ( get )\n> 1\n> > ( get )\n> 2\n> > ( define-values ( more2? get2 ) ( sequence-generate inport ) )\n> > ( list ( get2 ) ( get2 ) ( get2 ) )\n> '(3 4 5)\n> > ( more2? )\n> #f\n> ```\n\n> ```\n(sequence-generate* seq)\n  →   (or/c list? #f)\n( →  (values (or/c list? #f) procedure?))\n\n  seq : sequence?```\n\n\nLike [sequence-generate](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-generate%29%29), but avoids state (aside from any inherent in the sequence) by returning a list of values for the sequence’s first element—or #f if the sequence is empty—and a thunk to continue with the sequence; the result of the thunk is the same as the result of [sequence-generate*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence-generate%2A%29%29), but for the second element of the sequence, and so on. If the thunk is called when the element result is #f (indicating no further values in the sequence), the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\n##### 4.17.1.3 Additional Sequence Operations\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/sequence](#%28mod-path._racket%2Fsequence%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/sequence](#%28mod-path._racket%2Fsequence%29) and [racket](index.html) libraries, but not [racket/base](index.html).\n\n>
\n\n

value

\n\n

[empty-sequence](#%28def._%28%28lib._racket%2Fsequence..rkt%29._empty-sequence%29%29) : [sequence?](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._sequence~3f%29%29)

\n\nA sequence with no elements.\n\n> ```\n(sequence → list s)  →  list?\n  s : sequence?\n```"} {"text": "# 4.17.1 Sequences\nReturns a list whose elements are the elements of s, each of which must be a single value. If s is infinite, this function does not terminate.\n> ```\n(sequence-length s)  →  exact-nonnegative-integer?\n  s : sequence?\n```\n\n\nReturns the number of elements of s by extracting and discarding all of them. If s is infinite, this function does not terminate.\n\n> ```\n(sequence-ref s i)  →  any\n  s : sequence?\n  i : exact-nonnegative-integer?\n```\nReturns the ith element of s (which may be multiple values).\n> ```\n(sequence-tail s i)  →  sequence?\n  s : sequence?\n  i : exact-nonnegative-integer?\n```\n\n\nReturns a sequence equivalent to s, except that the first i elements are omitted.\n\nIn case [initiating](#%28tech._initiate%29) s involves a side effect, the sequence s is not [initiate](#%28tech._initiate%29)d until the resulting sequence is [initiate](#%28tech._initiate%29)d, at which point the first i elements are extracted from the sequence.\n\n> ```\n(sequence-append s ...) → sequence?\n  s : sequence?\n```\nReturns a sequence that contains all elements of each sequence in the order they appear in the original sequences. The new sequence is constructed lazily.\nIf all given ss are streams, the result is also a stream.\n> ```\n(sequence-map f s)  →  sequence?\n  f : procedure?\n  s : sequence?```\nReturns a sequence that contains f applied to each element of s. The new sequence is constructed lazily.\nIf s is a [stream](streams.html#%28tech._stream%29), then the result is also a [stream](streams.html#%28tech._stream%29).\n> ```"} {"text": "# 4.17.1 Sequences\n(sequence-andmap f s) → boolean?\n  f : ( →  any/c ... boolean?)\n  s : sequence?\n```\nReturns #t if f returns a true result on every element of s. If s is infinite and f never returns a false result, this function does not terminate.\n\n> ```\n(sequence-ormap f s) → boolean?\n  f : ( →  any/c ... boolean?)\n  s : sequence?```\n\n\nReturns #t if f returns a true result on some element of s. If s is infinite and f never returns a true result, this function does not terminate.\n\n> ```\n(parameter)\t→\t\n(-> any/c ... any)\n```\nApplies f to each element of s. If s is infinite, this function does not terminate.\n> ```\n(sequence-fold f i s) → any/c\n  f : ( →  any/c any/c ... any/c)\n  i : any/c\n  s : sequence?```\nFolds f over each element of s with i as the initial accumulator. If s is infinite, this function does not terminate. The f function takes the accumulator as its first argument and the next sequence element as its second.\n> ```\n(sequence-count f s)  →  exact-nonnegative-integer?\n  f : procedure?\n  s : sequence?"} {"text": "# 4.17.1 Sequences\n```\nReturns the number of elements in s for which f returns a true result. If s is infinite, this function does not terminate.\n\n> ```\n(sequence-filter f s) → sequence?\n  f : ( →  any/c ... boolean?)\n  s : sequence?```\n\n\nReturns a sequence whose elements are the elements of s for which f returns a true result. Although the new sequence is constructed lazily, if s has an infinite number of elements where f returns a false result in between two elements where f returns a true result, then operations on this sequence will not terminate during the infinite sub-sequence.\n\nIf s is a [stream](streams.html#%28tech._stream%29), then the result is also a [stream](streams.html#%28tech._stream%29).\n\n> ```\n(sequence-add-between s e)  →  sequence?\n  s : sequence?\n  e : any/c\n```\nReturns a sequence whose elements are the elements of s, but with e between each pair of elements in s. The new sequence is constructed lazily.\nIf s is a stream, then the result is also a stream.\nExamples:\n> ```racket\n> > ( let* ( [ all-reds ( in-cycle ' ( \"red\" ) ) ] [ red-and-blues ( sequence-add-between all-reds \"blue\" ) ] ) ( for/list ( [ n ( in-range 10 ) ] [ elt red-and-blues ] ) elt ) )\n> '(\"red\" \"blue\" \"red\" \"blue\" \"red\" \"blue\" \"red\" \"blue\" \"red\" \"blue\")\n> > ( for ( [ text ( sequence-add-between ' ( \"veni\" \"vidi\" \"duci\" ) \", \" ) ] ) ( display text ) )\n> veni, vidi, duci\n> ```\n> ```\n(sequence/c [#:min-count min-count]\n    elem/c ...)   →   contract?\n  min-count : (or/c #f exact-nonnegative-integer?) = #f\n  elem/c : contract?```"} {"text": "# 4.17.1 Sequences\nWraps a [sequence](#%28tech._sequence%29), obligating it to produce elements with as many values as there are elem/c contracts, and obligating each value to satisfy the corresponding elem/c. The result is not guaranteed to be the same kind of sequence as the original value; for instance, a wrapped list is not guaranteed to satisfy [list?](pairs.html#%28def._%28%28quote._~23~25kernel%29._list~3f%29%29).\nIf min-count is a number, the stream is required to have at least that many elements in it.\nExamples:\n> ```racket\n> > ( define/contract predicates ( sequence/c ( -> any/c boolean? ) ) ( in-list ( list integer? string->symbol ) ) )\n> > ( for ( [ P predicates ] ) ( printf \"~s\\n\" ( P \"cat\" ) ) )\n> #f\n> predicates: broke its own contract\n> promised: boolean?\n> produced: 'cat\n> in: an element of\n> (sequence/c (-> any/c boolean?))\n> contract from: (definition predicates)\n> blaming: (definition predicates)\n> (assuming the contract is correct)\n> at: eval:55:0\n> > ( define/contract numbers&strings ( sequence/c number? string? ) ( in-dict ( list ( cons 1 \"one\" ) ( cons 2 \"two\" ) ( cons 3 ' three ) ) ) )\n> > ( for ( [ ( N S ) numbers&strings ] ) ( printf \"~s: ~a\\n\" N S ) )\n> 1: one 2: two\n> numbers&strings: broke its own contract\n> promised: string?\n> produced: 'three\n> in: an element of\n> (sequence/c number? string?)\n> contract from: (definition numbers&strings)\n> blaming: (definition numbers&strings)\n> (assuming the contract is correct)\n> at: eval:57:0\n> > ( define/contract a-sequence ( sequence/c #:min-count 2 char? ) \"x\" )\n> > ( for ( [ x a-sequence ] [ i ( in-naturals ) ] ) ( printf \"~a is ~a\\n\" i x ) )\n> 0 is x\n> a-sequence: broke its own contract\n> promised: a sequence that contains at least 2 values\n> produced: \"x\"\n> in: (sequence/c #:min-count 2 char?)\n> contract from: (definition a-sequence)\n> blaming: (definition a-sequence)\n> (assuming the contract is correct)\n> at: eval:59:0\n> ```"} {"text": "##### 4.17.1.3.1 Additional Sequence Constructors and Functions\n> ```\n(in-syntax stx)  →  sequence?\n  stx : syntax?\n```\nProduces a sequence whose elements are the successive subparts of stx. Equivalent to (stx → list lst).\n\nAn in-syntax application can provide better performance for syntax iteration when it appears directly in a for clause.\n\nExample:\n\n> ```racket\n> > ( for/list ( [ x ( in-syntax #' ( 1 2 3 ) ) ] ) x )\n> '(# # #)\n> ```\n\nAdded in version 6.3 of package base.\n\n> ```\n(in-slice length seq) → sequence?\n  length : exact-positive-integer?\n  seq : sequence?```\n\n\nReturns a sequence whose elements are lists with the first length elements of seq, then the next length and so on.\n\nExample:\n\n> ```racket\n> > ( for/list ( [ e ( in-slice 3 ( in-range 8 ) ) ] ) e )\n> '((0 1 2) (3 4 5) (6 7))\n> ```\n\nAdded in version 6.3 of package base.\n\n> ```\n(initiate-sequence\n    #:pos → element pos → element  \n   [ #:early-next-pos early-next-pos]  \n    #:next-pos next-pos  \n    #:init-pos init-pos  \n   [ #:continue-with-pos? continue-with-pos?  \n    #:continue-with-val? continue-with-val?  \n    #:continue-after-pos+val? continue-after-pos+val?)  \n\n  →   (any/c . → . any)\n(or/c (any/c . → . any) #f)\n(any/c . → . any/c)\nany/c\n(or/c (any/c . → . any/c) #f)\n(or/c (any/c ... . → . any/c) #f)\n(or/c (any/c any/c ... . → . any/c) #f)\n\n  pos → element : (any/c . → . any)\n  early-next-pos : (or/c (any/c . → . any) #f) = #f\n  next-pos : (any/c . → . any/c)\n  init-pos : any/c\n  continue-with-pos? : (or/c (any/c . → . any/c) #f) = #f\n  continue-with-val? : (or/c (any/c ... . → . any/c) #f) = #f\n   continue-after-pos+val?   :   (or/c (any/c any/c ... . → . any/c) #f)\n      =   #f\n```"} {"text": "# 4.17.1 Sequences\nReturns values suitable for the thunk argument in make-do-sequence. See make-do-sequence for the meaning of each argument.\nExamples:\n> ```racket\n> > ( define ( in-alt-list xs ) ( make-do-sequence ( λ ( ) ( initiate-sequence #:pos → element car #:next-pos ( λ ( xs ) ( cdr ( cdr xs ) ) ) #:init-pos xs #:continue-with-pos? pair? #:continue-after-pos+val? ( λ ( xs _ ) ( pair? ( cdr xs ) ) ) ) ) ) )\n> > ( sequence → list ( in-alt-list ' ( 1 2 3 4 5 6 ) ) )\n> '(1 3 5)\n> > ( sequence → list ( in-alt-list ' ( 1 2 3 4 5 6 7 ) ) )\n> '(1 3 5 7)\n> ```\nAdded in version 8.10.0.5 of package base.\n------------------------------------------------------------------------"} {"text": "# 4.17.2 Streams"} {"text": "#### 4.17.2 Streams\nA stream is a kind of sequence that supports functional iteration via stream-first and stream-rest. The stream-cons form constructs a lazy stream, but plain lists can be used as streams, and functions such as in-range and in-naturals also create streams.\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/stream]()) |  package: base |\nThe bindings documented in this section are provided by the [racket/stream]() and racket libraries, but not racket/base.\n> ```\n(stream? v) → boolean?\n  v : any/c```\nReturns #t if v can be used as a [stream](#%28tech._stream%29), #f otherwise.\n> ```\n(stream-empty? s)  →  boolean?\n  s : stream?\n```\n\n\nReturns #t if s has no elements, #f otherwise.\n\n> ```\n(stream-first s)  →  any\n  s : (and/c stream? (not/c stream-empty?))\n```\nReturns the value(s) of the first element in s.\n> ```\n(stream-rest s)  →  stream?\n  s : (and/c stream? (not/c stream-empty?))"} {"text": "# 4.17.2 Streams\n```\nReturns a stream that is equivalent to s without its first element.\n\n>
\n\n

syntax

\n\n

(stream-cons first-expr rest-expr)

(stream-cons #:eager first-expr rest-expr)
(stream-cons first-expr #:eager rest-expr)
(stream-cons #:eager first-expr #:eager rest-expr)
\n\nProduces a stream whose first element is determined by first-expr and whose rest is determined by rest-expr.\n\nIf first-expr is not preceded by #:eager, then first-expr is not evaluated immediately. Instead, stream-first on the result stream forces the evaluation of first-expr (once) to produce the first element of the stream. If evaluating first-expr raises an exception or tries to force itself, then an exn:fail:contract exception is raised, and future attempts to force evaluation will trigger another exception.\n\nIf rest-expr is not preceded by #:eager, then rest-expr is not evaluated immediately. Instead, stream-rest on the result stream produces another stream that is like the one produced by (stream-lazy rest-expr).\n\nThe first element of the stream as produced by first-expr can be multiple values. The rest-expr must produce a stream when it is evaluated, otherwise the exn:fail:contract? exception is raised.\n\nChanged in version 8.0.0.12 of package base: Added #:eager options. \nChanged in version 8.8.0.7: Changed to allow multiple values.\n\n>
\n\n

syntax

\n\n

(stream-lazy stream-expr)

(stream-lazy #:who who-expr stream-expr)
\n\nSimilar to (delay stream-expr), but the result is a stream instead of a promise, and stream-expr must produce a stream when it is eventually forced. The stream produced by stream-lazy has the same content as the stream produced by stream-expr; that is, operations like stream-first on the result stream will force stream-expr and retry on its result.\n\nIf evaluating stream-expr raises an exception or tries to force itself, then an exn:fail:contract exception is raised, and future attempts to force evaluation will trigger another exception.\n\nIf who-expr is provided, it is evaluated when constructing the delayed stream. If stream-expr later produces a value that is not a stream, and if who-expr produced a symbol value, then the symbol is used for the error message.\n\nAdded in version 8.0.0.12 of package base.\n\n> ```\n(stream-force s) → stream?\n  s : stream?```\n\n\nForces the evaluation of a delayed stream from [stream-lazy](#%28form._%28%28lib._racket%2Fstream..rkt%29._stream-lazy%29%29), from the [stream-rest](#%28def._%28%28lib._racket%2Fstream..rkt%29._stream-rest%29%29) of a [stream-cons](#%28form._%28%28lib._racket%2Fstream..rkt%29._stream-cons%29%29), etc., returning the forced stream. If s is not a delayed stream, then s is returned.\n\nNormally, [stream-force](#%28def._%28%28lib._racket%2Fstream..rkt%29._stream-force%29%29) is not needed, because operations like [stream-first](#%28def._%28%28lib._racket%2Fstream..rkt%29._stream-first%29%29), [stream-rest](#%28def._%28%28lib._racket%2Fstream..rkt%29._stream-rest%29%29), and [stream-empty?](#%28def._%28%28lib._racket%2Fstream..rkt%29._stream-empty~3f%29%29) force a delayed stream as needed. In rare cases, [stream-force](#%28def._%28%28lib._racket%2Fstream..rkt%29._stream-force%29%29) can be useful to reveal the underlying implementation of a stream (e.g., a stream that is an instance of a structure type that has the [prop:stream](#%28def._%28%28lib._racket%2Fstream..rkt%29._prop~3astream%29%29) property).\n\nAdded in version 8.0.0.12 of package base.\n\n>
\n\n

syntax

\n\n

([stream](#%28form._%28%28lib._racket%2Fstream..rkt%29._stream%29%29) elem-expr ...)

 
elem-expr = ([values](values.html#%28def._%28%28quote._~23~25kernel%29._values%29%29) single-expr ...)
  | single-expr
\n\nA shorthand for nested [stream-cons](#%28form._%28%28lib._racket%2Fstream..rkt%29._stream-cons%29%29)es ending with [empty-stream](#%28def._%28%28lib._racket%2Fstream..rkt%29._empty-stream%29%29). As a match pattern, [stream](#%28form._%28%28lib._racket%2Fstream..rkt%29._stream%29%29) matches a stream with as many elements as elem-exprs, and each element must match the corresponding elem-expr pattern. The pattern elem-expr can be ([values](values.html#%28def._%28%28quote._~23~25kernel%29._values%29%29) single-expr [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)), which matches against multiple valued elements in the stream.\n\nChanged in version 8.8.0.7 of package base: Changed to allow multiple values.\n\n>
\n\n

syntax

\n\n

([stream*](#%28form._%28%28lib._racket%2Fstream..rkt%29._stream%2A%29%29) elem-expr ... tail-expr)

\n\nA shorthand for nested [stream-cons](#%28form._%28%28lib._racket%2Fstream..rkt%29._stream-cons%29%29)es, but the tail-expr must produce a stream when it is forced, and that stream is used as the rest of the stream instead of [empty-stream](#%28def._%28%28lib._racket%2Fstream..rkt%29._empty-stream%29%29). Similar to [list*](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%2A%29%29) but for streams. As a match pattern, [stream*](#%28form._%28%28lib._racket%2Fstream..rkt%29._stream%2A%29%29) is similar to a [stream](#%28form._%28%28lib._racket%2Fstream..rkt%29._stream%29%29) pattern, but the tail-expr pattern matches the “rest” of the stream after the last elem-expr.\n\nAdded in version 6.3 of package base. \nChanged in version 8.0.0.12: Changed to delay rest-expr even if zero exprs are provided. \nChanged in version 8.8.0.7: Changed to allow multiple values.\n\n> ```\n(in-stream s)  →  sequence?\n  s : stream?\n```"} {"text": "# 4.17.2 Streams\nReturns a sequence that is equivalent to s.\nAn in-stream application can provide better performance for streams iteration when it appears directly in a for clause.\nSee for for information on the reachability of stream elements during an iteration.\nChanged in version 6.7.0.4 of package base: Improved element-reachability guarantee for streams in for.\n>
\n

value

\n

empty-stream : stream?

\nA stream with no elements.\n> ```\n(stream → list s) → list?\n  s : stream?```\nReturns a list whose elements are the elements of s, each of which must be a single value. If s is infinite, this function does not terminate.\n> ```\n(stream-length s)  →  exact-nonnegative-integer?\n  s : stream?\n```\n\n\nReturns the number of elements of s. If s is infinite, this function does not terminate.\n\nIn the case of lazy streams, this function forces evaluation only of the sub-streams, and not the stream’s elements.\n\n> ```\n(stream-ref s i)  →  any\n  s : stream?\n  i : exact-nonnegative-integer?\n```\nReturns the ith element of s (which may be multiple values).\n> ```\n(stream-tail s i)  →  stream?\n  s : stream?\n  i : exact-nonnegative-integer?"} {"text": "# 4.17.2 Streams\n```\n\n\nReturns a stream equivalent to s, except that the first i elements are omitted.\n\nIn case extracting elements from s involves a side effect, they will not be extracted until the first element is extracted from the resulting stream.\n\n> ```\n(stream-take s i)  →  stream?\n  s : stream?\n  i : exact-nonnegative-integer?\n```\nReturns a stream of the first i elements of s.\n> ```\n(stream-append s ...) → stream?\n  s : stream?\n```\nReturns a stream that contains all elements of each stream in the order they appear in the original streams. The new stream is constructed lazily, while the last given stream is used in the tail of the result.\n\n> ```\n(stream-map f s)  →  stream?\n  f : procedure?\n  s : stream?```\n\n\nReturns a stream that contains f applied to each element of s. The new stream is constructed lazily.\n\n> ```\n(stream-andmap f s) → boolean?\n  f : ( →  any/c ... boolean?)\n  s : stream?\n```\nReturns #t if f returns a true result on every element of s. If s is infinite and f never returns a false result, this function does not terminate.\n> ```\n(stream-ormap f s) → boolean?\n  f : ( →  any/c ... boolean?)\n  s : stream?```\nReturns #t if f returns a true result on some element of s. If s is infinite and f never returns a true result, this function does not terminate.\n> ```\n(parameter)\t→\t\n(-> any/c ... any)"} {"text": "# 4.17.2 Streams\n```\nApplies f to each element of s. If s is infinite, this function does not terminate.\n\n> ```\n(stream-fold f i s) → any/c\n  f : ( →  any/c any/c ... any/c)\n  i : any/c\n  s : stream?```\n\n\nFolds f over each element of s with i as the initial accumulator. If s is infinite, this function does not terminate. The f function takes the accumulator as its first argument and the next stream element as its second.\n\n> ```\n(stream-count f s)  →  exact-nonnegative-integer?\n  f : procedure?\n  s : stream?\n```\nReturns the number of elements in s for which f returns a true result. If s is infinite, this function does not terminate.\n> ```\n(stream-filter f s) → stream?\n  f : ( →  any/c ... boolean?)\n  s : stream?```\nReturns a stream whose elements are the elements of s for which f returns a true result. Although the new stream is constructed lazily, if s has an infinite number of elements where f returns a false result, then operations on this stream will not terminate during the infinite sub-stream.\n> ```\n(stream-add-between s e)  →  stream?\n  s : stream?\n  e : any/c"} {"text": "# 4.17.2 Streams\n```\nReturns a stream whose elements are the elements of s, but with e between each pair of elements in s. The new stream is constructed lazily.\n\n>
\n\n

syntax

\n\n

(for/stream (for-clause ...) body-or-break ... body)

\n\n

syntax

\n\n

(for*/stream (for-clause ...) body-or-break ... body)

\n\nIterates like for/list and for*/list, respectively, but the results are lazily collected into a stream instead of a list.\n\nUnlike most for forms, these forms are evaluated lazily, so each body will not be evaluated until the resulting stream is forced. This allows for/stream and for*/stream to iterate over infinite sequences, unlike their finite counterparts.\n\nExamples:\n\n> ```racket\n> > ( for/stream ( [ i ' ( 1 2 3 ) ] ) ( * i i ) )\n> #\n> > ( stream → list ( for/stream ( [ i ' ( 1 2 3 ) ] ) ( * i i ) ) )\n> '(1 4 9)\n> > ( stream-ref ( for/stream ( [ i ' ( 1 2 3 ) ] ) ( displayln i ) ( * i i ) ) 1 )\n> 2\n> 4\n> > ( stream-ref ( for/stream ( [ i ( in-naturals ) ] ) ( * i i ) ) 25 )\n> 625\n> > ( stream-ref ( for/stream ( [ i ( in-naturals ) ] ) ( values i ( add1 i ) ) ) 10 )\n> 10 11\n> ```\n\nAdded in version 6.3.0.9 of package base. \nChanged in version 8.8.0.7: Changed to allow multiple values.\n\n>
\n\n

value

\n\n

gen:stream : any/c

\n\nAssociates three methods to a structure type to implement the generic interface (see Generic Interfaces) for streams.\n\nTo supply method implementations, the #:methods keyword should be used in a structure type definition. The following three methods must be implemented:\n\n- stream-empty? : accepts one argument\n\n- stream-first : accepts one argument\n\n- stream-rest : accepts one argument\n\nExamples:\n\n> ```racket\n> > ( struct list-stream ( v ) #:methods gen:stream [ ( define ( stream-empty? stream ) ( empty? ( list-stream-v stream ) ) ) ( define ( stream-first stream ) ( first ( list-stream-v stream ) ) ) ( define ( stream-rest stream ) ( list-stream ( rest ( list-stream-v stream ) ) ) ) ] )\n> > ( define l1 ( list-stream ' ( 1 2 ) ) )\n> > ( stream? l1 )\n> #t\n> > ( stream-first l1 )\n> 1\n> ```\n\nChanged in version 8.7.0.5 of package base: Added a check so that omitting any of stream-empty?, stream-first, and stream-rest is now a syntax error.\n\n>
\n\n

value

\n\n

prop:stream : struct-type-property?

\n\nA structure type property used to define custom extensions to the stream API. Using the prop:stream property is discouraged; use the gen:stream generic interface instead. Accepts a vector of three procedures taking the same arguments as the methods in gen:stream.\n\n> ```\n(stream/c c) → contract?\n  c : contract?```\n\n\nReturns a contract that recognizes streams. All elements of the stream must match c.\n\nIf the c argument is a flat contract or a chaperone contract, then the result will be a chaperone contract. Otherwise, the result will be an impersonator contract.\n\nWhen an [stream/c](#%28def._%28%28lib._racket%2Fstream..rkt%29._stream%2Fc%29%29) contract is applied to a stream, the result is not [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to the input. The result will be either a [chaperone](chaperones.html#%28tech._chaperone%29) or [impersonator](chaperones.html#%28tech._impersonator%29) of the input depending on the type of contract.\n\nContracts on streams are evaluated lazily by necessity (since streams may be infinite). Contract violations will not be raised until the value in violation is retrieved from the stream. As an exception to this rule, streams that are lists are checked immediately, as if c had been used with [listof](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._listof%29%29).\n\nIf a contract is applied to a stream, and that stream is subsequently used as the tail of another stream (as the second parameter to [stream-cons](#%28form._%28%28lib._racket%2Fstream..rkt%29._stream-cons%29%29)), the new elements will not be checked with the contract, but the tail’s elements will still be enforced.\n\nAdded in version 6.1.1.8 of package base.\n\n------------------------------------------------------------------------\n\n# 4.17.3 Generators\n\n#### 4.17.3 Generators\n\nA generator is a procedure that returns a sequence of values, incrementing the sequence each time that the generator is called. In particular, the [generator](#%28form._%28%28lib._racket%2Fgenerator..rkt%29._generator%29%29) form implements a generator by evaluating a body that calls [yield](#%28def._%28%28lib._racket%2Fgenerator..rkt%29._yield%29%29) to return values from the generator.\n\n| | |\n|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/generator]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\n> ```\n(generator? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 4.17.2 Streams\nReturn #t if v is a generator, #f otherwise.\n>
\n

syntax

\n

(generator formals body ...+)

 
formals = (id ...)
  | (id ...+ . rest-id)
  | rest-id
\nCreates a generator, where formals specify the arguments. Keyword and optional arguments are not supported. This is the same as the formals of a single case-lambda clause."} {"text": "# 4.17.2 Streams\nFor the first call to a generator, the arguments are bound to the formals and evaluation of body starts. During the dynamic extent of body, the generator can return immediately using the yield function. A second call to the generator resumes at the yield call, producing the arguments of the second call as the results of the yield, and so on. The eventual results of body are supplied to an implicit final yield; after that final yield, calling the generator again returns the same values, but all such calls must provide 0 arguments to the generator.\nExamples:\n> ```racket\n> > ( define g ( generator ( ) ( let loop ( [ x ' ( a b c ) ] ) ( if ( null? x ) 0 ( begin ( yield ( car x ) ) ( loop ( cdr x ) ) ) ) ) ) )\n> > ( g )\n> 'a\n> > ( g )\n> 'b\n> > ( g )\n> 'c\n> > ( g )\n> 0\n> > ( g )\n> 0\n> ```\n> ```\n(yield v ...) → any\n  v : any/c```\nReturns vs from a generator, saving the point of execution inside a generator (i.e., within the [dynamic extent](eval-model.html#%28tech._dynamic._extent%29) of a [generator](#%28form._%28%28lib._racket%2Fgenerator..rkt%29._generator%29%29) body) to be resumed by the next call to the generator. The results of [yield](#%28def._%28%28lib._racket%2Fgenerator..rkt%29._yield%29%29) are the arguments that are provided to the next call of the generator."} {"text": "# 4.17.2 Streams\nWhen not in the [dynamic extent](eval-model.html#%28tech._dynamic._extent%29) of a [generator](#%28form._%28%28lib._racket%2Fgenerator..rkt%29._generator%29%29), [infinite-generator](#%28form._%28%28lib._racket%2Fgenerator..rkt%29._infinite-generator%29%29), or [in-generator](#%28form._%28%28lib._racket%2Fgenerator..rkt%29._in-generator%29%29) body, [yield](#%28def._%28%28lib._racket%2Fgenerator..rkt%29._yield%29%29) raises [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29).\nExamples:\n> ```racket\n> > ( define my-generator ( generator ( ) ( yield 1 ) ( yield 2 3 4 ) ) )\n> > ( my-generator )\n> 1\n> > ( my-generator )\n> 2 3 4\n> ```\nExamples:\n> ```racket\n> > ( define pass-values-generator ( generator ( ) ( let* ( [ from-user ( yield 2 ) ] [ from-user-again ( yield ( add1 from-user ) ) ] ) ( yield from-user-again ) ) ) )\n> > ( pass-values-generator )\n> 2\n> > ( pass-values-generator 5 )\n> 6\n> > ( pass-values-generator 12 )\n> 12\n> ```\n>
\n

syntax

\n

([infinite-generator](#%28form._%28%28lib._racket%2Fgenerator..rkt%29._infinite-generator%29%29) body ...+)

\nLike [generator](#%28form._%28%28lib._racket%2Fgenerator..rkt%29._generator%29%29), but repeats evaluation of the bodys when the last body completes without implicitly [yield](#%28def._%28%28lib._racket%2Fgenerator..rkt%29._yield%29%29)ing.\nExamples:"} {"text": "# 4.17.2 Streams\n> ```racket\n> > ( define welcome ( infinite-generator ( yield ' hello ) ( yield ' goodbye ) ) )\n> > ( welcome )\n> 'hello\n> > ( welcome )\n> 'goodbye\n> > ( welcome )\n> 'hello\n> > ( welcome )\n> 'goodbye\n> ```\n>
\n

syntax

\n

([in-generator](#%28form._%28%28lib._racket%2Fgenerator..rkt%29._in-generator%29%29) maybe-arity body ...+)

 
maybe-arity = 
  | #:arity arity-k
"} {"text": "# 4.17.2 Streams\nProduces a [sequence](sequences.html#%28tech._sequence%29) that encapsulates the [generator](#%28tech._generator%29) formed by ([generator](#%28form._%28%28lib._racket%2Fgenerator..rkt%29._generator%29%29) () body [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)). The values produced by the generator form the elements of the sequence, except for the last value produced by the generator (i.e., the values produced by returning).\nExample:\n> ```racket\n> > ( for/list ( [ i ( in-generator ( let loop ( [ x ' ( a b c ) ] ) ( when ( not ( null? x ) ) ( yield ( car x ) ) ( loop ( cdr x ) ) ) ) ) ] ) i )\n> '(a b c)\n> ```\nIf [in-generator](#%28form._%28%28lib._racket%2Fgenerator..rkt%29._in-generator%29%29) is used immediately with a [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) (or [for/list](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29), etc.) binding’s right-hand side, then its result arity (i.e., the number of values in each element of the sequence) can be inferred. Otherwise, if the generator produces multiple values for each element, its arity should be declared with an #:arity arity-k clause; the arity-k must be a literal, exact, non-negative integer.\nExamples:"} {"text": "# 4.17.2 Streams\n> ```racket\n> > ( let ( [ g ( in-generator ( let loop ( [ n 3 ] ) ( unless ( zero? n ) ( yield n ( add1 n ) ) ( loop ( sub1 n ) ) ) ) ) ] ) ( let-values ( [ ( not-empty? next ) ( sequence-generate g ) ] ) ( let loop ( ) ( when ( not-empty? ) ( next ) ( loop ) ) ) ' done ) )\n> stop?: arity mismatch;\n> the expected number of arguments does not match the given\n> number\n> expected: 1\n> given: 2\n> > ( let ( [ g ( in-generator #:arity 2 ( let loop ( [ n 3 ] ) ( unless ( zero? n ) ( yield n ( add1 n ) ) ( loop ( sub1 n ) ) ) ) ) ] ) ( let-values ( [ ( not-empty? next ) ( sequence-generate g ) ] ) ( let loop ( ) ( when ( not-empty? ) ( next ) ( loop ) ) ) ' done ) )\n> 'done\n> ```\nTo use an existing generator as a sequence, use [in-producer](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-producer%29%29) with a stop-value known for the generator:\n> ```racket\n> > ( define abc-generator ( generator ( ) ( for ( [ x ' ( a b c ) ] ) ( yield x ) ) ) )\n> > ( for/list ( [ i ( in-producer abc-generator ( void ) ) ] ) i )\n> '(a b c)\n> > ( define my-stop-value ( gensym ) )\n> > ( define my-generator ( generator ( ) ( let loop ( [ x ( list ' a ( void ) ' c ) ] ) ( if ( null? x ) my-stop-value ( begin ( yield ( car x ) ) ( loop ( cdr x ) ) ) ) ) ) )\n> > ( for/list ( [ i ( in-producer my-generator my-stop-value ) ] ) i )\n> '(a # c)\n> ```\n> ```\n(parameter)\t→"} {"text": "# 4.17.2 Streams\n```\nReturns a symbol that describes the state of the generator.\n\n- 'fresh — The generator has been freshly created and has not been called yet.\n\n- 'suspended — Control within the generator has been suspended due to a call to yield. The generator can be called.\n\n- 'running — The generator is currently executing.\n\n- 'done — The generator has executed its entire body and will continue to produce the same result as from the last call.\n\nExamples:\n\n> ```racket\n> > ( define my-generator ( generator ( ) ( yield 1 ) ( yield 2 ) ) )\n> > ( generator-state my-generator )\n> 'fresh\n> > ( my-generator )\n> 1\n> > ( generator-state my-generator )\n> 'suspended\n> > ( my-generator )\n> 2\n> > ( generator-state my-generator )\n> 'suspended\n> > ( my-generator )\n> > ( generator-state my-generator )\n> 'done\n> > ( define introspective-generator ( generator ( ) ( ( yield 1 ) ) ) )\n> > ( introspective-generator )\n> 1\n> > ( introspective-generator ( lambda ( ) ( generator-state introspective-generator ) ) )\n> 'running\n> > ( generator-state introspective-generator )\n> 'done\n> > ( introspective-generator )\n> 'running\n> ```\n\n> ```\n(sequence → generator s)  →  ( →  any)\n  s : sequence?```\n\n\nConverts a [sequence](sequences.html#%28tech._sequence%29) to a [generator](#%28tech._generator%29). The generator returns the next element of the sequence each time the generator is invoked, where each element of the sequence must be a single value. When the sequence ends, the generator returns [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13) as its final result.\n\n> ```\n(sequence → repeated-generator s)  →  ( →  any)\n  s : sequence?\n```"} {"text": "# 4.17.2 Streams\nLike sequence → generator, but when s has no further values, the generator starts the sequence again (so that the generator never stops producing values).\n------------------------------------------------------------------------"} {"text": "# 4.18 Dictionaries"} {"text": "### 4.18 Dictionaries\nA dictionary is an instance of a datatype that maps keys to values. The following datatypes are all dictionaries:\n- hash tables;\n- vectors (using only exact integers as keys);\n- lists of pairs as an association list using equal? to compare keys, which must be distinct; and\n- structures whose types implement the gen:dict generic interface.\nWhen list of pairs is used as association list but does not have distinct keys (so it’s not an association list), operations like dict-ref and dict-remove operate on the first instance of the key, while operations like dict-map and dict-keys produce an element for every instance of the key.\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/dict]()) |  package: base |\nThe bindings documented in this section are provided by the [racket/dict]() and racket libraries, but not racket/base."} {"text": "#### 4.18.1 Dictionary Predicates and Contracts\n> ```\n(dict? v) → boolean?\n  v : any/c```\nReturns #t if v is a [dictionary](#%28tech._dictionary%29), #f otherwise.\nBeware that [dict?](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict~3f%29%29) is not a constant-time test on pairs, since checking that v is an [association list](#%28tech._association._list%29) may require traversing the list.\nExamples:\n> ```racket\n> > ( dict? #hash ( ( a . \"apple\" ) ) )\n> #t\n> > ( dict? ' # ( \"apple\" \"banana\" ) )\n> #t\n> > ( dict? ' ( \"apple\" \"banana\" ) )\n> #f\n> > ( dict? ' ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> #t\n> ```\n> ```\n(parameter)\t→"} {"text": "# 4.18 Dictionaries\n```\n(parameter)\t→```\n\n\nRecognizes dictionaries that support all of the methods from [gen:dict](#%28form._%28%28lib._racket%2Fdict..rkt%29._gen~3adict%29%29) named by the syms. Note that the generated contract is not similar to [hash/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fhash..rkt%29._hash%2Fc%29%29), but closer to [dict-implements?](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-implements~3f%29%29).\n\nExamples:\n\n> ```racket\n> > ( struct deformed-dict ( ) #:methods gen:dict [ ] )\n> > ( define/contract good-dict ( dict-implements/c ) ( deformed-dict ) )\n> > ( define/contract bad-dict ( dict-implements/c ' dict-ref ) ( deformed-dict ) )\n> bad-dict: broke its own contract\n> promised: (dict-implements/c dict-ref)\n> produced: #\n> in: (dict-implements/c dict-ref)\n> contract from: (definition bad-dict)\n> blaming: (definition bad-dict)\n> (assuming the contract is correct)\n> at: eval:14:0\n> ```\n\n> ```\n(dict-mutable? d)  →  boolean?\n  d : dict?\n```\nReturns #t if d is mutable via dict-set!, #f otherwise.\nEquivalent to (dict-implements? d 'dict-set!).\nExamples:\n> ```racket\n> > ( dict-mutable? #hash ( ( a . \"apple\" ) ) )\n> #f\n> > ( dict-mutable? ( make-hash ) )\n> #t\n> > ( dict-mutable? ' # ( \"apple\" \"banana\" ) )\n> #f\n> > ( dict-mutable? ( vector \"apple\" \"banana\" ) )\n> #t\n> > ( dict-mutable? ' ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> #f\n> ```\n> ```\n(dict-can-remove-keys? d)  →  boolean?\n  d : dict?```"} {"text": "# 4.18 Dictionaries\nReturns #t if d supports removing mappings via [dict-remove!](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-remove%21%29%29) and/or [dict-remove](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-remove%29%29), #f otherwise.\nEquivalent to ([or](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29) ([dict-implements?](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-implements~3f%29%29) d 'dict-remove!) ([dict-implements?](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-implements~3f%29%29) d 'dict-remove)).\nExamples:\n> ```racket\n> > ( dict-can-remove-keys? #hash ( ( a . \"apple\" ) ) )\n> #t\n> > ( dict-can-remove-keys? ' # ( \"apple\" \"banana\" ) )\n> #f\n> > ( dict-can-remove-keys? ' ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> #t\n> ```\n> ```\n(dict-can-functional-set? d)  →  boolean?\n  d : dict?"} {"text": "# 4.18 Dictionaries\n```\nReturns #t if d supports functional update via dict-set, #f otherwise.\n\nEquivalent to (dict-implements? d 'dict-set).\n\nExamples:\n\n> ```racket\n> > ( dict-can-functional-set? #hash ( ( a . \"apple\" ) ) )\n> #t\n> > ( dict-can-functional-set? ( make-hash ) )\n> #f\n> > ( dict-can-functional-set? ' # ( \"apple\" \"banana\" ) )\n> #f\n> > ( dict-can-functional-set? ' ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> #t\n> ```\n\n#### 4.18.2 Generic Dictionary Interface\n\n>
\n\n

syntax

\n\n

gen:dict

\n\nA generic interface (see Generic Interfaces) that supplies dictionary method implementations for a structure type via the #:methods option of struct definitions. This interface can be used to implement any of the methods documented as Primitive Dictionary Methods and Derived Dictionary Methods.\n\nExamples:\n\n> ```racket\n> > ( struct alist ( v ) #:methods gen:dict [ ( define ( dict-ref dict key [ default ( lambda ( ) ( error \"key not found\" key ) ) ] ) ( cond [ ( assoc key ( alist-v dict ) ) => cdr ] [ else ( if ( procedure? default ) ( default ) default ) ] ) ) ( define ( dict-set dict key val ) ( alist ( cons ( cons key val ) ( alist-v dict ) ) ) ) ( define ( dict-remove dict key ) ( define al ( alist-v dict ) ) ( alist ( remove* ( filter ( λ ( p ) ( equal? ( car p ) key ) ) al ) al ) ) ) ( define ( dict-count dict ) ( length ( remove-duplicates ( alist-v dict ) #:key car ) ) ) ] )\n> ; etc. other methods\n> > ( define d1 ( alist ' ( ( 1 . a ) ( 2 . b ) ) ) )\n> > ( dict? d1 )\n> #t\n> > ( dict-ref d1 1 )\n> 'a\n> > ( dict-remove d1 1 )\n> #\n> ```\n\n>
\n\n

value

\n\n

prop:dict : struct-type-property?

\n\nA structure type property used to define custom extensions to the dictionary API. Using the prop:dict property is discouraged; use the gen:dict generic interface instead. Accepts a vector of 10 method implementations:\n\n- dict-ref\n\n- dict-set!, or #f if unsupported\n\n- dict-set, or #f if unsupported\n\n- dict-remove!, or #f if unsupported\n\n- dict-remove, or #f if unsupported\n\n- dict-count\n\n- dict-iterate-first\n\n- dict-iterate-next\n\n- dict-iterate-key\n\n- dict-iterate-value\n\n##### 4.18.2.1 Primitive Dictionary Methods\n\nThese methods of gen:dict have no fallback implementations; they are only supported for dictionary types that directly implement them.\n\n> ```\n(dict-ref dict key [failure-result) → any\n  dict : dict?\n  key : any/c\n   failure-result   :   failure-result/c\n      =   (lambda () (raise (make-exn:fail ....)))```\n\n\nReturns the value for key in dict. If no value is found for key, then failure-result determines the result:\n\n- If failure-result is a procedure, it is called (through a tail call) with no arguments to produce the result.\n\n- Otherwise, failure-result is returned as the result.\n\nExamples:\n\n> ```racket\n> > ( dict-ref #hash ( ( a . \"apple\" ) ( b . \"beer\" ) ) ' a )\n> \"apple\"\n> > ( dict-ref #hash ( ( a . \"apple\" ) ( b . \"beer\" ) ) ' c )\n> hash-ref: no value found for key\n> key: 'c\n> > ( dict-ref #hash ( ( a . \"apple\" ) ( b . \"beer\" ) ) ' c #f )\n> #f\n> > ( dict-ref ' ( ( a . \"apple\" ) ( b . \"banana\" ) ) ' b )\n> \"banana\"\n> > ( dict-ref # ( \"apple\" \"banana\" ) 1 )\n> \"banana\"\n> > ( dict-ref # ( \"apple\" \"banana\" ) 3 #f )\n> #f\n> > ( dict-ref # ( \"apple\" \"banana\" ) -3 #f )\n> dict-ref: contract violation\n> expected: natural?\n> given: -3\n> in: the k argument of\n> (->i\n> ((d dict?) (k (d) (dict-key-contract d)))\n> ((default any/c))\n> any)\n> contract from: /racket/dict.rkt\n> blaming: top-level\n> (assuming the contract is correct)\n> at: /racket/dict.rkt:182:2\n> ```\n\n> ```\n(parameter)\t→\t\n(-> and/c dict? (not/c immutable?))\n```"} {"text": "# 4.18 Dictionaries\nMaps key to v in dict, overwriting any existing mapping for key. The update can fail with a exn:fail:contract exception if dict is not mutable or if key is not an allowed key for the dictionary (e.g., not an exact integer in the appropriate range when dict is a vector).\nExamples:\n> ```racket\n> > ( define h ( make-hash ) )\n> > ( dict-set! h ' a \"apple\" )\n> > h\n> '#hash((a . \"apple\"))\n> > ( define v ( vector #f #f #f ) )\n> > ( dict-set! v 0 \"apple\" )\n> > v\n> '#(\"apple\" #f #f)\n> ```\n> ```\n(dict-set dict key v)  →  (and/c dict? immutable?)\n  dict : (and/c dict? immutable?)\n  key : any/c\n  v : any/c```\nFunctionally extends dict by mapping key to v, overwriting any existing mapping for key, and returning an extended dictionary. The update can fail with a [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception if dict does not support functional extension or if key is not an allowed key for the dictionary.\nExamples:\n> ```racket\n> > ( dict-set #hash ( ) ' a \"apple\" )\n> '#hash((a . \"apple\"))\n> > ( dict-set #hash ( ( a . \"apple\" ) ( b . \"beer\" ) ) ' b \"banana\" )\n> '#hash((a . \"apple\") (b . \"banana\"))\n> > ( dict-set ' ( ) ' a \"apple\" )\n> '((a . \"apple\"))\n> > ( dict-set ' ( ( a . \"apple\" ) ( b . \"beer\" ) ) ' b \"banana\" )\n> '((a . \"apple\") (b . \"banana\"))\n> ```\n> ```\n(parameter)\t→\t\n(-> and/c dict? (not/c immutable?))"} {"text": "# 4.18 Dictionaries\n```\nRemoves any existing mapping for key in dict. The update can fail if dict is not mutable or does not support removing keys (as is the case for vectors, for example).\n\nExamples:\n\n> ```racket\n> > ( define h ( make-hash ) )\n> > ( dict-set! h ' a \"apple\" )\n> > h\n> '#hash((a . \"apple\"))\n> > ( dict-remove! h ' a )\n> > h\n> '#hash()\n> ```\n\n> ```\n(dict-remove dict key)  →  (and/c dict? immutable?)\n  dict : (and/c dict? immutable?)\n  key : any/c```\n\n\nFunctionally removes any existing mapping for key in dict, returning the fresh dictionary. The update can fail if dict does not support functional update or does not support removing keys.\n\nExamples:\n\n> ```racket\n> > ( define h #hash ( ) )\n> > ( define h ( dict-set h ' a \"apple\" ) )\n> > h\n> '#hash((a . \"apple\"))\n> > ( dict-remove h ' a )\n> '#hash()\n> > h\n> '#hash((a . \"apple\"))\n> > ( dict-remove h ' z )\n> '#hash((a . \"apple\"))\n> > ( dict-remove ' ( ( a . \"apple\" ) ( b . \"banana\" ) ) ' a )\n> '((b . \"banana\"))\n> ```\n\n> ```\n(dict-iterate-first dict)  →  any/c\n  dict : dict?\n```\nReturns #f if dict contains no elements, otherwise it returns a non-#f value that is an index to the first element in the dict table; “first” refers to an unspecified ordering of the dictionary elements. For a mutable dict, this index is guaranteed to refer to the first item only as long as no mappings are added to or removed from dict.\nExamples:"} {"text": "# 4.18 Dictionaries\n> ```racket\n> > ( dict-iterate-first #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> 0\n> > ( dict-iterate-first #hash ( ) )\n> #f\n> > ( dict-iterate-first # ( \"apple\" \"banana\" ) )\n> 0\n> > ( dict-iterate-first ' ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> #\n> ```\n> ```\n(dict-iterate-next dict pos)  →  any/c\n  dict : dict?\n  pos : any/c\n```\n\n\nReturns either a non-#f that is an index to the element in dict after the element indexed by pos or #f if pos refers to the last element in dict. If pos is not a valid index, then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. For a mutable dict, the result index is guaranteed to refer to its item only as long as no items are added to or removed from dict. The [dict-iterate-next](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-next%29%29) operation should take constant time.\n\nExamples:\n\n> ```racket\n> > ( define h #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> > ( define i ( dict-iterate-first h ) )\n> > i\n> 0\n> > ( dict-iterate-next h i )\n> 1\n> > ( dict-iterate-next h ( dict-iterate-next h i ) )\n> #f\n> ```\n\n> ```\n(dict-iterate-key dict pos)  →  any\n  dict : dict?\n  pos : any/c\n```\nReturns the key for the element in dict at index pos. If pos is not a valid index for dict, the exn:fail:contract exception is raised. The dict-iterate-key operation should take constant time.\nExamples:"} {"text": "# 4.18 Dictionaries\n> ```racket\n> > ( define h ' ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> > ( define i ( dict-iterate-first h ) )\n> > ( dict-iterate-key h i )\n> 'a\n> > ( dict-iterate-key h ( dict-iterate-next h i ) )\n> 'b\n> ```\n> ```\n(dict-iterate-value dict pos)  →  any\n  dict : dict?\n  pos : any/c```\nReturns the value for the element in dict at index pos. If pos is not a valid index for dict, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. The [dict-iterate-key](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-key%29%29) operation should take constant time.\nExamples:\n> ```racket\n> > ( define h ' ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> > ( define i ( dict-iterate-first h ) )\n> > ( dict-iterate-value h i )\n> \"apple\"\n> > ( dict-iterate-value h ( dict-iterate-next h i ) )\n> \"banana\"\n> ```"} {"text": "##### 4.18.2.2 Derived Dictionary Methods\nThese methods of [gen:dict](#%28form._%28%28lib._racket%2Fdict..rkt%29._gen~3adict%29%29) have fallback implementations in terms of the other methods; they may be supported even by dictionary types that do not directly implement them.\n> ```\n(dict-has-key? dict key)  →  boolean?\n  dict : dict?\n  key : any/c\n```\n(parameter)\t→\t\n(-> and/c dict? (not/c immutable?))```\n\n\nMaps each key to each v in dict, overwriting any existing mapping for each key. The update can fail with a [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception if dict is not mutable or if any key is not an allowed key for the dictionary (e.g., not an exact integer in the appropriate range when dict is a [vector](vectors.html#%28tech._vector%29)). The update takes place from the left, so later mappings overwrite earlier mappings.\n\nSupported for any dict that implements [dict-set!](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-set%21%29%29).\n\nExamples:\n\n> ```racket\n> > ( define h ( make-hash ) )\n> > ( dict-set*! h ' a \"apple\" ' b \"banana\" )\n> > h\n> '#hash((a . \"apple\") (b . \"banana\"))\n> > ( define v1 ( vector #f #f #f ) )\n> > ( dict-set*! v1 0 \"apple\" 1 \"banana\" )\n> > v1\n> '#(\"apple\" \"banana\" #f)\n> > ( define v2 ( vector #f #f #f ) )\n> > ( dict-set*! v2 0 \"apple\" 0 \"banana\" )\n> > v2\n> '#(\"banana\" #f #f)\n> ```\n\n> ```\n(dict-set* dict key v ... ...) → (and/c dict? immutable?)\n  dict : (and/c dict? immutable?)\n  key : any/c\n  v : any/c\n```"} {"text": "# 4.18 Dictionaries\nFunctionally extends dict by mapping each key to each v, overwriting any existing mapping for each key, and returning an extended dictionary. The update can fail with a exn:fail:contract exception if dict does not support functional extension or if any key is not an allowed key for the dictionary. The update takes place from the left, so later mappings overwrite earlier mappings.\nSupported for any dict that implements dict-set.\nExamples:\n> ```racket\n> > ( dict-set* #hash ( ) ' a \"apple\" ' b \"beer\" )\n> '#hash((a . \"apple\") (b . \"beer\"))\n> > ( dict-set* #hash ( ( a . \"apple\" ) ( b . \"beer\" ) ) ' b \"banana\" ' a \"anchor\" )\n> '#hash((a . \"anchor\") (b . \"banana\"))\n> > ( dict-set* ' ( ) ' a \"apple\" ' b \"beer\" )\n> '((a . \"apple\") (b . \"beer\"))\n> > ( dict-set* ' ( ( a . \"apple\" ) ( b . \"beer\" ) ) ' b \"banana\" ' a \"anchor\" )\n> '((a . \"anchor\") (b . \"banana\"))\n> > ( dict-set* ' ( ( a . \"apple\" ) ( b . \"beer\" ) ) ' b \"banana\" ' b \"ballistic\" )\n> '((a . \"apple\") (b . \"ballistic\"))\n> ```\n> ```\n(dict-ref! dict key to-set)  →  any\n  dict : dict?\n  key : any/c\n  to-set : any/c```\nReturns the value for key in dict. If no value is found for key, then to-set determines the result as in [dict-ref](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-ref%29%29) (i.e., it is either a thunk that computes a value or a plain value), and this result is stored in dict for the key. (Note that if to-set is a thunk, it is not invoked in tail position.)"} {"text": "# 4.18 Dictionaries\nSupported for any dict that implements [dict-ref](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-ref%29%29) and [dict-set!](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-set%21%29%29).\nExamples:\n> ```racket\n> > ( dict-ref! ( make-hasheq ' ( ( a . \"apple\" ) ( b . \"beer\" ) ) ) ' a #f )\n> \"apple\"\n> > ( dict-ref! ( make-hasheq ' ( ( a . \"apple\" ) ( b . \"beer\" ) ) ) ' c ' cabbage )\n> 'cabbage\n> > ( define h ( make-hasheq ' ( ( a . \"apple\" ) ( b . \"beer\" ) ) ) )\n> > ( dict-ref h ' c )\n> hash-ref: no value found for key\n> key: 'c\n> > ( dict-ref! h ' c ( λ ( ) ' cabbage ) )\n> 'cabbage\n> > ( dict-ref h ' c )\n> 'cabbage\n> ```\n> ```\n(parameter)\t→\t\n(-> and/c dict? (not/c immutable?))"} {"text": "# 4.18 Dictionaries\n```\nComposes dict-ref and dict-set! to update an existing mapping in dict, where the optional failure-result argument is used as in dict-ref when no mapping exists for key already.\n\nSupported for any dict that implements dict-ref and dict-set!.\n\nExamples:\n\n> ```racket\n> > ( define h ( make-hash ) )\n> > ( dict-update! h ' a add1 )\n> hash-update!: no value found for key: 'a\n> > ( dict-update! h ' a add1 0 )\n> > h\n> '#hash((a . 1))\n> > ( define v ( vector #f #f #f ) )\n> > ( dict-update! v 0 not )\n> > v\n> '#(#t #f #f)\n> ```\n\n> ```\n(dict-update dict key updater [failure-result)\n  →  (and/c dict? immutable?)\n  dict : dict?\n  key : any/c\n  updater : (any/c . → . any/c)\n   failure-result   :   failure-result/c\n      =   (lambda () (raise (make-exn:fail ....)))```\n\n\nComposes [dict-ref](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-ref%29%29) and [dict-set](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-set%29%29) to functionally update an existing mapping in dict, where the optional failure-result argument is used as in [dict-ref](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-ref%29%29) when no mapping exists for key already.\n\nSupported for any dict that implements [dict-ref](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-ref%29%29) and [dict-set](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-set%29%29).\n\nExamples:\n\n> ```racket\n> > ( dict-update #hash ( ) ' a add1 )\n> hash-update: no value found for key: 'a\n> > ( dict-update #hash ( ) ' a add1 0 )\n> '#hash((a . 1))\n> > ( dict-update #hash ( ( a . \"apple\" ) ( b . \"beer\" ) ) ' b string-length )\n> '#hash((a . \"apple\") (b . 4))\n> ```\n\n> ```\n(dict-map dict proc)  →  (listof any/c)\n  dict : dict?\n  proc : (any/c any/c . → . any/c)\n```"} {"text": "# 4.18 Dictionaries\nApplies the procedure proc to each element in dict in an unspecified order, accumulating the results into a list. The procedure proc is called each time with a key and its value.\nSupported for any dict that implements dict-iterate-first, dict-iterate-next, dict-iterate-key, and dict-iterate-value.\nExample:\n> ```racket\n> > ( dict-map #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) vector )\n> '(#(b \"banana\") #(a \"apple\"))\n> ```\n> ```\n(dict-map/copy dict proc)  →  dict?\n  dict : dict?\n  proc : (any/c any/c . → . (values any/c any/c))```\nApplies the procedure proc to each element in dict in an unspecified order, accumulating the results into a dict of the same kind. The procedure proc is called each time with a key and its value, and must return a corresponding key and value.\nSupported for any dict that implements [dict-iterate-first](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-first%29%29), [dict-iterate-next](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-next%29%29), [dict-iterate-key](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-key%29%29), and [dict-iterate-value](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-value%29%29), and either [dict-set](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-set%29%29) and [dict-clear](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-clear%29%29), or [dict-set!](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-set%21%29%29), [dict-copy](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-copy%29%29), and [dict-clear!](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-clear%21%29%29)."} {"text": "# 4.18 Dictionaries\nExample:\n> ```racket\n> > ( dict-map/copy #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) ( lambda ( k v ) ( values k ( string-upcase v ) ) ) )\n> '#hash((a . \"APPLE\") (b . \"BANANA\"))\n> ```\nAdded in version 8.5.0.2 of package base.\n> ```\n(parameter)\t→\t\n(-> any/c any/c . → . any)\n```\nApplies proc to each element in dict (for the side-effects of proc) in an unspecified order. The procedure proc is called each time with a key and its value.\n\nSupported for any dict that implements dict-iterate-first, dict-iterate-next, dict-iterate-key, and dict-iterate-value.\n\nExample:\n\n> ```racket\n> > ( dict-for-each #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) ( lambda ( k v ) ( printf \"~a = ~s\\n\" k v ) ) )\n> b = \"banana\" a = \"apple\"\n> ```\n\n> ```\n(dict-empty? dict) → boolean?\n  dict : dict?```\n\n\nReports whether dict is empty.\n\nSupported for any dict that implements [dict-iterate-first](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-first%29%29).\n\nExamples:\n\n> ```racket\n> > ( dict-empty? #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> #f\n> > ( dict-empty? ( vector ) )\n> #t\n> ```\n\n> ```\n(dict-count dict)  →  exact-nonnegative-integer?\n  dict : dict?\n```\nReturns the number of keys mapped by dict, usually in constant time.\nSupported for any dict that implements dict-iterate-first and dict-iterate-next.\nExamples:\n> ```racket\n> > ( dict-count #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> 2\n> > ( dict-count # ( \"apple\" \"banana\" ) )\n> 2\n> ```\n> ```\n(dict-copy dict)  →  dict?\n  dict : dict?```"} {"text": "# 4.18 Dictionaries\nProduces a new, mutable dictionary of the same type as dict and with the same key/value associations.\nSupported for any dict that implements [dict-clear](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-clear%29%29), [dict-set!](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-set%21%29%29), [dict-iterate-first](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-first%29%29), [dict-iterate-next](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-next%29%29), [dict-iterate-key](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-key%29%29), and [dict-iterate-value](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-value%29%29).\nExamples:\n> ```racket\n> > ( define original ( vector \"apple\" \"banana\" ) )\n> > ( define copy ( dict-copy original ) )\n> > original\n> '#(\"apple\" \"banana\")\n> > copy\n> '#(\"apple\" \"banana\")\n> > ( dict-set! copy 1 \"carrot\" )\n> > original\n> '#(\"apple\" \"banana\")\n> > copy\n> '#(\"apple\" \"carrot\")\n> ```\n> ```\n(dict-clear dict)  →  dict?\n  dict : dict?"} {"text": "# 4.18 Dictionaries\n```\n(parameter)\t→```\n\n\nRemoves all of the key/value associations in dict.\n\nSupported for any dict that supports [dict-remove!](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-remove%21%29%29), [dict-iterate-first](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-first%29%29), and [dict-iterate-key](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-key%29%29).\n\nExamples:\n\n> ```racket\n> > ( define table ( make-hash ) )\n> > ( dict-set! table ' a \"apple\" )\n> > ( dict-set! table \"banana\" ' b )\n> > table\n> '#hash((a . \"apple\") (\"banana\" . b))\n> > ( dict-clear! table )\n> > table\n> '#hash()\n> ```\n\n> ```\n(dict-keys dict)  →  list?\n  dict : dict?\n```\nReturns a list of the keys from dict in an unspecified order.\nSupported for any dict that implements dict-iterate-first, dict-iterate-next, and dict-iterate-key.\nExamples:\n> ```racket\n> > ( define h #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> > ( dict-keys h )\n> '(b a)\n> ```\n> ```\n(dict-values dict)  →  list?\n  dict : dict?```\nReturns a list of the values from dict in an unspecified order.\nSupported for any dict that implements [dict-iterate-first](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-first%29%29), [dict-iterate-next](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-next%29%29), and [dict-iterate-value](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-value%29%29).\nExamples:\n> ```racket\n> > ( define h #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> > ( dict-values h )\n> '(\"banana\" \"apple\")\n> ```\n> ```\n(dict → list dict)  →  list?\n  dict : dict?"} {"text": "# 4.18 Dictionaries\n```\nReturns a list of the associations from dict in an unspecified order.\n\nSupported for any dict that implements dict-iterate-first, dict-iterate-next, dict-iterate-key, and dict-iterate-value.\n\nExamples:\n\n> ```racket\n> > ( define h #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> > ( dict → list h )\n> '((b . \"banana\") (a . \"apple\"))\n> ```\n\n#### 4.18.3 Dictionary Sequences\n\n> ```\n(in-dict dict)  →  sequence?\n  dict : dict?```\n\n\nReturns a [sequence](sequences.html#%28tech._sequence%29) whose each element is two values: a key and corresponding value from dict.\n\nSupported for any dict that implements [dict-iterate-first](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-first%29%29), [dict-iterate-next](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-next%29%29), [dict-iterate-key](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-key%29%29), and [dict-iterate-value](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-value%29%29).\n\nExamples:\n\n> ```racket\n> > ( define h #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> > ( for/list ( [ ( k v ) ( in-dict h ) ] ) ( format \"~a = ~s\" k v ) )\n> '(\"b = \\\"banana\\\"\" \"a = \\\"apple\\\"\")\n> ```\n\n> ```\n(in-dict-keys dict)  →  sequence?\n  dict : dict?\n```\nReturns a sequence whose elements are the keys of dict.\nSupported for any dict that implements dict-iterate-first, dict-iterate-next, and dict-iterate-key.\nExamples:\n> ```racket\n> > ( define h #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> > ( for/list ( [ k ( in-dict-keys h ) ] ) k )\n> '(b a)\n> ```\n> ```"} {"text": "# 4.18 Dictionaries\n(in-dict-values dict) → sequence?\n  dict : dict?```\nReturns a sequence whose elements are the values of dict.\nSupported for any dict that implements [dict-iterate-first](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-first%29%29), [dict-iterate-next](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-next%29%29), and [dict-iterate-value](#%28def._%28%28lib._racket%2Fdict..rkt%29._dict-iterate-value%29%29).\nExamples:\n> ```racket\n> > ( define h #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> > ( for/list ( [ v ( in-dict-values h ) ] ) v )\n> '(\"banana\" \"apple\")\n> ```\n> ```\n(in-dict-pairs dict)  →  sequence?\n  dict : dict?"} {"text": "# 4.18 Dictionaries\n```\nReturns a sequence whose elements are pairs, each containing a key and its value from dict (as opposed to using in-dict, which gets the key and value as separate values for each element).\n\nSupported for any dict that implements dict-iterate-first, dict-iterate-next, dict-iterate-key, and dict-iterate-value.\n\nExamples:\n\n> ```racket\n> > ( define h #hash ( ( a . \"apple\" ) ( b . \"banana\" ) ) )\n> > ( for/list ( [ p ( in-dict-pairs h ) ] ) p )\n> '((b . \"banana\") (a . \"apple\"))\n> ```\n\n#### 4.18.4 Contracted Dictionaries\n\n>
\n\n

value

\n\n

prop:dict/contract : struct-type-property?

\n\nA structure type property for defining dictionaries with contracts. The value associated with prop:dict/contract must be a list of two immutable vectors:\n\n> ```racket\n> ( list dict-vector\n> ( vector type-key-contract\n> type-value-contract\n> type-iter-contract\n> instance-key-contract\n> instance-value-contract\n> instance-iter-contract ) )\n> ```\n\nThe first vector must be a vector of 10 procedures which match the gen:dict generic interface (in addition, it must be an immutable vector). The second vector must contain six elements; each of the first three is a contract for the dictionary type’s keys, values, and positions, respectively. Each of the second three is either #f or a procedure used to extract the contract from a dictionary instance.\n\n> ```\n(dict-key-contract d) → contract?\n  d : dict?\n\n(dict-value-contract d)  →  contract?\n  d : dict?\n\n(dict-iter-contract d)  →  contract?\n  d : dict?```\n\n\nReturns the contract that d imposes on its keys, values, or iterators, respectively, if d implements the [prop:dict/contract](#%28def._%28%28lib._racket%2Fdict..rkt%29._prop~3adict%2Fcontract%29%29) interface.\n\n#### 4.18.5 Custom Hash Tables\n\n> ```\nsyntax\n\n(define-custom-hash-types name\n> optional-predicate\n> comparison-expr\n> optional-hash-functions )\n \noptional-predicate   =  \n    |   #:key? predicate-expr\n         \noptional-hash-functions   =  \n    |   hash1-expr\n    |   hash1-expr hash2-expr\n```"} {"text": "# 4.18 Dictionaries\n(parameter)\t→\t\n(-> any/c . → . boolean?)```\nCreates a new dictionary type based on the given comparison function eql?, hash functions hash1 and hash2, and predicate key?. The new dictionary type has variants that are immutable, mutable with strongly-held keys, and mutable with weakly-held keys. The given name is used when printing instances of the new dictionary type, and the symbol who is used for reporting errors.\nThe comparison function eql? may accept 2 or 3 arguments. If it accepts 2 arguments, it given two keys to compare them. If it accepts 3 arguments and does not accept 2 arguments, it is also given a recursive comparison function that handles data cycles when comparing sub-parts of the keys.\nThe hash functions hash1 and hash2 may accept 1 or 2 arguments. If either hash function accepts 1 argument, it is applied to a key to compute the corresponding hash value. If either hash function accepts 2 arguments and does not accept 1 argument, it is also given a recursive hash function that handles data cycles when computing hash values of sub-parts of the keys.\nThe predicate key? must accept 1 argument and is used to recognize valid keys for the new dictionary type.\nProduces seven values:\n- a predicate recognizing all instances of the new dictionary type,\n- a predicate recognizing immutable instances,\n- a predicate recognizing mutable instances,\n- a predicate recognizing weak instances,\n- a constructor for immutable instances,\n- a constructor for mutable instances, and\n- a constructor for weak instances."} {"text": "# 4.18 Dictionaries\nSee [define-custom-hash-types](#%28form._%28%28lib._racket%2Fdict..rkt%29._define-custom-hash-types%29%29) for an example.\n> ```\n(make-custom-hash eql?\n   [ hash1        \n    hash2        \n    #:key? key?)   →   dict?\n   eql?   :   ( or/c ( any/c any/c . → . any/c )\n> ( any/c any/c ( any/c any/c . → . any/c ) . → . any/c ) )\n   hash1   :   ( or/c ( any/c . → . exact-integer? )\n> ( any/c ( any/c . → . exact-integer? ) . → . exact-integer? ) )\n      =   (const 1)\n   hash2   :   ( or/c ( any/c . → . exact-integer? )\n> ( any/c ( any/c . → . exact-integer? ) . → . exact-integer? ) )\n      =   (const 1)\n  key? : (any/c . → . boolean?) = (λ (x) #true)\n(make-weak-custom-hash   eql?        \n   [ hash1        \n    hash2        \n    #:key? key?)   →   dict?\n   eql?   :   ( or/c ( any/c any/c . → . any/c )\n> ( any/c any/c ( any/c any/c . → . any/c ) . → . any/c ) )\n   hash1   :   ( or/c ( any/c . → . exact-integer? )\n> ( any/c ( any/c . → . exact-integer? ) . → . exact-integer? ) )\n      =   (const 1)\n   hash2   :   ( or/c ( any/c . → . exact-integer? )\n> ( any/c ( any/c . → . exact-integer? ) . → . exact-integer? ) )\n      =   (const 1)\n  key? : (any/c . → . boolean?) = (λ (x) #true)\n(make-immutable-custom-hash   eql?        \n   [ hash1        \n    hash2        \n    #:key? key?)   →   dict?\n   eql?   :   ( or/c ( any/c any/c . → . any/c )\n> ( any/c any/c ( any/c any/c . → . any/c ) . → . any/c ) )\n   hash1   :   ( or/c ( any/c . → . exact-integer? )"} {"text": "# 4.18 Dictionaries\n> ( any/c ( any/c . → . exact-integer? ) . → . exact-integer? ) )\n      =   (const 1)\n   hash2   :   ( or/c ( any/c . → . exact-integer? )\n> ( any/c ( any/c . → . exact-integer? ) . → . exact-integer? ) )\n      =   (const 1)\n  key? : (any/c . → . boolean?) = (λ (x) #true)\n```\nCreates an instance of a new dictionary type, implemented in terms of a hash table where keys are compared with eql?, hashed with hash1 and hash2, and where the key predicate is key?. See gen:equal-mode+hash and gen:equal+hash for information on suitable equality and hashing functions.\n\nThe make-custom-hash and make-weak-custom-hash functions create a mutable dictionary that does not support functional update, while make-immutable-custom-hash creates an immutable dictionary that supports functional update. The dictionary created by make-weak-custom-hash retains its keys weakly, like the result of make-weak-hash.\n\nDictionaries created by make-custom-hash and company are equal? when they have the same mutability and key strength, the associated procedures are equal?, and the key–value mappings are the same when keys and values are compared with equal?.\n\nSee also define-custom-hash-types.\n\nExamples:\n\n> ```racket\n> > ( define h ( make-custom-hash ( lambda ( a b ) ( string=? ( format \"~a\" a ) ( format \"~a\" b ) ) ) ( lambda ( a ) ( equal-hash-code ( format \"~a\" a ) ) ) ) )\n> > ( dict-set! h 1 ' one )\n> > ( dict-ref h \"1\" )\n> 'one\n> ```\n\n#### 4.18.6 Passing Keyword Arguments in Dictionaries\n\n> ```\n(keyword-apply/dict proc\n    kw-dict        \n    pos-arg ...        \n    pos-args        \n    #: kw-arg ...)   →   any\n\n  proc : procedure?\n  kw-dict : dict?\n  pos-arg : any/c\n  pos-args : (listof any/c)\n  kw-arg : any/c```\n\n\nApplies the proc using the positional arguments from ([list*](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%2A%29%29) pos-arg [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) pos-args), and the keyword arguments from kw-dict in addition to the directly supplied keyword arguments in the #:\\ kw-arg sequence.\n\nAll the keys in kw-dict must be keywords. The keywords in the kw-dict do not have to be sorted. However, the keywords in kw-dict and the directly supplied #:\\ keywords must not overlap. The given proc must accept all of the keywords in kw-dict plus the #:\\s.\n\nExamples:\n\n> ```racket\n> > ( define ( sundae #:ice-cream [ ice-cream ' ( \"vanilla\" ) ] #:toppings [ toppings ' ( \"brownie-bits\" ) ] #:sprinkles [ sprinkles \"chocolate\" ] #:syrup [ syrup \"caramel\" ] ) ( format \"A sundae with ~a ice cream, ~a, ~a sprinkles, and ~a syrup.\" ( string-join ice-cream #:before-last \" and \" ) ( string-join toppings #:before-last \" and \" ) sprinkles syrup ) )\n> > ( keyword-apply/dict sundae ' ( ( #:ice-cream \"chocolate\" ) ) ' ( ) )\n> \"A sundae with chocolate ice cream, brownie-bits, chocolate sprinkles, and caramel syrup.\"\n> > ( keyword-apply/dict sundae ( hash ' #:toppings ' ( \"cookie-dough\" ) ' #:sprinkles \"rainbow\" ' #:syrup \"chocolate\" ) ' ( ) )\n> \"A sundae with vanilla ice cream, cookie-dough, rainbow sprinkles, and chocolate syrup.\"\n> > ( keyword-apply/dict sundae #:sprinkles \"rainbow\" ( hash ' #:toppings ' ( \"cookie-dough\" ) ' #:syrup \"chocolate\" ) ' ( ) )\n> \"A sundae with vanilla ice cream, cookie-dough, rainbow sprinkles, and chocolate syrup.\"\n> ```\n\nAdded in version 7.9 of package base.\n\n------------------------------------------------------------------------\n\n# 4.19 Sets\n\n### 4.19 Sets\n\nA set represents a collection of distinct elements. The following datatypes are all sets:\n\n- [hash sets](#%28tech._hash._set%29);\n\n- [lists](pairs.html#%28tech._list%29) using [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) to compare elements; and\n\n- [structures](structures.html#%28tech._structure%29) whose types implement the [gen:set](#%28form._%28%28lib._racket%2Fset..rkt%29._gen~3aset%29%29) [generic interface](struct-generics.html#%28tech._generic._interface%29).\n\n| | |\n|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/set]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/set]() and [racket](index.html) libraries, but not [racket/base](index.html).\n\n#### 4.19.1 Hash Sets\n\nA hash set is a set whose elements are compared via [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) and partitioned via [equal-hash-code](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-hash-code%29%29), [equal-always-hash-code](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always-hash-code%29%29), [eqv-hash-code](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv-hash-code%29%29), or [eq-hash-code](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq-hash-code%29%29). A hash set is either immutable or mutable; mutable hash sets retain their elements either strongly or weakly.\n\n> > > Like operations on immutable hash tables, “constant time” hash set operations actually require O(log N) time for a set of size N.\n\nA hash set can be used as a [stream](streams.html#%28tech._stream%29) (see [Streams](streams.html)) and thus as a single-valued [sequence](sequences.html#%28tech._sequence%29) (see [Sequences](sequences.html)). The elements of the set serve as elements of the stream or sequence. If an element is added to or removed from the hash set during iteration, then an iteration step may fail with [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29), or the iteration may skip or duplicate elements. See also [in-set](#%28def._%28%28lib._racket%2Fset..rkt%29._in-set%29%29).\n\nTwo hash sets are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) when they use the same element-comparison procedure ([equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)), both hold elements strongly or weakly, have the same mutability, and have equivalent elements. Immutable hash sets support effectively constant-time access and update, just like mutable hash sets; the constant on immutable operations is usually larger, but the functional nature of immutable hash sets can pay off in certain algorithms.\n\nAll hash sets [implement](struct-generics.html#%28tech._implemented._generic._method%29) [set->stream](#%28def._%28%28lib._racket%2Fset..rkt%29._set-~3estream%29%29), [set-empty?](#%28def._%28%28lib._racket%2Fset..rkt%29._set-empty~3f%29%29), [set-member?](#%28def._%28%28lib._racket%2Fset..rkt%29._set-member~3f%29%29), [set-count](#%28def._%28%28lib._racket%2Fset..rkt%29._set-count%29%29), [subset?](#%28def._%28%28lib._racket%2Fset..rkt%29._subset~3f%29%29), [proper-subset?](#%28def._%28%28lib._racket%2Fset..rkt%29._proper-subset~3f%29%29), [set-map](#%28def._%28%28lib._racket%2Fset..rkt%29._set-map%29%29), [set-for-each](#%28def._%28%28lib._racket%2Fset..rkt%29._set-for-each%29%29), [set-copy](#%28def._%28%28lib._racket%2Fset..rkt%29._set-copy%29%29), [set-copy-clear](#%28def._%28%28lib._racket%2Fset..rkt%29._set-copy-clear%29%29), [set->list](#%28def._%28%28lib._racket%2Fset..rkt%29._set-~3elist%29%29), and [set-first](#%28def._%28%28lib._racket%2Fset..rkt%29._set-first%29%29). Immutable hash sets in addition [implement](struct-generics.html#%28tech._implemented._generic._method%29) [set-add](#%28def._%28%28lib._racket%2Fset..rkt%29._set-add%29%29), [set-remove](#%28def._%28%28lib._racket%2Fset..rkt%29._set-remove%29%29), [set-clear](#%28def._%28%28lib._racket%2Fset..rkt%29._set-clear%29%29), [set-union](#%28def._%28%28lib._racket%2Fset..rkt%29._set-union%29%29), [set-intersect](#%28def._%28%28lib._racket%2Fset..rkt%29._set-intersect%29%29), [set-subtract](#%28def._%28%28lib._racket%2Fset..rkt%29._set-subtract%29%29), and [set-symmetric-difference](#%28def._%28%28lib._racket%2Fset..rkt%29._set-symmetric-difference%29%29). Mutable hash sets in addition [implement](struct-generics.html#%28tech._implemented._generic._method%29) [set-add!](#%28def._%28%28lib._racket%2Fset..rkt%29._set-add%21%29%29), [set-remove!](#%28def._%28%28lib._racket%2Fset..rkt%29._set-remove%21%29%29), [set-clear!](#%28def._%28%28lib._racket%2Fset..rkt%29._set-clear%21%29%29), [set-union!](#%28def._%28%28lib._racket%2Fset..rkt%29._set-union%21%29%29), [set-intersect!](#%28def._%28%28lib._racket%2Fset..rkt%29._set-intersect%21%29%29), [set-subtract!](#%28def._%28%28lib._racket%2Fset..rkt%29._set-subtract%21%29%29), and [set-symmetric-difference!](#%28def._%28%28lib._racket%2Fset..rkt%29._set-symmetric-difference%21%29%29).\n\nOperations on sets that contain elements that are mutated are unpredictable in much the same way that [hash table](hashtables.html#%28tech._hash._table%29) operations are unpredictable when keys are mutated.\n\n> ```\n(set-equal? x)  →  boolean?\n  x : any/c\n\n(set-equal-always? x)  →  boolean?\n  x : any/c\n\n(set-eqv? x)  →  boolean?\n  x : any/c\n\n(set-eq? x)  →  boolean?\n  x : any/c\n```"} {"text": "# 4.18 Dictionaries\nReturns #t if x is a hash set that compares elements with equal?, equal-always?, eqv?, or eq?, respectively; returns #f otherwise.\nChanged in version 8.5.0.3 of package base: Added set-equal-always?.\n> ```\n(set? x)  →  boolean?\n  x : any/c\n(set-mutable? x)  →  boolean?\n  x : any/c\n(set-weak? x)  →  boolean?\n  x : any/c```\nReturns #t if x is a [hash set](#%28tech._hash._set%29) that is respectively immutable, mutable with strongly-held keys, or mutable with weakly-held keys; returns #f otherwise.\n> ```\n(set v ...) → (and/c generic-set? set-equal? set?)\n  v : any/c\n(setalw v ...)  →  (and/c generic-set? set-equal-always? set?)\n  v : any/c\n(seteqv v ...)  →  (and/c generic-set? set-eqv? set?)\n  v : any/c\n(seteq v ...)  →  (and/c generic-set? set-eq? set?)\n  v : any/c\n(mutable-set v ...)\n  →  (and/c generic-set? set-equal? set-mutable?)\n  v : any/c\n(mutable-setalw v ...)\n  →  (and/c generic-set? set-equal-always? set-mutable?)\n  v : any/c\n(mutable-seteqv v ...)\n  →  (and/c generic-set? set-eqv? set-mutable?)\n  v : any/c\n(mutable-seteq v ...)\n  →  (and/c generic-set? set-eq? set-mutable?)\n  v : any/c\n(weak-set v ...)  →  (and/c generic-set? set-equal? set-weak?)\n  v : any/c\n(weak-setalw v ...)\n  →  (and/c generic-set? set-equal-always? set-weak?)\n  v : any/c\n(weak-seteqv v ...)  →  (and/c generic-set? set-eqv? set-weak?)\n  v : any/c\n(weak-seteq v ...)  →  (and/c generic-set? set-eq? set-weak?)\n  v : any/c"} {"text": "# 4.18 Dictionaries\n```\nCreates a hash set with the given vs as elements. The elements are added in the order that they appear as arguments, so in the case of sets that use equal?, equal-always?, or eqv?, an earlier element may be replaced by a later element that is equal?, equal-always?, or eqv?, but not eq?.\n\nChanged in version 8.5.0.3 of package base: Added setalw, mutable-setalw, and weak-setalw.\n\n> ```\n(list → set lst)  →  (and/c generic-set? set-equal? set?)\n  lst : list?\n\n(list → setalw lst)\n  →  (and/c generic-set? set-equal-always? set?)\n  lst : list?\n\n(list → seteqv lst)  →  (and/c generic-set? set-eqv? set?)\n  lst : list?\n\n(list → seteq lst)  →  (and/c generic-set? set-eq? set?)\n  lst : list?\n\n(list → mutable-set lst)\n  →  (and/c generic-set? set-equal? set-mutable?)\n  lst : list?\n\n(list → mutable-setalw lst)\n  →  (and/c generic-set? set-equal-always? set-mutable?)\n  lst : list?\n\n(list → mutable-seteqv lst)\n  →  (and/c generic-set? set-eqv? set-mutable?)\n  lst : list?\n\n(list → mutable-seteq lst)\n  →  (and/c generic-set? set-eq? set-mutable?)\n  lst : list?\n\n(list → weak-set lst)\n  →  (and/c generic-set? set-equal? set-weak?)\n  lst : list?\n\n(list → weak-setalw lst)\n  →  (and/c generic-set? set-equal-always? set-weak?)\n  lst : list?\n\n(list → weak-seteqv lst)\n  →  (and/c generic-set? set-eqv? set-weak?)\n  lst : list?\n\n(list → weak-seteq lst)  →  (and/c generic-set? set-eq? set-weak?)\n  lst : list?```\n\n\nCreates a [hash set](#%28tech._hash._set%29) with the elements of the given lst as the elements of the set. Equivalent to ([apply](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._apply%29%29) [set](#%28def._%28%28lib._racket%2Fset..rkt%29._set%29%29) lst), ([apply](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._apply%29%29) [setalw](#%28def._%28%28lib._racket%2Fset..rkt%29._setalw%29%29) lst), ([apply](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._apply%29%29) [seteqv](#%28def._%28%28lib._racket%2Fset..rkt%29._seteqv%29%29) lst), ([apply](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._apply%29%29) [seteq](#%28def._%28%28lib._racket%2Fset..rkt%29._seteq%29%29) lst), and so on, respectively.\n\nChanged in version 8.5.0.3 of package base: Added [list->setalw](#%28def._%28%28lib._racket%2Fset..rkt%29._list-~3esetalw%29%29), [list->mutable-setalw](#%28def._%28%28lib._racket%2Fset..rkt%29._list-~3emutable-setalw%29%29), and [list->weak-setalw](#%28def._%28%28lib._racket%2Fset..rkt%29._list-~3eweak-setalw%29%29).\n\n>
\n\n

syntax

\n\n

([for/set](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fset%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for/seteq](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fseteq%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for/seteqv](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fseteqv%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for/setalw](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fsetalw%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for*/set](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2A%2Fset%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for*/seteq](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2A%2Fseteq%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for*/seteqv](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2A%2Fseteqv%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for*/setalw](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2A%2Fsetalw%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for/mutable-set](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fmutable-set%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for/mutable-seteq](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fmutable-seteq%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for/mutable-seteqv](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fmutable-seteqv%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for/mutable-setalw](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fmutable-setalw%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for*/mutable-set](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2A%2Fmutable-set%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for*/mutable-seteq](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2A%2Fmutable-seteq%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for*/mutable-seteqv](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2A%2Fmutable-seteqv%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for*/mutable-setalw](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2A%2Fmutable-setalw%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for/weak-set](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fweak-set%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for/weak-seteq](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fweak-seteq%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for/weak-seteqv](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fweak-seteqv%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for/weak-setalw](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fweak-setalw%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for*/weak-set](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2A%2Fweak-set%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for*/weak-seteq](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2A%2Fweak-seteq%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for*/weak-seteqv](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2A%2Fweak-seteqv%29%29) (for-clause ...) body ...+)

\n\n

syntax

\n\n

([for*/weak-setalw](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2A%2Fweak-setalw%29%29) (for-clause ...) body ...+)

\n\nAnalogous to [for/list](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2Flist%29%29) and [for*/list](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%2Flist%29%29), but to construct a [hash set](#%28tech._hash._set%29) instead of a list.\n\nChanged in version 8.5.0.3 of package base: Added [for/setalw](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fsetalw%29%29), [for/mutable-setalw](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fmutable-setalw%29%29), and [for/weak-setalw](#%28form._%28%28lib._racket%2Fset..rkt%29._for%2Fweak-setalw%29%29).\n\n> ```\n(in-immutable-set st)  →  sequence?\n  st : set?\n\n(in-mutable-set st)  →  sequence?\n  st : set-mutable?\n\n(in-weak-set st)  →  sequence?\n  st : set-weak?\n```"} {"text": "# 4.18 Dictionaries\nExplicitly converts a specific kind of hash set to a sequence for use with for forms.\nAs with in-list and some other sequence constructors, in-immutable-set performs better when it appears directly in a for clause.\nThese sequence constructors are compatible with Custom Hash Sets.\nAdded in version 6.4.0.7 of package base."} {"text": "#### 4.19.2 Set Predicates and Contracts\n> ```\n(generic-set? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a [set](#%28tech._set%29); returns #f otherwise.\nExamples:\n> ```racket\n> > ( generic-set? ( list 1 2 3 ) )\n> #t\n> > ( generic-set? ( set 1 2 3 ) )\n> #t\n> > ( generic-set? ( mutable-seteq 1 2 3 ) )\n> #t\n> > ( generic-set? ( vector 1 2 3 ) )\n> #f\n> ```\n> ```\n(parameter)\t→\n```\n(parameter)\t→```\n\n\nRecognizes sets that support all of the methods from [gen:set](#%28form._%28%28lib._racket%2Fset..rkt%29._gen~3aset%29%29) named by the syms.\n\n> ```\n(set/c elem/c\n   [ #:cmp cmp        \n    #:kind kind        \n    #:lazy? lazy?        \n    #:equal-key/c equal-key/c)   →   contract?\n\n  elem/c : chaperone-contract?\n   cmp   :   (or/c 'dont-care 'equal 'equal-always 'eqv 'eq)\n      =   'dont-care\n\n   kind   :   (or/c 'dont-care 'immutable 'mutable 'weak 'mutable-or-weak)\n      =   'immutable\n\n   lazy?   :   any/c   =   ( not ( and ( equal? kind ' immutable )\n> ( flat-contract? elem/c ) ) )\n\n  equal-key/c : contract? = any/c\n```\nConstructs a contract that recognizes sets whose elements match elem/c.\nIf kind is 'immutable, 'mutable, or 'weak, the resulting contract accepts only hash sets that are respectively immutable, mutable with strongly-held keys, or mutable with weakly-held keys. If kind is 'mutable-or-weak, the resulting contract accepts any mutable hash sets, regardless of key-holding strength.\nIf cmp is 'equal, 'equal-always, 'eqv, or 'eq, the resulting contract accepts only hash sets that compare elements using equal?, equal-always?, eqv?, or eq?, respectively."} {"text": "# 4.18 Dictionaries\nIf cmp is 'eqv or 'eq, then elem/c must be a flat contract.\nIf cmp and kind are both 'dont-care, then the resulting contract will accept any kind of set, not just hash sets.\nIf lazy? is not #f, then the elements of the set are not checked immediately by the contract and only the set itself is checked (according to the cmp and kind arguments). If lazy? is #f, then the elements are checked immediately by the contract. The lazy? argument is ignored when the set contract accepts generic sets (i.e., when cmp and kind are both 'dont-care); in that case, the value being checked in that case is a list?, then the contract is not lazy otherwise the contract is lazy.\nIf kind allows mutable sets (i.e., is 'dont-care, 'mutable, 'weak, or 'mutable-or-weak) and lazy? is #f, then the elements are checked both immediately and when they are accessed from the set.\nThe equal-key/c contract is used when values are passed to the comparison and hashing functions used internally.\nThe result contract will be a flat contract when elem/c and equal-key/c are both flat contracts, lazy? is #f, and kind is 'immutable. The result will be a chaperone contract when elem/c is a chaperone contract.\nChanged in version 8.3.0.9 of package base: Added support for random generation. \nChanged in version 8.5.0.3: Added 'equal-always support for cmp."} {"text": "#### 4.19.3 Generic Set Interface\n>
\n

syntax

\n

gen:set

\nA generic interface (see Generic Interfaces) that supplies set method implementations for a structure type via the #:methods option of struct definitions. This interface can be used to implement any of the methods documented as Set Methods.\nExamples:\n> ```racket\n> > ( struct binary-set [ integer ] #:transparent #:methods gen:set [ ( define ( set-member? st i ) ( bitwise-bit-set? ( binary-set-integer st ) i ) ) ( define ( set-add st i ) ( binary-set ( bitwise-ior ( binary-set-integer st ) ( arithmetic-shift 1 i ) ) ) ) ( define ( set-remove st i ) ( binary-set ( bitwise-and ( binary-set-integer st ) ( bitwise-not ( arithmetic-shift 1 i ) ) ) ) ) ] )\n> > ( define bset ( binary-set 5 ) )\n> > bset\n> (binary-set 5)\n> > ( generic-set? bset )\n> #t\n> > ( set-member? bset 0 )\n> #t\n> > ( set-member? bset 1 )\n> #f\n> > ( set-member? bset 2 )\n> #t\n> > ( set-add bset 4 )\n> (binary-set 21)\n> > ( set-remove bset 2 )\n> (binary-set 1)\n> ```"} {"text": "##### 4.19.3.1 Set Methods\nThe methods of gen:set can be classified into three categories, as determined by their fallback implementations:\n1. methods with no fallbacks,\n2. methods whose fallbacks depend on other, non-fallback methods,\n3. and methods whose fallbacks can depend on either fallback or non-fallback methods.\nAs an example, implementing the following methods would guarantee that all the methods in gen:set would at least have a fallback method:\n- set-member?\n- set-add\n- set-add!\n- set-remove\n- set-remove!\n- set-first\n- set-empty?\n- set-copy-clear\nThere may be other such subsets of methods that would guarantee at least a fallback for every method.\n> ```\n(set-member? st v) → boolean?\n  st : generic-set?\n  v : any/c```\nReturns #t if v is in st, #f otherwise. Has no fallback.\n> ```\n(set-add st v)  →  generic-set?\n  st : generic-set?\n  v : any/c\n```\n(parameter)\t→```\n\n\nAdds the element v to st. This operation runs in constant time for [hash sets](#%28tech._hash._set%29). Has no fallback.\n\nFor [hash sets](#%28tech._hash._set%29), see also the [caveats concerning concurrent modification](hashtables.html#%28elem._%28caveat._concurrency%29%29) for hash tables, which applies to hash sets.\n\n> ```\n(set-remove st v)  →  generic-set?\n  st : generic-set?\n  v : any/c\n```\n(parameter)\t→```\nRemoves the element v from st. This operation runs in constant time for [hash sets](#%28tech._hash._set%29). Has no fallback."} {"text": "# 4.18 Dictionaries\nFor [hash sets](#%28tech._hash._set%29), see also the [caveats concerning concurrent modification](hashtables.html#%28elem._%28caveat._concurrency%29%29) for hash tables, which applies to hash sets.\n> ```\n(set-empty? st)  →  boolean?\n  st : generic-set?\n```\nReturns #t if st has no members; returns #f otherwise.\n\nSupported for any st that implements set → stream or set-count.\n\n> ```\n(set-count st)  →  exact-nonnegative-integer?\n  st : generic-set?```\n\n\nReturns the number of elements in st.\n\nSupported for any st that [supports](struct-generics.html#%28tech._supported._generic._method%29) [set->stream](#%28def._%28%28lib._racket%2Fset..rkt%29._set-~3estream%29%29).\n\n> ```\n(set-first st)  →  any/c\n  st : (and/c generic-set? (not/c set-empty?))\n```\nProduces an unspecified element of st. Multiple uses of set-first on st produce the same result.\nSupported for any st that implements set → stream.\n> ```\n(set-rest st)  →  generic-set?\n  st : (and/c generic-set? (not/c set-empty?))```\nProduces a set that includes all elements of st except ([set-first](#%28def._%28%28lib._racket%2Fset..rkt%29._set-first%29%29) st).\nSupported for any st that [implements](struct-generics.html#%28tech._implemented._generic._method%29) [set-remove](#%28def._%28%28lib._racket%2Fset..rkt%29._set-remove%29%29) and either [set-first](#%28def._%28%28lib._racket%2Fset..rkt%29._set-first%29%29) or [set->stream](#%28def._%28%28lib._racket%2Fset..rkt%29._set-~3estream%29%29).\n> ```\n(set → stream st)  →  stream?\n  st : generic-set?"} {"text": "# 4.18 Dictionaries\n```\nProduces a stream containing the elements of st.\n\nSupported for any st that implements:\n\n- set → list\n\n- in-set\n\n- set-empty?, set-first, set-rest\n\n- set-empty?, set-first, set-remove\n\n- set-count, set-first, set-rest\n\n- set-count, set-first, set-remove\n\n> ```\n(set-copy st)  →  generic-set?\n  st : generic-set?```\n\n\nProduces a new, mutable set of the same type and with the same elements as st.\n\nSupported for any st that [supports](struct-generics.html#%28tech._supported._generic._method%29) [set->stream](#%28def._%28%28lib._racket%2Fset..rkt%29._set-~3estream%29%29) and [implements](struct-generics.html#%28tech._implemented._generic._method%29) [set-copy-clear](#%28def._%28%28lib._racket%2Fset..rkt%29._set-copy-clear%29%29) and [set-add!](#%28def._%28%28lib._racket%2Fset..rkt%29._set-add%21%29%29).\n\n> ```\n(set-copy-clear st)  →  (and/c generic-set? set-empty?)\n  st : generic-set?\n```\nProduces a new, empty set of the same type, mutability, and key strength as st.\nA difference between set-copy-clear and set-clear is that the latter conceptually iterates set-remove on the given set, and so it preserves any contract on the given set. The set-copy-clear function produces a new set without any contracts.\nThe set-copy-clear function must call concrete set constructors and thus has no generic fallback.\n> ```\n(set-clear st)  →  (and/c generic-set? set-empty?)\n  st : generic-set?```\nProduces a set like st but with all elements removed."} {"text": "# 4.18 Dictionaries\nSupported for any st that [implements](struct-generics.html#%28tech._implemented._generic._method%29) [set-remove](#%28def._%28%28lib._racket%2Fset..rkt%29._set-remove%29%29) and [supports](struct-generics.html#%28tech._supported._generic._method%29) [set->stream](#%28def._%28%28lib._racket%2Fset..rkt%29._set-~3estream%29%29).\n> ```\n(parameter)\t→\n```\nRemoves all elements from st.\n\nSupported for any st that implements set-remove! and either supports set → stream or implements set-first and either set-count or set-empty?.\n\nFor hash sets, see also the caveats concerning concurrent modification for hash tables, which applies to hash sets.\n\n> ```\n(set-union st0 st ...) → generic-set?\n  st0 : generic-set?\n  st : generic-set?```\n\n\nProduces a set of the same type as st0 that includes the elements from st0 and all of the sts.\n\nIf st0 is a list, each st must also be a list. This operation runs on lists in time proportional to the total size of the sts times the size of the result.\n\nIf st0 is a [hash set](#%28tech._hash._set%29), each st must also be a [hash set](#%28tech._hash._set%29) that uses the same comparison function ([equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)). The mutability and key strength of the hash sets may differ. This operation runs on hash sets in time proportional to the total size of all of the sets except the largest immutable set.\n\nAt least one set must be provided to [set-union](#%28def._%28%28lib._racket%2Fset..rkt%29._set-union%29%29) to determine the type of the resulting set (list, hash set, etc.). If there is a case where [set-union](#%28def._%28%28lib._racket%2Fset..rkt%29._set-union%29%29) may be applied to zero arguments, instead pass an empty set of the intended type as the first argument.\n\nSupported for any st that [implements](struct-generics.html#%28tech._implemented._generic._method%29) [set-add](#%28def._%28%28lib._racket%2Fset..rkt%29._set-add%29%29) and [supports](struct-generics.html#%28tech._supported._generic._method%29) [set->stream](#%28def._%28%28lib._racket%2Fset..rkt%29._set-~3estream%29%29).\n\nExamples:\n\n> ```racket\n> > ( set-union ( set ) )\n> (set)\n> > ( set-union ( seteq ) )\n> (seteq)\n> > ( set-union ( set 1 2 ) ( set 2 3 ) )\n> (set 1 2 3)\n> > ( set-union ( list 1 2 ) ( list 2 3 ) )\n> '(3 1 2)\n> > ( set-union ( set 1 2 ) ( seteq 2 3 ) )\n> set-union: set arguments have incompatible equivalence\n> predicates\n> first set: (set 1 2)\n> incompatible set: (seteq 2 3)\n> ; Sets of different types cannot be unioned\n> ```\n\n> ```\n(parameter)\t→\n```"} {"text": "# 4.18 Dictionaries\nAdds the elements from all of the sts to st0.\nIf st0 is a hash set, each st must also be a hash set that uses the same comparison function (equal?, equal-always?, eqv?, or eq?). The mutability and key strength of the hash sets may differ. This operation runs on hash sets in time proportional to the total size of the sts.\nSupported for any st that implements set-add! and supports set → stream.\nFor hash sets, see also the caveats concerning concurrent modification for hash tables, which applies to hash sets.\n> ```\n(set-intersect st0 st ...) → generic-set?\n  st0 : generic-set?\n  st : generic-set?```\nProduces a set of the same type as st0 that includes the elements from st0 that are also contained by all of the sts.\nIf st0 is a list, each st must also be a list. This operation runs on lists in time proportional to the total size of the sts times the size of st0.\nIf st0 is a [hash set](#%28tech._hash._set%29), each st must also be a [hash set](#%28tech._hash._set%29) that uses the same comparison function ([equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)). The mutability and key strength of the hash sets may differ. This operation runs on hash sets in time proportional to the size of the smallest immutable set."} {"text": "# 4.18 Dictionaries\nSupported for any st that [implements](struct-generics.html#%28tech._implemented._generic._method%29) either [set-remove](#%28def._%28%28lib._racket%2Fset..rkt%29._set-remove%29%29) or both [set-clear](#%28def._%28%28lib._racket%2Fset..rkt%29._set-clear%29%29) and [set-add](#%28def._%28%28lib._racket%2Fset..rkt%29._set-add%29%29), and [supports](struct-generics.html#%28tech._supported._generic._method%29) [set->stream](#%28def._%28%28lib._racket%2Fset..rkt%29._set-~3estream%29%29).\n> ```\n(parameter)\t→\n```\nRemoves every element from st0 that is not contained by all of the sts.\n\nIf st0 is a hash set, each st must also be a hash set that uses the same comparison function (equal?, equal-always?, eqv?, or eq?). The mutability and key strength of the hash sets may differ. This operation runs on hash sets in time proportional to the size of st0.\n\nSupported for any st that implements set-remove! and supports set → stream.\n\nFor hash sets, see also the caveats concerning concurrent modification for hash tables, which applies to hash sets.\n\n> ```\n(set-subtract st0 st ...) → generic-set?\n  st0 : generic-set?\n  st : generic-set?```\n\n\nProduces a set of the same type as st0 that includes the elements from st0 that are not contained by any of the sts.\n\nIf st0 is a list, each st must also be a list. This operation runs on lists in time proportional to the total size of the sts times the size of st0.\n\nIf st0 is a [hash set](#%28tech._hash._set%29), each st must also be a [hash set](#%28tech._hash._set%29) that uses the same comparison function ([equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)). The mutability and key strength of the hash sets may differ. This operation runs on hash sets in time proportional to the size of st0.\n\nSupported for any st that [implements](struct-generics.html#%28tech._implemented._generic._method%29) either [set-remove](#%28def._%28%28lib._racket%2Fset..rkt%29._set-remove%29%29) or both [set-clear](#%28def._%28%28lib._racket%2Fset..rkt%29._set-clear%29%29) and [set-add](#%28def._%28%28lib._racket%2Fset..rkt%29._set-add%29%29), and [supports](struct-generics.html#%28tech._supported._generic._method%29) [set->stream](#%28def._%28%28lib._racket%2Fset..rkt%29._set-~3estream%29%29).\n\n> ```\n(parameter)\t→\n```"} {"text": "# 4.18 Dictionaries\nRemoves every element from st0 that is contained by any of the sts.\nIf st0 is a hash set, each st must also be a hash set that uses the same comparison function (equal?, equal-always?, eqv?, or eq?). The mutability and key strength of the hash sets may differ. This operation runs on hash sets in time proportional to the size of st0.\nSupported for any st that implements set-remove! and supports set → stream.\nFor hash sets, see also the caveats concerning concurrent modification for hash tables, which applies to hash sets.\n> ```\n(set-symmetric-difference st0 st ...) → generic-set?\n  st0 : generic-set?\n  st : generic-set?```\nProduces a set of the same type as st0 that includes all of the elements contained an odd number of times in st0 and the sts.\nIf st0 is a list, each st must also be a list. This operation runs on lists in time proportional to the total size of the sts times the size of st0.\nIf st0 is a [hash set](#%28tech._hash._set%29), each st must also be a [hash set](#%28tech._hash._set%29) that uses the same comparison function ([equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)). The mutability and key strength of the hash sets may differ. This operation runs on hash sets in time proportional to the total size of all of the sets except the largest immutable set."} {"text": "# 4.18 Dictionaries\nSupported for any st that [implements](struct-generics.html#%28tech._implemented._generic._method%29) [set-remove](#%28def._%28%28lib._racket%2Fset..rkt%29._set-remove%29%29) or both [set-clear](#%28def._%28%28lib._racket%2Fset..rkt%29._set-clear%29%29) and [set-add](#%28def._%28%28lib._racket%2Fset..rkt%29._set-add%29%29), and [supports](struct-generics.html#%28tech._supported._generic._method%29) [set->stream](#%28def._%28%28lib._racket%2Fset..rkt%29._set-~3estream%29%29).\nExample:\n> ```racket\n> > ( set-symmetric-difference ( set 1 ) ( set 1 2 ) ( set 1 2 3 ) )\n> (set 1 3)\n> ```\n> ```\n(parameter)\t→"} {"text": "# 4.18 Dictionaries\n```\nAdds and removes elements of st0 so that it includes all of the elements contained an odd number of times in the sts and the original contents of st0.\n\nIf st0 is a hash set, each st must also be a hash set that uses the same comparison function (equal?, equal-always?, eqv?, or eq?). The mutability and key strength of the hash sets may differ. This operation runs on hash sets in time proportional to the total size of the sts.\n\nSupported for any st that implements set-remove! and supports set → stream.\n\nFor hash sets, see also the caveats concerning concurrent modification for hash tables, which applies to hash sets.\n\n> ```\n(set=? st st2) → boolean?\n  st : generic-set?\n  st2 : generic-set?```\n\n\nReturns #t if st and st2 contain the same members; returns #f otherwise.\n\nIf st is a list, then st2 must also be a list. This operation runs on lists in time proportional to the size of st times the size of st2.\n\nIf st is a [hash set](#%28tech._hash._set%29), then st2 must also be a [hash set](#%28tech._hash._set%29) that uses the same comparison function ([equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)). The mutability and key strength of the hash sets may differ. This operation runs on hash sets in time proportional to the size of st plus the size of st2.\n\nSupported for any st and st2 that both [support](struct-generics.html#%28tech._supported._generic._method%29) [subset?](#%28def._%28%28lib._racket%2Fset..rkt%29._subset~3f%29%29); also supported for any if st2 that [implements](struct-generics.html#%28tech._implemented._generic._method%29) [set=?](#%28def._%28%28lib._racket%2Fset..rkt%29._set~3d~3f%29%29) regardless of st.\n\nExamples:\n\n> ```racket\n> > ( set=? ( list 1 2 ) ( list 2 1 ) )\n> #t\n> > ( set=? ( set 1 ) ( set 1 2 3 ) )\n> #f\n> > ( set=? ( set 1 2 3 ) ( set 1 ) )\n> #f\n> > ( set=? ( set 1 2 3 ) ( set 1 2 3 ) )\n> #t\n> > ( set=? ( seteq 1 2 ) ( mutable-seteq 2 1 ) )\n> #t\n> > ( set=? ( seteq 1 2 ) ( seteqv 1 2 ) )\n> set=?: set arguments have incompatible equivalence\n> predicates\n> first set: (seteq 1 2)\n> incompatible set: (seteqv 1 2)\n> ; Sets of different types cannot be compared\n> ```\n\n> ```\n(subset? st st2)  →  boolean?\n  st : generic-set?\n  st2 : generic-set?\n```"} {"text": "# 4.18 Dictionaries\nReturns #t if st2 contains every member of st; returns #f otherwise.\nIf st is a list, then st2 must also be a list. This operation runs on lists in time proportional to the size of st times the size of st2.\nIf st is a hash set, then st2 must also be a hash set that uses the same comparison function (equal?, equal-always?, eqv?, or eq?). The mutability and key strength of the hash sets may differ. This operation runs on hash sets in time proportional to the size of st.\nSupported for any st that supports set → stream.\nExamples:\n> ```racket\n> > ( subset? ( set 1 ) ( set 1 2 3 ) )\n> #t\n> > ( subset? ( set 1 2 3 ) ( set 1 ) )\n> #f\n> > ( subset? ( set 1 2 3 ) ( set 1 2 3 ) )\n> #t\n> ```\n> ```\n(proper-subset? st st2)  →  boolean?\n  st : generic-set?\n  st2 : generic-set?```\nReturns #t if st2 contains every member of st and at least one additional element; returns #f otherwise.\nIf st is a list, then st2 must also be a list. This operation runs on lists in time proportional to the size of st times the size of st2."} {"text": "# 4.18 Dictionaries\nIf st is a [hash set](#%28tech._hash._set%29), then st2 must also be a [hash set](#%28tech._hash._set%29) that uses the same comparison function ([equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-always?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-always~3f%29%29), [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29), or [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)). The mutability and key strength of the hash sets may differ. This operation runs on hash sets in time proportional to the size of st plus the size of st2.\nSupported for any st and st2 that both [support](struct-generics.html#%28tech._supported._generic._method%29) [subset?](#%28def._%28%28lib._racket%2Fset..rkt%29._subset~3f%29%29).\nExamples:\n> ```racket\n> > ( proper-subset? ( set 1 ) ( set 1 2 3 ) )\n> #t\n> > ( proper-subset? ( set 1 2 3 ) ( set 1 ) )\n> #f\n> > ( proper-subset? ( set 1 2 3 ) ( set 1 2 3 ) )\n> #f\n> ```\n> ```\n(set → list st)  →  list?\n  st : generic-set?"} {"text": "# 4.18 Dictionaries\n```\nProduces a list containing the elements of st.\n\nSupported for any st that supports set → stream.\n\n> ```\n(set-map st proc)  →  (listof any/c)\n  st : generic-set?\n  proc : (any/c . → . any/c)```\n\n\nApplies the procedure proc to each element in st in an unspecified order, accumulating the results into a list.\n\nSupported for any st that [supports](struct-generics.html#%28tech._supported._generic._method%29) [set->stream](#%28def._%28%28lib._racket%2Fset..rkt%29._set-~3estream%29%29).\n\n> ```\n(parameter)\t→\t\n(-> any/c . → . any)\n```\nApplies proc to each element in st (for the side-effects of proc) in an unspecified order.\nSupported for any st that supports set → stream.\n> ```\n(in-set st)  →  sequence?\n  st : generic-set?```\nExplicitly converts a set to a sequence for use with [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) and other forms.\nSupported for any st that [supports](struct-generics.html#%28tech._supported._generic._method%29) [set->stream](#%28def._%28%28lib._racket%2Fset..rkt%29._set-~3estream%29%29).\n> ```\n(impersonate-hash-set st\n    inject-proc  \n    add-proc  \n    shrink-proc  \n    extract-proc  \n   [ clear-proc  \n    equal-key-proc]  \n    prop  \n    prop-val ...  \n    ...)  "} {"text": "# 4.18 Dictionaries\n  →  (and/c (or/c set-mutable? set-weak?) impersonator?)\n  st : (or/c set-mutable? set-weak?)\n  inject-proc : (or/c #f ( →  set? any/c any/c))\n  add-proc : (or/c #f ( →  set? any/c any/c))\n  shrink-proc : (or/c #f ( →  set? any/c any/c))\n  extract-proc : (or/c #f ( →  set? any/c any/c))\n  clear-proc : (or/c #f ( →  set? any)) = #f\n  equal-key-proc : (or/c #f ( →  set? any/c any/c)) = #f\n  prop : impersonator-property?\n  prop-val : any/c\n```\nImpersonates st, redirecting various set operations via the given procedures.\n\nThe inject-proc procedure is called whenever an element is temporarily put into the set for the purposes of comparing it with other elements that may already be in the set. For example, when evaluating (set-member? s e), e will be passed to the inject-proc before comparing it with other elements of s.\n\nThe add-proc procedure is called when adding an element to a set, e.g., via set-add or set-add!. The result of the add-proc is stored in the set.\n\nThe shrink-proc procedure is called when building a new set with one fewer element. For example, when evaluating (set-remove s e) or (set-remove! s e), an element is removed from a set, e.g., via set-remove or set-remove!. The result of the shrink-proc is the element actually removed from the set.\n\nThe extract-proc procedure is called when an element is pulled out of a set, e.g., by set-first. The result of the extract-proc is the element actually produced by from the set.\n\nThe clear-proc is called by set-clear and set-clear! and if it returns (as opposed to escaping, perhaps via raising an exception), the clearing operation is permitted. Its result is ignored. If clear-proc is #f, then clearing is done element by element (via calls into the other supplied procedures).\n\nThe equal-key-proc is called when an element’s hash code is needed of when an element is supplied to the underlying equality in the set. The result of equal-key-proc is used when computing the hash or comparing for equality.\n\nIf any of the inject-proc, add-proc, shrink-proc, or extract-proc arguments are #f, then they all must be #f, the clear-proc and equal-key-proc must also be #f, and there must be at least one property supplied.\n\nPairs of prop and prop-val (the number of arguments to impersonate-hash-set must be odd) add impersonator properties or override impersonator property values of st.\n\n> ```\n(chaperone-hash-set st\n    inject-proc  \n    add-proc  \n    shrink-proc  \n    extract-proc  \n   [ clear-proc  \n    equal-key-proc]  \n    prop  \n    prop-val ...  \n    ...)  \n\n  →  (and/c (or/c set? set-mutable? set-weak?) chaperone?)\n  st : (or/c set? set-mutable? set-weak?)\n  inject-proc : (or/c #f ( →  set? any/c any/c))\n  add-proc : (or/c #f ( →  set? any/c any/c))\n  shrink-proc : (or/c #f ( →  set? any/c any/c))\n  extract-proc : (or/c #f ( →  set? any/c any/c))\n  clear-proc : (or/c #f ( →  set? any)) = #f\n  equal-key-proc : (or/c #f ( →  set? any/c any/c)) = #f\n  prop : impersonator-property?\n  prop-val : any/c```\n\n\nChaperones st. Like [impersonate-hash-set](#%28def._%28%28lib._racket%2Fset..rkt%29._impersonate-hash-set%29%29) but with the constraints that the results of the inject-proc, add-proc, shrink-proc, extract-proc, and equal-key-proc must be [chaperone-of?](chaperones.html#%28def._%28%28quote._~23~25kernel%29._chaperone-of~3f%29%29) their second arguments. Also, the input may be an [immutable?](booleans.html#%28def._%28%28quote._~23~25kernel%29._immutable~3f%29%29) set.\n\n#### 4.19.4 Custom Hash Sets\n\n> ```\nsyntax\n\n(define-custom-set-types name\n> optional-predicate\n> comparison-expr\n> optional-hash-functions )\n \noptional-predicate   =  \n    |   #:elem? predicate-expr\n         \noptional-hash-functions   =  \n    |   hash1-expr\n    |   hash1-expr hash2-expr\n```"} {"text": "# 4.18 Dictionaries\n(parameter)\t→\t\n(-> any/c . → . boolean?)```\nCreates a new set type based on the given comparison function eql?, hash functions hash1 and hash2, and predicate elem?. The new set type has variants that are immutable, mutable with strongly-held elements, and mutable with weakly-held elements. The given name is used when printing instances of the new set type, and the symbol who is used for reporting errors.\nThe comparison function eql? may accept 2 or 3 arguments. If it accepts 2 arguments, it given two elements to compare them. If it accepts 3 arguments and does not accept 2 arguments, it is also given a recursive comparison function that handles data cycles when comparing sub-parts of the elements.\nThe hash functions hash1 and hash2 may accept 1 or 2 arguments. If either hash function accepts 1 argument, it is applied to a element to compute the corresponding hash value. If either hash function accepts 2 arguments and does not accept 1 argument, it is also given a recursive hash function that handles data cycles when computing hash values of sub-parts of the elements.\nThe predicate elem? must accept 1 argument and is used to recognize valid elements for the new set type.\nProduces seven values:\n- a predicate recognizing all instances of the new set type,\n- a predicate recognizing weak instances,\n- a predicate recognizing mutable instances,\n- a predicate recognizing immutable instances,\n- a constructor for weak instances,\n- a constructor for mutable instances, and\n- a constructor for immutable instances."} {"text": "# 4.18 Dictionaries\nSee [define-custom-set-types](#%28form._%28%28lib._racket%2Fset..rkt%29._define-custom-set-types%29%29) for an example.\n------------------------------------------------------------------------"} {"text": "# 4.20 Procedures"} {"text": "### 4.20 Procedures\n> ```\n(procedure? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a procedure, #f otherwise.\n\n> ```\n(apply proc v ... lst #: kw-arg ...) → any\n  proc : procedure?\n  v : any/c\n  lst : list?\n  kw-arg : any/c```\n\n\n> > > \"+\"[The apply Function](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=application.html%23%2528part._apply%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces [apply](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._apply%29%29).\n\nApplies proc using the content of ([list*](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%2A%29%29) v [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) lst) as the (by-position) arguments. The #:\\ kw-arg sequence is also supplied as keyword arguments to proc, where #:\\ stands for any keyword.\n\nThe given proc must accept as many arguments as the number of vs plus length of lst, it must accept the supplied keyword arguments, and it must not require any other keyword arguments; otherwise, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. The given proc is called in tail position with respect to the [apply](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._apply%29%29) call.\n\nExamples:\n\n> ```racket\n> > ( apply + ' ( 1 2 3 ) )\n> 6\n> > ( apply + 1 2 ' ( 3 ) )\n> 6\n> > ( apply + ' ( ) )\n> 0\n> > ( apply sort ( list ( list ' ( 2 ) ' ( 1 ) ) < ) #:key car )> '((1) (2))\n> ```\n\n> ```\n(compose proc ...) → procedure?\n  proc : procedure?\n\n(compose1 proc ...)  →  procedure?\n  proc : procedure?\n```"} {"text": "# 4.20 Procedures\n(parameter)\t→\t\n(-> # # #f)```\nReturns a procedure that is like proc, except that its name as returned by [object-name](inspectors.html#%28def._%28%28quote._~23~25kernel%29._object-name%29%29) (and as printed for debugging) is name and its [realm](exns.html#%28tech._realm%29) (potentially used for adjusting error messages) is realm.\nThe given name and realm are used for printing and adjusting an error message if the resulting procedure is applied to the wrong number of arguments. In addition, if proc is an [accessor](define-struct.html#%28tech._accessor%29) or [mutator](define-struct.html#%28tech._mutator%29) produced by [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29), [make-struct-field-accessor](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._make-struct-field-accessor%29%29), or [make-struct-field-mutator](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._make-struct-field-mutator%29%29), the resulting procedure also uses name when its (first) argument has the wrong type. More typically, however, name is not used for reporting errors, since the procedure name is typically hard-wired into an internal check.\nChanged in version 8.4.0.2 of package base: Added the realm argument.\n> ```\n(parameter)\t→"} {"text": "# 4.20 Procedures\n```\n(parameter)\t→```\n\n\nReturns a procedure that is like proc except that, when applied to the wrong number of arguments, the resulting error hides the first argument as if the procedure had been compiled with the 'method-arity-error syntax property.\n\n> ```\n(procedure-closure-contents-eq?   proc1        \n    proc2)   →   boolean?\n\n  proc1 : procedure?\n  proc2 : procedure?\n```\n(parameter)\t→\t\n(-> listof keyword?)```\n> > > \"+\"[The apply Function](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=application.html%23%2528part._apply%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces [keyword-apply](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._keyword-apply%29%29).\nLike [apply](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._apply%29%29), but kw-lst and kw-val-lst supply by-keyword arguments in addition to the by-position arguments of the vs and lst, and in addition to the directly supplied keyword arguments in the #:\\ kw-arg sequence, where #:\\ stands for any keyword."} {"text": "# 4.20 Procedures\nThe given kw-lst must be sorted using [keyword, otherwise, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. The given kw-val-lst must have the same length as kw-lst, otherwise, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. The given proc must accept all of the keywords in kw-lst plus the #:\\s, it must not require any other keywords, and it must accept as many by-position arguments as supplied via the vs and lst; otherwise, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nExamples:\n> ```racket\n> ( define ( f x #:y y #:z [ z 10 ] ) ( list x y z ) )\n> > ( keyword-apply f ' ( #:y ) ' ( 2 ) ' ( 1 ) )\n> '(1 2 10)\n> > ( keyword-apply f ' ( #:y #:z ) ' ( 2 3 ) ' ( 1 ) )\n> '(1 2 3)\n> > ( keyword-apply f #:z 7 ' ( #:y ) ' ( 2 ) ' ( 1 ) )\n> '(1 2 7)\n> ```\n> ```\n(procedure-arity proc)  →  normalized-arity?\n  proc : procedure?"} {"text": "# 4.20 Procedures\n```\nReturns information about the number of by-position arguments accepted by proc. See also procedure-arity?, normalized-arity?, and procedure-arity-mask.\n\n> ```\n(procedure-arity? v)  →  boolean?\n  v : any/c```\n\n\nA valid arity a is one of the following:\n\n- An exact non-negative integer, which means that the procedure accepts a arguments, only.\n\n- A [arity-at-least](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._arity-at-least%29%29) instance, which means that the procedure accepts ([arity-at-least-value](#%28def._%28%28quote._~23~25kernel%29._arity-at-least-value%29%29) a) or more arguments.\n\n- A list containing integers and [arity-at-least](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._arity-at-least%29%29) instances, which means that the procedure accepts any number of arguments that can match one of the elements of a.\n\nThe result of [procedure-arity](#%28def._%28%28quote._~23~25kernel%29._procedure-arity%29%29) is always normalized in the sense of [normalized-arity?](#%28def._%28%28lib._racket%2Ffunction..rkt%29._normalized-arity~3f%29%29).\n\nExamples:\n\n> ```racket\n> > ( procedure-arity cons )\n> 2\n> > ( procedure-arity list )\n> (arity-at-least 0)\n> > ( arity-at-least? ( procedure-arity list ) )\n> #t\n> > ( arity-at-least-value ( procedure-arity list ) )\n> 0\n> > ( arity-at-least-value ( procedure-arity ( lambda ( x . y ) x ) ) )\n> 1\n> > ( procedure-arity ( case-lambda [ ( x ) 0 ] [ ( x y ) 1 ] ) )\n> '(1 2)\n> ```\n\n> ```\n(procedure-arity-mask proc)  →  exact-integer?\n  proc : procedure?\n```"} {"text": "# 4.20 Procedures\nReturns the same information as procedure-arity, but encoded differently. The arity is encoded as an exact integer mask where (bitwise-bit-set? mask n) returns true if proc accepts n arguments.\nThe mask encoding of an arity is often easier to test and manipulate, and procedure-arity-mask is sometimes faster than procedure-arity while always being at least as fast.\nAdded in version 7.0.0.11 of package base.\n> ```\n(procedure-arity-includes? proc k [kws-ok?) → boolean?\n  proc : procedure?\n  k : exact-nonnegative-integer?\n  kws-ok? : any/c = #f```\nReturns #t if the procedure can accept k by-position arguments, #f otherwise. If kws-ok? is #f, the result is #t only if proc has no required keyword arguments.\nExamples:\n> ```racket\n> > ( procedure-arity-includes? cons 2 )\n> #t\n> > ( procedure-arity-includes? display 3 )\n> #f\n> > ( procedure-arity-includes? ( lambda ( x #:y y ) x ) 1 )\n> #f\n> > ( procedure-arity-includes? ( lambda ( x #:y y ) x ) 1 #t )\n> #t\n> ```\n> ```\n(parameter)\t→\t\n(-> or/c symbol? #f)"} {"text": "# 4.20 Procedures\n```\n(parameter)\t→\t\n(-> or/c symbol? #f)```\n\n\nThe same as [procedure-reduce-arity](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._procedure-reduce-arity%29%29), but using the representation of arity described with [procedure-arity-mask](#%28def._%28%28quote._~23~25kernel%29._procedure-arity-mask%29%29).\n\nThe mask encoding of an arity is often easier to test and manipulate, and [procedure-reduce-arity-mask](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._procedure-reduce-arity-mask%29%29) is sometimes faster than [procedure-reduce-arity](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._procedure-reduce-arity%29%29) while always being at least as fast.\n\nAdded in version 7.0.0.11 of package base. \nChanged in version 8.4.0.2: Added the realm argument.\n\n> ```\n(parameter)\t→\t\n(-> listof keyword?)\n```\nReturns information about the keyword arguments required and accepted by a procedure. The first result is a list of distinct keywords (sorted by keyword ```racket\n> > ( procedure-keywords + )\n> '() '()\n> > ( procedure-keywords ( lambda ( #:tag t #:mode m ) t ) )\n> '(#:mode #:tag) '(#:mode #:tag)\n> > ( procedure-keywords ( lambda ( #:tag t #:mode [ m #f ] ) t ) )\n> '(#:tag) '(#:mode #:tag)\n> ```\n> ```\n(procedure-result-arity proc) → (or/c #f procedure-arity?)\n  proc : procedure?```"} {"text": "# 4.20 Procedures\nReturns the arity of the result of the procedure proc or #f if the number of results are not known, perhaps due to shortcomings in the implementation of [procedure-result-arity](#%28def._%28%28quote._~23~25kernel%29._procedure-result-arity%29%29) or because proc’s behavior is not sufficiently simple.\nExamples:\n> ```racket\n> > ( procedure-result-arity car )\n> 1\n> > ( procedure-result-arity values )\n> #f\n> > ( procedure-result-arity ( λ ( x ) ( apply values ( let loop ( ) ( cond [ ( zero? ( random 10 ) ) ' ( ) ] [ else ( cons 1 ( loop ) ) ] ) ) ) ) )\n> #f\n> ```\nAdded in version 6.4.0.3 of package base.\n> ```\n(parameter)\t→\t\n(-> (listof keyword?) list? any/c ... . → . any)"} {"text": "# 4.20 Procedures\n```\n(1)\t→\t\n(-> show2 1)```\n\n\nLike [procedure-reduce-arity](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._procedure-reduce-arity%29%29), but constrains the keyword arguments according to required-kws and allowed-kws, which must be sorted using [keyword ```racket\n> ( define orig-show ( make-keyword-procedure ( lambda ( kws kw-args . rest ) ( list kws kw-args rest ) ) ) ) ( define show ( procedure-reduce-keyword-arity orig-show 3 ' ( #:init ) ' ( #:extra #:init ) ) )\n> > ( show #:init 0 1 2 3 #:extra 4 )\n> '((#:extra #:init) (4 0) (1 2 3))\n> > ( show 1 )\n> arity mismatch;\n> the expected number of arguments does not match the given\n> number\n> expected: 3 plus an argument with keyword #:init plus an\n> optional argument with keyword #:extra\n> given: 1\n> arguments...:\n> 1\n> > ( show #:init 0 1 2 3 #:extra 4 #:more 7 )\n> application: procedure does not expect an argument with\n> given keyword\n> procedure: #\n> given keyword: #:more\n> arguments...:\n> 1\n> 2\n> 3\n> #:extra 4\n> #:init 0\n> #:more 7\n> ```\n\nChanged in version 8.4.0.2 of package base: Added the realm argument.\n\n> ```\n(parameter)\t→\t\n(-> listof keyword?)\n```"} {"text": "# 4.20 Procedures\nThe same as procedure-reduce-keyword-arity, but using the representation of arity described with procedure-arity-mask.\nAdded in version 7.0.0.11 of package base. \nChanged in version 8.4.0.2: Added the realm argument.\n>
\n

struct

\n
(struct arity-at-least (value)
    #:extra-constructor-name make-arity-at-least)
  value : exact-nonnegative-integer?
\nA structure type used for the result of procedure-arity. See also procedure-arity?.\n>
\n

value

\n

prop:procedure : struct-type-property?

\nA structure type property to identify structure types whose instances can be applied as procedures. In particular, when procedure? is applied to the instance, the result will be #t, and when an instance is used in the function position of an application expression, a procedure is extracted from the instance and used to complete the procedure call."} {"text": "# 4.20 Procedures\nIf the prop:procedure property value is an exact non-negative integer, it designates a field within the structure that should contain a procedure. The integer must be between 0 (inclusive) and the number of non-automatic fields in the structure type (exclusive, not counting supertype fields). The designated field must also be specified as immutable, so that after an instance of the structure is created, its procedure cannot be changed. (Otherwise, the arity and name of the instance could change, and such mutations are generally not allowed for procedures.) When the instance is used as the procedure in an application expression, the value of the designated field in the instance is used to complete the procedure call. (This procedure can be another structure that acts as a procedure; the immutability of procedure fields disallows cycles in the procedure graph, so that the procedure call will eventually continue with a non-structure procedure.) That procedure receives all of the arguments from the application expression. The procedure’s name (see object-name), arity (see procedure-arity), and keyword protocol (see procedure-keywords) are also used for the name, arity, and keyword protocol of the structure. If the value in the designated field is not a procedure, then the instance behaves like (case-lambda) (i.e., a procedure which does not accept any number of arguments). See also procedure-extract-target."} {"text": "# 4.20 Procedures\nProviding an integer proc-spec argument to make-struct-type is the same as both supplying the value with the prop:procedure property and designating the field as immutable (so that a property binding or immutable designation is redundant and disallowed).\nExamples:\n> ```racket\n> > ( struct annotated-proc ( base note ) #:property prop:procedure ( struct-field-index base ) )\n> > ( define plus1 ( annotated-proc ( lambda ( x ) ( + x 1 ) ) \"adds 1 to its argument\" ) )\n> > ( procedure? plus1 )\n> #t\n> > ( annotated-proc? plus1 )\n> #t\n> > ( plus1 10 )\n> 11\n> > ( annotated-proc-note plus1 )\n> \"adds 1 to its argument\"\n> ```\nWhen the prop:procedure value is a procedure, it should accept at least one non-keyword argument. When an instance of the structure is used in an application expression, the property-value procedure is called with the instance as the first argument. The remaining arguments to the property-value procedure are the arguments from the application expression (including keyword arguments). Thus, if the application expression provides five non-keyword arguments, the property-value procedure is called with six non-keyword arguments. The name of the instance (see object-name) and its keyword protocol (see procedure-keywords) are unaffected by the property-value procedure, but the instance’s arity is determined by subtracting one from every possible non-keyword argument count of the property-value procedure. If the property-value procedure cannot accept at least one argument, then the instance behaves like (case-lambda)."} {"text": "# 4.20 Procedures\nProviding a procedure proc-spec argument to make-struct-type is the same as supplying the value with the prop:procedure property (so that a specific property binding is disallowed).\nExamples:\n> ```racket\n> > ( struct fish ( weight color ) #:mutable #:property prop:procedure ( lambda ( f n ) ( let ( [ w ( fish-weight f ) ] ) ( set-fish-weight! f ( + n w ) ) ) ) )\n> > ( define wanda ( fish 12 ' red ) )\n> > ( fish? wanda )\n> #t\n> > ( procedure? wanda )\n> #t\n> > ( fish-weight wanda )\n> 12\n> > ( for-each wanda ' ( 1 2 3 ) )\n> > ( fish-weight wanda )\n> 18\n> ```\nIf the value supplied for the prop:procedure property is not an exact non-negative integer or a procedure, the exn:fail:contract exception is raised.\n> ```\n(procedure-struct-type? type) → boolean?\n  type : struct-type?```\nReturns #t if instances of the structure type represented by type are procedures (according to [procedure?](#%28def._%28%28quote._~23~25kernel%29._procedure~3f%29%29)), #f otherwise.\n> ```\n(procedure-extract-target proc)  →  (or/c #f procedure?)\n  proc : procedure?"} {"text": "# 4.20 Procedures\n```\nIf proc is an instance of a structure type with property prop:procedure, and if the property value indicates a field of the structure, and if the field value is a procedure, then procedure-extract-target returns the field value. Otherwise, the result is #f.\n\nWhen a prop:procedure property value is a procedure, the procedure is not returned by procedure-extract-target. Such a procedure is different from one accessed through a structure field, because it consumes an extra argument, which is always the structure that was applied as a procedure. Keeping the procedure private ensures that is it always called with a suitable first argument.\n\n>
\n\n

value

\n\n

prop:arity-string : struct-type-property?

\n\nA structure type property that is used for reporting arity-mismatch errors when a structure type with the prop:procedure property is applied to the wrong number of arguments. The value of the prop:arity-string property must be a procedure that takes a single argument, which is the misapplied structure, and returns a string. The result string is used after the word “expects,” and it is followed in the error message by the number of actual arguments.\n\nArity-mismatch reporting automatically uses procedure-extract-target when the prop:arity-string property is not associated with a procedure structure type.\n\nExamples:\n\n> ```racket\n> > ( struct evens ( proc ) #:property prop:procedure ( struct-field-index proc ) #:property prop:arity-string ( lambda ( p ) \"an even number of arguments\" ) )\n> > ( define pairs ( evens ( case-lambda [ ( ) null ] [ ( a b . more ) ( cons ( cons a b ) ( apply pairs more ) ) ] ) ) )\n> > ( pairs 1 2 3 4 )\n> '((1 . 2) (3 . 4))\n> > ( pairs 5 )\n> arity mismatch;\n> the expected number of arguments does not match the given\n> number\n> expected: an even number of arguments\n> given: 1\n> arguments...:\n> 5\n> ```\n\n>
\n\n

value

\n\n

prop:checked-procedure : struct-type-property?

\n\nA structure type property that is used with checked-procedure-check-and-extract, which is a hook to allow the compiler to improve the performance of keyword arguments. The property can only be attached to a structure type without a supertype and with at least two fields.\n\n> ```\n(checked-procedure-check-and-extract type\n    v        \n    proc        \n    v1        \n    v2)   →   any/c\n\n  type : struct-type?\n  v : any/c\n  proc : (any/c any/c any/c . → . any/c)\n  v1 : any/c\n  v2 : any/c```\n\n\nExtracts a value from v if it is an instance of type, which must have the property [prop:checked-procedure](#%28def._%28%28quote._~23~25kernel%29._prop~3achecked-procedure%29%29). If v is such an instance, then the first field of v is extracted and applied to v1 and v2; if the result is a true value, the result is the value of the second field of v.\n\nIf v is not an instance of type, or if the first field of v applied to v1 and v2 produces #f, then proc is applied to v, v1, and v2, and its result is returned by [checked-procedure-check-and-extract](#%28def._%28%28quote._~23~25kernel%29._checked-procedure-check-and-extract%29%29).\n\n> ```\n(procedure-specialize proc)  →  procedure?\n  proc : procedure?\n```"} {"text": "# 4.20 Procedures\nReturns proc or its equivalent, but provides a hint to the run-time system that it should spend extra time and memory to specialize the implementation of proc.\nThe hint is currently used when proc is the value of a lambda or case-lambda form that references variables bound outside of the lambda or case-lambda, and when proc has not been previously applied.\nAdded in version 6.3.0.10 of package base."} {"text": "#### 4.20.2 Reflecting on Primitives\nA primitive procedure is a built-in procedure that may be implemented in a lower-level language. Not all procedures of racket/base are primitives, but many are. The distinction between primitives and other procedures may be useful to other low-level code.\n> ```\n(primitive? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a primitive procedure, #f otherwise.\n> ```\n(primitive-closure? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is internally implemented as a primitive closure rather than a simple primitive procedure, #f otherwise.\n\n> ```\n(primitive-result-arity prim)  →  procedure-arity?\n  prim : primitive?```\n\n\nReturns the arity of the result of the primitive procedure prim (as opposed to the procedure’s input arity as returned by [procedure-arity](#%28def._%28%28quote._~23~25kernel%29._procedure-arity%29%29)). For most primitives, this procedure returns 1, since most primitives return a single value when applied.\n\n#### 4.20.3 Additional Higher-Order Functions\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/function](#%28mod-path._racket%2Ffunction%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/function](#%28mod-path._racket%2Ffunction%29) and [racket](index.html) libraries, but not [racket/base](index.html).\n\n> ```\n(identity v)  →  any/c\n  v : any/c\n```"} {"text": "# 4.20 Procedures\nReturns v.\n> ```\n(const v)  →  procedure?\n  v : any/c```\nReturns a procedure that accepts any arguments (including keyword arguments) and returns v.\nExamples:\n> ```racket\n> > ( ( const ' foo ) )\n> 'foo\n> > ( ( const ' foo ) 1 2 3 )\n> 'foo\n> > ( ( const ' foo ) ' a ' b #:c ' c )\n> 'foo\n> ```\n> ```\n(const* v ...) → procedure?\n  v : any/c\n```\nSimilar to const, except it returns vs.\n\nExamples:\n\n> ```racket\n> > ( ( const* ) )\n> > ( ( const* ) 1 2 3 )\n> > ( ( const* ) ' a ' b #:c ' c )\n> > ( ( const* ' foo ) )\n> 'foo\n> > ( ( const* ' foo ) 1 2 3 )\n> 'foo\n> > ( ( const* ' foo ) ' a ' b #:c ' c )\n> 'foo\n> > ( ( const* ' foo ' foo ) )\n> 'foo 'foo\n> > ( ( const* ' foo ' foo ) 1 2 3 )\n> 'foo 'foo\n> > ( ( const* ' foo ' foo ) ' a ' b #:c ' c )\n> 'foo 'foo\n> ```\n\nAdded in version 8.7.0.5 of package base.\n\n>
\n\n

syntax

\n\n

(thunk  body ...+)

\n\n

syntax

\n\n

(thunk* body ...+)

\n\nThe thunk form creates a nullary function that evaluates the given body. The thunk* form is similar, except that the resulting function accepts any arguments (including keyword arguments).\n\nExamples:\n\n> ```racket\n> ( define th1 ( thunk ( define x 1 ) ( printf \"~a\\n\" x ) ) )\n> > ( th1 )\n> 1\n> > ( th1 ' x )\n> th1: arity mismatch;\n> the expected number of arguments does not match the given\n> number\n> expected: 0\n> given: 1\n> > ( th1 #:y ' z )\n> application: procedure does not accept keyword arguments\n> procedure: th1\n> arguments...:\n> #:y 'z\n> ( define th2 ( thunk* ( define x 1 ) ( printf \"~a\\n\" x ) ) )\n> > ( th2 )\n> 1\n> > ( th2 ' x )\n> 1\n> > ( th2 #:y ' z )\n> 1\n> ```\n\n> ```\n(negate proc) → procedure?\n  proc : procedure?```\n\n\nReturns a procedure that is just like proc, except that it returns the [not](booleans.html#%28def._%28%28quote._~23~25kernel%29._not%29%29) of proc’s result.\n\nExamples:\n\n> ```racket\n> > ( filter ( negate symbol? ) ' ( 1 a 2 b 3 c ) )\n> '(1 2 3)\n> > ( map ( negate = ) ' ( 1 2 3 ) ' ( 1 1 1 ) )\n> '(#f #t #t)\n> ```\n\n> ```\n((conjoin f ...) x ...)  →  any\n  f : procedure?\n  x : any/c\n```"} {"text": "# 4.20 Procedures\nCombines calls to each function with and. Equivalent to (and (f x ...) ...)\nExamples:\n> ```racket\n> ( define f ( conjoin exact? integer? ) )\n> > ( f 1 )\n> #t\n> > ( f 1.0 )\n> #f\n> > ( f 1/2 )\n> #f\n> > ( f 0.5 )\n> #f\n> > ( ( conjoin ( λ ( x ) ( values 1 2 ) ) ) 0 )\n> 1 2\n> ```\n> ```\n((disjoin f ...) x ...)  →  any\n  f : procedure?\n  x : any/c```\nCombines calls to each function with [or](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29). Equivalent to ([or](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29) (f x [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29))\nExamples:\n> ```racket\n> ( define f ( disjoin exact? integer? ) )\n> > ( f 1 )\n> #t\n> > ( f 1.0 )\n> #t\n> > ( f 1/2 )\n> #t\n> > ( f 0.5 )\n> #f\n> > ( ( disjoin ( λ ( x ) ( values 1 2 ) ) ) 0 )\n> 1 2\n> ```\n> ```\n(curry proc) → procedure?\n  proc : procedure?\n(curry proc v ...+)  →  any\n  proc : procedure?\n  v : any/c"} {"text": "# 4.20 Procedures\n```\nThe result of (curry proc) is a procedure that is a curried version of proc. When the resulting procedure is first applied, unless it is given the maximum number of arguments that it can accept according to (procedure-arity proc), the result is a procedure to accept additional arguments.\n\nExamples:\n\n> ```racket\n> > ( ( curry list ) 1 2 )\n> #\n> > ( ( curry cons ) 1 )\n> #\n> > ( ( curry cons ) 1 2 )\n> '(1 . 2)\n> ```\n\nAfter the first application of the result of (curry proc), each further application accumulates arguments until an acceptable number of arguments according to (procedure-arity proc) have been accumulated, at which point the original proc is called.\n\nExamples:\n\n> ```racket\n> > ( ( ( curry list ) 1 2 ) 3 )\n> '(1 2 3)\n> > ( ( ( curry list ) 1 ) 3 )\n> '(1 3)\n> > ( ( ( ( curry foldl ) + ) 0 ) ' ( 1 2 3 ) )\n> 6\n> > ( define foo ( curry ( lambda ( x y z ) ( list x y z ) ) ) )\n> > ( foo 1 2 3 )\n> '(1 2 3)\n> > ( ( ( ( ( foo ) 1 ) 2 ) ) 3 )\n> '(1 2 3)\n> ```\n\nA function call (curry proc v ...) is equivalent to ((curry proc) v ...). In other words, curry itself is curried.\n\nExamples:\n\n> ```racket\n> > ( map ( ( curry + ) 10 ) ' ( 1 2 3 ) )\n> '(11 12 13)\n> > ( map ( curry + 10 ) ' ( 1 2 3 ) )\n> '(11 12 13)\n> > ( map ( compose ( curry * 2 ) ( curry + 10 ) ) ' ( 1 2 3 ) )\n> '(22 24 26)\n> ```\n\nThe curry function also supports functions with keyword arguments: keyword arguments will be accumulated in the same way as positional arguments until all required keyword arguments according to (procedure-keywords proc) have been supplied.\n\nExamples:\n\n> ```racket\n> ( define ( f #:a a #:b b #:c c ) ( list a b c ) )\n> > ( ( ( ( curry f ) #:a 1 ) #:b 2 ) #:c 3 )\n> '(1 2 3)\n> > ( ( ( ( curry f ) #:b 1 ) #:c 2 ) #:a 3 )\n> '(3 1 2)\n> > ( ( curry f #:a 1 #:c 2 ) #:b 3 )\n> '(1 3 2)\n> ```\n\nChanged in version 7.0.0.7 of package base: Added support for keyword arguments.\n\n> ```\n(curryr proc) → procedure?\n  proc : procedure?\n(curryr proc v ...+)  →  any\n  proc : procedure?\n  v : any/c```\n\n\nLike [curry](#%28def._%28%28lib._racket%2Ffunction..rkt%29._curry%29%29), except that the arguments are collected in the opposite direction: the first step collects the rightmost group of arguments, and following steps add arguments to the left of these.\n\nExample:\n\n> ```racket\n> > ( map ( curryr list ' foo ) ' ( 1 2 3 ) )\n> '((1 foo) (2 foo) (3 foo))\n> ```\n\n> ```\n(normalized-arity? arity)  →  boolean?\n  arity : any/c\n```"} {"text": "# 4.20 Procedures\nA normalized arity has one of the following forms:\n- the empty list;\n- an exact non-negative integer;\n- an arity-at-least instance;\n- a list of two or more strictly increasing, exact non-negative integers; or\n- a list of one or more strictly increasing, exact non-negative integers followed by a single arity-at-least instance whose value is greater than the preceding integer by at least 2.\nEvery normalized arity is a valid procedure arity and satisfies procedure-arity?. Any two normalized arity values that are arity=? must also be equal?.\nExamples:\n> ```racket\n> > ( normalized-arity? ( arity-at-least 1 ) )\n> #t\n> > ( normalized-arity? ( list ( arity-at-least 1 ) ) )\n> #f\n> > ( normalized-arity? ( list 0 ( arity-at-least 2 ) ) )\n> #t\n> > ( normalized-arity? ( list ( arity-at-least 2 ) 0 ) )\n> #f\n> > ( normalized-arity? ( list 0 2 ( arity-at-least 3 ) ) )\n> #f\n> ```\n> ```\n(normalize-arity arity)\n  →  (and/c normalized-arity? (lambda (x) (arity=? x arity)))\n  arity : procedure-arity?```\nProduces a normalized form of arity. See also [normalized-arity?](#%28def._%28%28lib._racket%2Ffunction..rkt%29._normalized-arity~3f%29%29) and [arity=?](#%28def._%28%28lib._racket%2Ffunction..rkt%29._arity~3d~3f%29%29).\nExamples:"} {"text": "# 4.20 Procedures\n> ```racket\n> > ( normalize-arity 1 )\n> 1\n> > ( normalize-arity ( list 1 ) )\n> 1\n> > ( normalize-arity ( arity-at-least 2 ) )\n> (arity-at-least 2)\n> > ( normalize-arity ( list ( arity-at-least 2 ) ) )\n> (arity-at-least 2)\n> > ( normalize-arity ( list 1 ( arity-at-least 2 ) ) )\n> (arity-at-least 1)\n> > ( normalize-arity ( list ( arity-at-least 2 ) 1 ) )\n> (arity-at-least 1)\n> > ( normalize-arity ( list ( arity-at-least 2 ) 3 ) )\n> (arity-at-least 2)\n> > ( normalize-arity ( list 3 ( arity-at-least 2 ) ) )\n> (arity-at-least 2)\n> > ( normalize-arity ( list ( arity-at-least 6 ) 0 2 ( arity-at-least 4 ) ) )\n> (list 0 2 (arity-at-least 4))\n> ```\n> ```\n(arity=? a b) → boolean?\n  a : procedure-arity?\n  b : procedure-arity?"} {"text": "# 4.20 Procedures\n```\nReturns #true if procedures with arity a and b accept the same numbers of arguments, and #false otherwise. Equivalent to both (and (arity-includes? a b) (arity-includes? b a)) and (equal? (normalize-arity a) (normalize-arity b)).\n\nExamples:\n\n> ```racket\n> > ( arity=? 1 1 )\n> #t\n> > ( arity=? ( list 1 ) 1 )\n> #t\n> > ( arity=? 1 ( list 1 ) )\n> #t\n> > ( arity=? 1 ( arity-at-least 1 ) )\n> #f\n> > ( arity=? ( arity-at-least 1 ) 1 )\n> #f\n> > ( arity=? ( arity-at-least 1 ) ( list 1 ( arity-at-least 2 ) ) )\n> #t\n> > ( arity=? ( list 1 ( arity-at-least 2 ) ) ( arity-at-least 1 ) )\n> #t\n> > ( arity=? ( arity-at-least 1 ) ( list 1 ( arity-at-least 3 ) ) )\n> #f\n> > ( arity=? ( list 1 ( arity-at-least 3 ) ) ( arity-at-least 1 ) )\n> #f\n> > ( arity=? ( list 0 1 2 ( arity-at-least 3 ) ) ( list ( arity-at-least 0 ) ) )\n> #t\n> > ( arity=? ( list ( arity-at-least 0 ) ) ( list 0 1 2 ( arity-at-least 3 ) ) )\n> #t\n> > ( arity=? ( list 0 2 ( arity-at-least 3 ) ) ( list ( arity-at-least 0 ) ) )\n> #f\n> > ( arity=? ( list ( arity-at-least 0 ) ) ( list 0 2 ( arity-at-least 3 ) ) )\n> #f\n> ```\n\n> ```\n(arity-includes? a b) → boolean?\n  a : procedure-arity?\n  b : procedure-arity?```\n\n\nReturns #true if procedures with arity a accept any number of arguments that procedures with arity b accept.\n\nExamples:\n\n> ```racket\n> > ( arity-includes? 1 1 )\n> #t\n> > ( arity-includes? ( list 1 ) 1 )\n> #t\n> > ( arity-includes? 1 ( list 1 ) )\n> #t\n> > ( arity-includes? 1 ( arity-at-least 1 ) )\n> #f\n> > ( arity-includes? ( arity-at-least 1 ) 1 )\n> #t\n> > ( arity-includes? ( arity-at-least 1 ) ( list 1 ( arity-at-least 2 ) ) )\n> #t\n> > ( arity-includes? ( list 1 ( arity-at-least 2 ) ) ( arity-at-least 1 ) )\n> #t\n> > ( arity-includes? ( arity-at-least 1 ) ( list 1 ( arity-at-least 3 ) ) )\n> #t\n> > ( arity-includes? ( list 1 ( arity-at-least 3 ) ) ( arity-at-least 1 ) )\n> #f\n> > ( arity-includes? ( list 0 1 2 ( arity-at-least 3 ) ) ( list ( arity-at-least 0 ) ) )\n> #t\n> > ( arity-includes? ( list ( arity-at-least 0 ) ) ( list 0 1 2 ( arity-at-least 3 ) ) )\n> #t\n> > ( arity-includes? ( list 0 2 ( arity-at-least 3 ) ) ( list ( arity-at-least 0 ) ) )\n> #f\n> > ( arity-includes? ( list ( arity-at-least 0 ) ) ( list 0 2 ( arity-at-least 3 ) ) )\n> #t\n> ```\n\n------------------------------------------------------------------------\n\n# 4.21 Void\n\n### 4.21 Void\n\nThe constant [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13) is returned by most forms and procedures that have a side-effect and no useful result.\n\nThe [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13) value is always [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to itself.\n\n> ```\n(parameter)\t→\n```"} {"text": "# 4.20 Procedures\n(parameter)\t→```\nReturns the constant [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13). Each v argument is ignored.\n------------------------------------------------------------------------"} {"text": "# 4.22 Undefined"} {"text": "### 4.22 Undefined\n| | |\n|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/undefined]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/undefined]() library, not [racket/base](index.html) or [racket](index.html).\nThe constant [undefined](#%28def._%28%28lib._racket%2Fundefined..rkt%29._undefined%29%29) can be used as a placeholder value for a value to be installed later, especially for cases where premature access of the value is either difficult or impossible to detect or prevent.\nThe [undefined](#%28def._%28%28lib._racket%2Fundefined..rkt%29._undefined%29%29) value is always [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to itself.\nAdded in version 6.0.0.6 of package base."} {"text": "# 4.22 Undefined\n>
\n

value

\n

[undefined](#%28def._%28%28lib._racket%2Fundefined..rkt%29._undefined%29%29) : [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29)

\nThe “undefined” constant.\n------------------------------------------------------------------------"} {"text": "# 5 Structures"} {"text": "## 5 Structures\n> > > \"+\"[Programmer-Defined Datatypes](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=define-struct.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces structure types via [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29).\nA structure type is a record datatype composing a number of fields. A structure, an instance of a structure type, is a first-class value that contains a value for each field of the structure type. A structure instance is created with a type-specific [constructor](define-struct.html#%28tech._constructor%29) procedure, and its field values are accessed and changed with type-specific [accessor](define-struct.html#%28tech._accessor%29) and [mutator](define-struct.html#%28tech._mutator%29) procedures. In addition, each structure type has a [predicate](define-struct.html#%28tech._predicate%29) procedure that answers #t for instances of the structure type and #f for any other value."} {"text": "# 5 Structures\nA structure type’s fields are essentially unnamed, though names are supported for error-reporting purposes. The constructor procedure takes one value for each field of the structure type, except that some of the fields of a structure type can be automatic fields; the [automatic fields](#%28tech._automatic._field%29) are initialized to a constant that is associated with the structure type, and the corresponding arguments are omitted from the constructor procedure. All automatic fields in a structure type follow the non-automatic fields.\nA structure type can be created as a structure subtype of an existing base structure type. An instance of a structure subtype can always be used as an instance of the base structure type, but the subtype gets its own predicate procedure, and it may have its own fields in addition to the fields of the base type.\nA structure subtype “inherits” the fields of its base type. If the base type has m fields, and if n fields are specified for the new structure subtype, then the resulting structure type has m+n fields. The value for automatic fields can be different in a subtype than in its base type."} {"text": "# 5 Structures\nIf m′ of the original m fields are non-automatic (where m′\\ > > \"+\"[Serialization](serialization.html) also provides information on reading and writing structures.\nTwo structure values are [eqv?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eqv~3f%29%29) if and only if they are [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29). Two structure values are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) if they are [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29). By default, two structure values are also [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) if they are instances of the same structure type, no fields are opaque, and the results of applying [struct->vector](structutils.html#%28def._%28%28quote._~23~25kernel%29._struct-~3evector%29%29) to the structs are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29). (Consequently, [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) testing for structures may depend on the current inspector.) A structure type can override the default [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) definition through the [gen:equal+hash](Equality.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._gen~3aequal%2Bhash%29%29) or [gen:equal-mode+hash](Equality.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._gen~3aequal-mode%2Bhash%29%29) [generic interface](struct-generics.html#%28tech._generic._interface%29)."} {"text": "# 5 Structures\n| |\n|-----------------------------------------------------------------------------------------------------------------------------------------|\n|     [5.1 Defining Structure Types: struct](define-struct.html) |\n|     [5.2 Creating Structure Types](creatingmorestructs.html) |\n|     [5.3 Structure Type Properties](structprops.html) |\n|     [5.4 Generic Interfaces](struct-generics.html) |\n|     [5.5 Copying and Updating Structures](struct-copy.html) |\n|     [5.6 Structure Utilities](structutils.html) |\n|       [5.6.1 Additional Structure Utilities](structutils.html#%28part._.Additional_.Structure_.Utilities%29) |\n|     [5.7 Structure Type Transformer Binding](structinfo.html) |\n------------------------------------------------------------------------"} {"text": "# 5.1 Defining Structure Types: struct"} {"text": "### 5.1 Defining Structure Types: [struct](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29)\n> > > \"+\"[Programmer-Defined Datatypes](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=define-struct.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces [struct](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29).\n> ```\nsyntax\n(struct id maybe-super (field ...)\n> struct-option ... )\nmaybe-super   =  \n    |   super-id\nfield   =   field-id\n    |   [field-id field-option ...]\nstruct-option   =   #:mutable\n    |   #:super super-expr\n    |   #:inspector inspector-expr\n    |   #:auto-value auto-expr\n    |   #:guard guard-expr\n    |   #:property prop-expr val-expr\n    |   #:properties prop-list-expr\n    |   #:transparent\n    |   #:prefab\n    |   #:sealed\n    |   #:authentic\n    |   #:name name-id\n    |   #:extra-name name-id\n    |   #:constructor-name constructor-id\n    |   #:extra-constructor-name constructor-id\n    |   #:reflection-name symbol-expr\n    |   #:methods gen:name-id method-defs\n    |   #:omit-define-syntaxes\n    |   #:omit-define-values\nfield-option   =   #:mutable\n    |   #:auto\nmethod-defs   =   (definition ...)"} {"text": "### 5.1 Defining Structure Types: [struct](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29)\n```\nCreates a new structure type (or uses a pre-existing structure type if #:prefab is specified), and binds transformers and variables related to the structure type.\n\nA struct form with n fields defines up to 4+2n names:\n\n- struct:id, a structure type descriptor value that represents the structure type.\n\n- constructor-id (which defaults to id), a constructor procedure that takes m arguments and returns a new instance of the structure type, where m is the number of fields that do not include an #:auto option.\n\n- name-id (which defaults to id), a transformer binding that encapsulates information about the structure type declaration. This binding is used to define subtypes, and it also works with the shared and match forms. For detailed information about the binding of name-id, see Structure Type Transformer Binding.\n\nThe constructor-id and name-id can be the same, in which case name-id performs both roles. In that case, the expansion of name-id as an expression produces an otherwise inaccessible identifier that is bound to the constructor procedure; the expanded identifier has a 'constructor-for property whose value is an identifier that is free-identifier=? to name-id as well as a syntax property accessible via syntax-procedure-alias-property with an identifier that is free-identifier=? to name-id.\n\n- id?, a predicate procedure that returns #t for instances of the structure type (constructed by constructor-id or the constructor for a subtype) and #f for any other value.\n\n- id-field-id, for each field; an accessor procedure that takes an instance of the structure type and extracts the value for the corresponding field.\n\n- set-id-field-id!, for each field that includes a #:mutable option, or when the #:mutable option is specified as a struct-option; a mutator procedure that takes an instance of the structure type and a new field value. The structure is destructively updated with the new value, and # is returned.\n\nIf super-id is provided, it must have a transformer binding of the same sort bound to name-id (see Structure Type Transformer Binding), and it specifies a supertype for the structure type. Alternately, the #:super option can be used to specify an expression that must produce a structure type descriptor. See Structures for more information on structure subtypes and supertypes. If both super-id and #:super are provided, a syntax error is reported.\n\nExamples:\n\n> ```racket\n> > ( struct document ( author title content ) )\n> > ( struct book document ( publisher ) )\n> > ( struct paper ( journal ) #:super struct:document )\n> ```\n\nIf the #:mutable option is specified for an individual field, then the field can be mutated in instances of the structure type, and a mutator procedure is bound. Supplying #:mutable as a struct-option is the same as supplying it for all fields. If #:mutable is specified as both a field-option and struct-option, a syntax error is reported.\n\nExamples:\n\n> ```racket\n> > ( struct cell ( [ content #:mutable ] ) #:transparent )\n> > ( define a-cell ( cell 0 ) )\n> > ( set-cell-content! a-cell 1 )\n> ```\n\nThe #:inspector, #:auto-value, and #:guard options specify an inspector, value for automatic fields, and guard procedure, respectively. See make-struct-type for more information on these attributes of a structure type. The #:property option, which can be supplied multiple times, attaches a property value to the structure type; see Structure Type Properties for more information on properties. The #:properties option, which can be supplied multiple times, accepts multiple properties and their values as an association list. The #:transparent option is a shorthand for #:inspector #f.\n\nExamples:\n\n> ```racket\n> > ( struct point ( x y ) #:inspector #f )\n> > ( point 3 5 )\n> (point 3 5)\n> > ( struct celsius ( temp ) #:guard ( λ ( temp name ) ( unless ( and ( real? temp ) ( >= temp -2 73.15 ) ) ( error \"not a valid temperature\" ) ) temp ) )\n> > ( celsius -2 75 )\n> not a valid temperature\n> ```\n\n> > > Use the prop:procedure property to implement an applicable structure, use prop:evt to create a structure type whose instances are synchronizable events, and so on. By convention, property names start with prop:.\n\nThe #:prefab option obtains a prefab (pre-defined, globally shared) structure type, as opposed to creating a new structure type. Such a structure type is inherently transparent and non-sealed, and it cannot have a guard or properties, so using #:prefab with #:transparent, #:inspector, #:guard, #:property, #:sealed, #:authentic, or #:methods is a syntax error. If a supertype is specified, it must also be a prefab structure type.\n\nExamples:\n\n> ```racket\n> > ( struct prefab-point ( x y ) #:prefab )\n> > ( prefab-point 1 2 )\n> '#s(prefab-point 1 2)\n> > ( prefab-point? #s ( prefab-point 1 2 ) )\n> #t\n> ```\n\nThe #:sealed option is a shorthand for #:property prop:sealed #t, which prevents the structure type from being used as the supertype of another structure type. See prop:sealed for more information.\n\nThe #:authentic option is a shorthand for #:property prop:authentic #t, which prevents instances of the structure type from being impersonated (see impersonate-struct), chaperoned (see chaperone-struct), or acquiring a non-flat contract (see struct/c). See prop:authentic for more information. If a supertype is specified, it must also have the prop:authentic property.\n\nIf name-id is supplied via #:extra-name and it is not id, then both name-id and id are bound to information about the structure type. Only one of #:extra-name and #:name can be provided within a struct form, and #:extra-name cannot be combined with #:omit-define-syntaxes.\n\nExamples:\n\n> ```racket\n> > ( struct ghost ( color name ) #:prefab #:extra-name GHOST )\n> > ( match ( ghost ' red ' blinky ) [ ( GHOST c n ) c ] )\n> 'red\n> ```\n\nIf constructor-id is supplied, then the transformer binding of name-id records constructor-id as the constructor binding; as a result, for example, struct-out includes constructor-id as an export. If constructor-id is supplied via #:extra-constructor-name and it is not id, applying object-name on the constructor produces the symbolic form of id rather than constructor-id. If constructor-id is supplied via #:constructor-name and it is not the same as name-id, then name-id does not serve as a constructor, and object-name on the constructor produces the symbolic form of constructor-id. Only one of #:extra-constructor-name and #:constructor-name can be provided within a struct form.\n\nExamples:\n\n> ```racket\n> > ( struct color ( r g b ) #:constructor-name -c olor )\n> > ( struct rectangle ( w h color ) #:extra-constructor-name rect )\n> > ( rectangle 13 50 ( -c olor 192 157 235 ) )\n> #\n> > ( rect 50 37 ( -c olor 35 183 252 ) )\n> #\n> ```\n\nIf #:reflection-name symbol-expr is provided, then symbol-expr must produce a symbol that is used to identify the structure type in reflective operations such as struct-type-info. It corresponds to the first argument of make-struct-type. Structure printing uses the reflective name, as do the various procedures that are bound by struct.\n\nExamples:\n\n> ```racket\n> > ( struct circle ( radius ) #:reflection-name ' )\n> > ( circle 15 )\n> #<>\n> > ( circle-radius \"bad\" )\n> -radius: contract violation\n> expected: ?\n> given: \"bad\"\n> ```\n\nIf #:methods gen:name-id method-defs is provided (potentially multiple times), then gen:name-id must be a transformer binding for the static information about a generic interface produced by define-generics. The method-defs define the methods of the gen:name-id interface. A define/generic form or auxiliary definitions and expressions may also appear in method-defs.\n\nExamples:\n\n> ```racket\n> > ( struct constant-stream ( val ) #:methods gen:stream [ ( define ( stream-empty? stream ) #f ) ( define ( stream-first stream ) ( constant-stream-val stream ) ) ( define ( stream-rest stream ) stream ) ] )\n> > ( stream-ref ( constant-stream ' forever ) 0 )\n> 'forever\n> > ( stream-ref ( constant-stream ' forever ) 50 )\n> 'forever\n> ```\n\nIf the #:omit-define-syntaxes option is supplied, then name-id (and id, if #:extra-name is specified) is not bound as a transformer. If the #:omit-define-values option is supplied, then none of the usual variables are bound, but id is bound. If both are supplied, then the struct form is equivalent to (begin).\n\nExamples:\n\n> ```racket\n> > ( struct square ( side ) #:omit-define-syntaxes )\n> > ( match ( square 5 ) ; fails to match because syntax is omitted [ ( struct square x ) x ] )\n> eval:28:0: match: square does not refer to a structure\n> definition\n> at: square\n> in: (struct square x)\n> > ( struct ellipse ( width height ) #:omit-define-values )\n> > ellipse-width\n> ellipse-width: undefined;\n> cannot reference an identifier before its definition\n> in module: top-level\n> ```\n\n> > > Expressions supplied to #:auto-value are evaluated once and shared between every instance of the structure type. In particular, updates to a mutable #:auto-value affect all current and future instances.\n\nIf #:auto is supplied as a field-option, then the constructor procedure for the structure type does not accept an argument corresponding to the field. Instead, the structure type’s automatic value is used for the field, as specified by the #:auto-value option, or as defaults to #f when #:auto-value is not supplied. The field is mutable (e.g., through reflective operations), but a mutator procedure is bound only if #:mutable is specified.\n\nIf a field includes the #:auto option, then all fields after it must also include #:auto, otherwise a syntax error is reported. If any field-option or struct-option keyword is repeated, other than #:property, a syntax error is reported.\n\nExamples:\n\n> ```racket\n> ( struct posn ( x y [ z #:auto #:mutable ] ) #:auto-value 0 #:transparent )\n> > ( posn 1 2 )\n> (posn 1 2 0)\n> > ( posn? ( posn 1 2 ) )\n> #t\n> > ( posn-y ( posn 1 2 ) )\n> 2\n> > ( posn-z ( posn 1 2 ) )\n> 0\n> ( struct color-posn posn ( hue ) #:mutable ) ( define cp ( color-posn 1 2 \"blue\" ) )\n> > ( color-posn-hue cp )\n> \"blue\"\n> > cp\n> (color-posn 1 2 0 ...)\n> > ( set-posn-z! cp 3 )\n> ```\n\nFor serialization, see define-serializable-struct.\n\nChanged in version 6.9.0.4 of package base: Added #:authentic. \nChanged in version 8.0.0.7: Added #:sealed. \nChanged in version 8.17.0.4: Added #:properties.\n\n>
\n\n

syntax

\n\n

(struct-field-index field-id)

\n\nThis form can only appear as an expression within a struct form; normally, it is used with #:property, especially for a property like prop:procedure. The result of a struct-field-index expression is an exact, non-negative integer that corresponds to the position within the structure declaration of the field named by field-id.\n\nExamples:\n\n> ```racket\n> ( struct mood-procedure ( base rating ) #:property prop:procedure ( struct-field-index base ) ) ( define happy+ ( mood-procedure add1 10 ) )\n> > ( happy+ 2 )\n> 3\n> > ( mood-procedure-rating happy+ )\n> 10\n> ```\n\n> ```\nsyntax\n\n(define-struct id-maybe-super (field ...)\n> struct-option ... )\n \nid-maybe-super   =   id\n    |   (id super-id)```\n\n\nLike [struct](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29), except that the syntax for supplying a super-id is different, and a constructor-id that has a make- prefix on id is implicitly supplied via #:extra-constructor-name if neither #:extra-constructor-name nor #:constructor-name is provided.\n\nThis form is provided for backwards compatibility; [struct](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) is preferred.\n\nExamples:\n\n> ```racket\n> ( define-struct posn ( x y [ z #:auto ] ) #:auto-value 0 #:transparent )\n> > ( make-posn 1 2 )\n> (posn 1 2 0)\n> > ( posn? ( make-posn 1 2 ) )\n> #t\n> > ( posn-y ( make-posn 1 2 ) )\n> 2\n> ```\n\n> ```\nsyntax\n\n(struct/derived (id . rest-form)\n> id ( field ... ) struct-option ... )\n( struct/derived ( id . rest-form )\n> id super-id ( field ... ) struct-option ... )\n```"} {"text": "### 5.1 Defining Structure Types: [struct](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29)\nThe same as struct, but with an extra (id . rest-form) sub-form that is treated as the overall form for syntax-error reporting and otherwise ignored. The only constraint on the sub-form for error reporting is that it starts with id. The struct/derived form is intended for use by macros that expand to struct.\nExamples:\n> ```racket\n> ( define-syntax ( fruit-struct stx ) ( syntax-case stx ( ) [ ( ds name . rest ) ( with-syntax ( [ orig stx ] ) #' ( struct/derived orig name ( seeds color ) . rest ) ) ] ) )\n> > ( fruit-struct apple )\n> > ( apple-seeds ( apple 12 \"red\" ) )\n> 12\n> > ( fruit-struct apple #:mutable )\n> > ( set-apple-seeds! ( apple 12 \"red\" ) 8 )\n> ; this next line will cause an error due to a bad keyword\n> > ( fruit-struct apple #:bad-option )\n> eval:54:0: fruit-struct: unrecognized struct-specification\n> keyword\n> at: #:bad-option\n> in: (fruit-struct apple #:bad-option)\n> ```\nAdded in version 7.5.0.16 of package base.\n> ```\nsyntax\n(define-struct/derived (id . rest-form)\n> id-maybe-super ( field ... ) struct-option ... )```"} {"text": "### 5.1 Defining Structure Types: [struct](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29)\nLike [struct/derived](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%2Fderived%29%29), except that the syntax for supplying a super-id is different, and a constructor-id that has a make- prefix on id is implicitly supplied via #:extra-constructor-name if neither #:extra-constructor-name nor #:constructor-name is provided. The [define-struct/derived](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-struct%2Fderived%29%29) form is intended for use by macros that expand to [define-struct](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-struct%29%29).\nExamples:\n> ```racket\n> ( define-syntax ( define-xy-struct stx ) ( syntax-case stx ( ) [ ( ds name . rest ) ( with-syntax ( [ orig stx ] ) #' ( define-struct/derived orig name ( x y ) . rest ) ) ] ) )\n> > ( define-xy-struct posn )\n> > ( posn-x ( make-posn 1 2 ) )\n> 1\n> > ( define-xy-struct posn #:mutable )\n> > ( set-posn-x! ( make-posn 1 2 ) 0 )\n> ; this next line will cause an error due to a bad keyword\n> > ( define-xy-struct posn #:bad-option )\n> eval:60:0: define-xy-struct: unrecognized\n> struct-specification keyword\n> at: #:bad-option\n> in: (define-xy-struct posn #:bad-option)\n> ```\nChanged in version 7.5.0.16 of package base: Moved main description to [struct/derived](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%2Fderived%29%29) and replaced with differences.\n------------------------------------------------------------------------"} {"text": "# 5.2 Creating Structure Types"} {"text": "### 5.2 Creating Structure Types\n> ```\n(current-inspector)\t→\t\n(-> or/c struct-type? #f)\n```\n(inclusive)\t→\t\n(-> format \"make-~a\" name)```\n\n\nReturns a field accessor that is equivalent to ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) (s) (accessor-proc s field-pos)). The accessor-proc must be an [accessor](define-struct.html#%28tech._accessor%29) returned by [make-struct-type](#%28def._%28%28quote._~23~25kernel%29._make-struct-type%29%29).\n\nThe field/proc-name argument determines the name of the resulting procedure for error reporting and debugging purposes. If field/proc-name is a symbol and arg-contract-str is not #f, then field/proc-name is used as the procedure name. If field/proc-name is a symbol and arg-contract-str is #f, then field/proc-name is combined with the name of accessor-proc’s structure type to form the procedure name. If field/proc-name is #f, then 'accessor is used as the procedure name.\n\nThe arg-contract-str argument determines how the accessor procedure reports an error when it is applied to a value that is not an instance of the accessor-proc’s structure type. If it is a string or symbol, the text of the string or symbol is used as a contract for error reporting. Otherwise, contract text is synthesized from the name of accessor-proc’s structure type.\n\nThe realm argument is also used for error reporting. It specifies a [realm](exns.html#%28tech._realm%29) that an error-message adjuster may use to determine how to adjust an error message. The realm argument also determines the result of [procedure-realm](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._procedure-realm%29%29) for the accessor procedure.\n\nFor examples, see [make-struct-type](#%28def._%28%28quote._~23~25kernel%29._make-struct-type%29%29).\n\nChanged in version 8.4.0.2 of package base: Added the arg-contract-str and realm arguments.\n\n> ```\n(parameter)\t→\t\n(-> or/c symbol? #f)\n```"} {"text": "# 5.2 Creating Structure Types\n(parameter)\t→\t\n(-> any/c . → . boolean?)```\nCreates a new structure type property and returns three values:\n- a structure type property descriptor, for use with [make-struct-type](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._make-struct-type%29%29) and [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29);\n- a property predicate procedure, which takes an arbitrary value and returns #t if the value is a descriptor or instance of a structure type that has a value for the property, #f otherwise;\n- a property accessor procedure, which returns the value associated with the structure type given its descriptor or one of its instances; if the structure type does not have a value for the property, or if any other kind of value is provided, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised unless a second argument, failure-result, is supplied to the procedure. In that case, if failure-result is a procedure, it is called (through a tail call) with no arguments to produce the result of the property accessor procedure; otherwise, failure-result is itself returned as the result."} {"text": "# 5.2 Creating Structure Types\nIf the optional guard is supplied as a procedure, it is called by [make-struct-type](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._make-struct-type%29%29) before attaching the property to a new structure type. The guard must accept two arguments: a value for the property supplied to [make-struct-type](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._make-struct-type%29%29), and a list containing information about the new structure type. The list contains the values that [struct-type-info](inspectors.html#%28def._%28%28quote._~23~25kernel%29._struct-type-info%29%29) would return for the new structure type if it skipped the current-inspector control checks.\nThe result of calling guard is associated with the property in the target structure type, instead of the value supplied to [make-struct-type](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._make-struct-type%29%29). To reject a property association (e.g., because the value supplied to [make-struct-type](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._make-struct-type%29%29) is inappropriate for the property), the guard can raise an exception. Such an exception prevents [make-struct-type](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._make-struct-type%29%29) from returning a structure type descriptor."} {"text": "# 5.2 Creating Structure Types\nIf guard is 'can-impersonate, then the property’s accessor can be redirected through [impersonate-struct](chaperones.html#%28def._%28%28quote._~23~25kernel%29._impersonate-struct%29%29). This option is identical to supplying #t as the can-impersonate? argument and is provided for backwards compatibility.\nThe optional supers argument is a list of properties that are automatically associated with some structure type when the newly created property is associated to the structure type. Each property in supers is paired with a procedure that receives the value supplied for the new property (after it is processed by guard) and returns a value for the associated property (which is then sent to that property’s guard, of any).\nThe optional can-impersonate? argument determines if the structure type property can be redirected through [impersonate-struct](chaperones.html#%28def._%28%28quote._~23~25kernel%29._impersonate-struct%29%29). If the argument is #f, then redirection is not allowed. Otherwise, the property accessor may be redirected by a struct impersonator.\nThe optional accessor-name argument supplies a name (in the sense of [object-name](inspectors.html#%28def._%28%28quote._~23~25kernel%29._object-name%29%29)) to use for the returned accessor function. If accessor-name is #f, a name is created by adding -accessor to the end of name."} {"text": "# 5.2 Creating Structure Types\nThe optional contract-str argument supplies a contract that is included in an error message with the returned accessor is applied to a value that is not an instance of the property (and where a failure-result argument is not supplied to the accessor). If contract-str is #f, a contract is created by adding ? to the end of name.\nThe optional realm argument supplies a [realm](exns.html#%28tech._realm%29) (in the sense of [procedure-realm](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._procedure-realm%29%29)) to associate with the returned accessor.\nExamples:\n> ```racket\n> > ( define-values ( prop:p p? p-ref ) ( make-struct-type-property ' p ) )\n> > ( define-values ( struct:a make-a a? a-ref a-set! ) ( make-struct-type ' a #f 2 1 ' uninitialized ( list ( cons prop:p 8 ) ) ) )\n> > ( p? struct:a )\n> #t\n> > ( p? 13 )\n> #f\n> > ( define an-a ( make-a ' x ' y ) )\n> > ( p? an-a )\n> #t\n> > ( p-ref an-a )\n> 8\n> > ( define-values ( struct:b make-b b? b-ref b-set! ) ( make-struct-type ' b #f 0 0 #f ) )\n> > ( p? struct:b )\n> #f\n> > ( define-values ( prop:q q? q-ref ) ( make-struct-type-property ' q ( lambda ( v si ) ( add1 v ) ) ( list ( cons prop:p sqrt ) ) ) )\n> > ( define-values ( struct:c make-c c? c-ref c-set! ) ( make-struct-type ' c #f 0 0 ' uninit ( list ( cons prop:q 8 ) ) ) )\n> > ( q-ref struct:c )\n> 9\n> > ( p-ref struct:c )\n> 3\n> ```"} {"text": "# 5.2 Creating Structure Types\nChanged in version 7.0 of package base: The [CS](implementations.html#%28tech._c%29) implementation of Racket skips the inspector check for exposing an ancestor structure type, if any, in information provided to a guard procedure. \nChanged in version 8.4.0.2: Added the accessor-name, contract-str, and realm arguments. \nChanged in version 8.5.0.2: Changed the [BC](implementations.html#%28tech._bc%29) implementation of Racket to skip the inspector check, the same as the [CS](implementations.html#%28tech._c%29) implementation, for ancestor information provided to a guard procedure.\n> ```\n(struct-type-property? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a structure type property descriptor value, #f otherwise.\n\n> ```\n(struct-type-property-accessor-procedure? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is an accessor procedure produced by [make-struct-type-property](#%28def._%28%28quote._~23~25kernel%29._make-struct-type-property%29%29), #f otherwise.\n\n> ```\n(struct-type-property-predicate-procedure? v\n   [ prop)   →   boolean?\n\n  v : any/c\n  prop : (or/c struct-type-property? #f) = #f\n```\nReturns #t if v is a predicate procedure produced by make-struct-type-property and either prop is #f or it was produced by the same call to make-struct-type-property, #f otherwise.\nAdded in version 7.5.0.11 of package base.\n------------------------------------------------------------------------"} {"text": "# 5.4 Generic Interfaces\n8.18.0.13"} {"text": "### 5.4 Generic Interfaces\n| | |\n|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/generic]()) |  package: base |\nA generic interface allows per-type methods to be associated with generic functions. Generic functions are defined using a define-generics form. Method implementations for a structure type are defined using the #:methods keyword (see Defining Structure Types: struct).\n> ```\nsyntax\n(define-generics id\n> generics-opt ...\n> [ method-id . kw-formals* ] ...\n> generics-opt ... )\ngenerics-opt   =   #:defaults ([default-pred? default-impl ...] ...)\n    |   #:fast-defaults ([fast-pred? fast-impl ...] ...)\n    |   #:fallbacks [fallback-impl ...]\n    |   #:defined-predicate defined-pred-id\n    |   #:defined-table defined-table-id\n    |   #:derive-property prop-expr prop-value-expr\n    |   #:requires [required-method-id ...]\nkw-formals*   =   (arg* ...)\n    |   (arg* ...+ . rest-id)\n    |   rest-id\narg*   =   arg-id\n    |   [arg-id]\n    |   keyword arg-id\n    |   keyword [arg-id]```\nDefines the following names, plus any specified by keyword options.\n- gen:id as a transformer binding for the static information about a new generic interface;\n- id? as a predicate identifying instances of structure types that implement this generic group; and"} {"text": "# 5.4 Generic Interfaces\n- each method-id as a generic method that calls the corresponding method on values where id? is true. Each method-id’s kw-formals\\* must include a required by-position argument that is [free-identifier=?](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._free-identifier~3d~3f%29%29) to id. That argument is used in the generic definition to locate the specialization.\n- id/c as a contract combinator that recognizes instances of structure types which implement the gen:id generic interface. The combinator takes pairs of method-ids and contracts. The contracts will be applied to each of the corresponding method implementations. The id/c combinator is intended to be used to contract the range of a constructor procedure for a struct type that implements the generic interface.\nThe #:defaults option may be provided at most once. When it is provided, each generic function uses default-pred?s to dispatch to the given default method implementations, default-impls, if dispatching to the generic method table fails. The syntax of the default-impls is the same as the methods provided for the #:methods keyword for [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29).\nThe #:fast-defaults option may be provided at most once. It works the same as #:defaults, except the fast-pred?s are checked before dispatching to the generic method table. This option is intended to provide a fast path for dispatching to built-in datatypes, such as lists and vectors, that do not overlap with structures implementing gen:id."} {"text": "# 5.4 Generic Interfaces\nThe #:fallbacks option may be provided at most once. When it is provided, the fallback-impls define fallback method implementations that are used for any instance of the generic interface that does not supply a specific implementation. The syntax of the fallback-impls is the same as the methods provided for the #:methods keyword for [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29).\nThe #:defined-predicate option may be provided at most once. When it is provided, defined-pred-id is defined as a procedure that reports whether a specific instance of the generic interface implements a given set of methods. Specifically, (defined-pred-id v 'name [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) produces #t if v has implementations for each method name, not counting #:fallbacks implementations, and produces #f otherwise. This procedure is intended for use by higher-level APIs to adapt their behavior depending on method availability.\nThe #:defined-table option may be provided at most once. When it is provided, defined-table-id is defined as a procedure that takes an instance of the generic interface and returns an immutable [hash table](hashtables.html#%28tech._hash._table%29) that maps symbols corresponding to method names to booleans representing whether or not that method is implemented by the instance. This option is deprecated; use #:defined-predicate instead."} {"text": "# 5.4 Generic Interfaces\nThe #:derive-property option may be provided any number of times. Each time it is provided, it specifies a [structure type property](structprops.html#%28tech._structure._type._property%29) via prop-expr and a value for the property via prop-value-expr. All structures implementing the generic interface via #:methods automatically implement this structure type property using the provided values. When prop-value-expr is executed, each method-id is bound to its specific implementation for the [structure type](structures.html#%28tech._structure._type%29).\nThe #:requires option may be provided at most once. When it is provided, any instance of the generic interface must supply an implementation of the specified required-method-ids. Otherwise, a compile-time error is raised.\nIf a value v satisfies id?, then v is a generic instance of gen:id.\nIf a generic instance v has a corresponding implementation for some method-id provided via #:methods in [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) or via #:defaults or #:fast-defaults in [define-generics](#%28form._%28%28lib._racket%2Fgeneric..rkt%29._define-generics%29%29), then method-id is an implemented generic method of v.\nIf method-id is not an implemented generic method of a generic instance v, and method-id has a fallback implementation that does not raise an [exn:fail:support](#%28def._%28%28lib._racket%2Fgeneric..rkt%29._exn~3afail~3asupport%29%29) exception when given v, then method-id is a supported generic method of v."} {"text": "# 5.4 Generic Interfaces\nChanged in version 8.7.0.5 of package base: Added the #:requires option.\n> ```\n(parameter)\t→\n```\n(100x90)\t→\t\n(-> printable/c [ gen-print (→ * (printable?) (output-port?) void?) ] [ gen-port-print (→ output-port? printable? void?) ] [ gen-print* (→ * (printable? #:width exact-nonnegative-integer?) (output-port? #:height exact-nonnegative-integer?) void?) ])```\n\n\nCreates an [impersonator](chaperones.html#%28tech._impersonator%29) of val-expr, which must be a structure that implements the [generic interface](#%28tech._generic._interface%29) gen-id. The impersonator applies the results of the method-proc-exprs to the structure’s implementation of the corresponding method-ids, and replaces the method implementation with the result.\n\nA props-expr can provide properties to attach to the impersonator. The result of props-expr must be a list with an even number of elements, where the first element of the list is an impersonator property, the second element is its value, and so on.\n\nChanged in version 6.1.1.8 of package base: Added #:properties.\n\n> ```\nsyntax\n\n(chaperone-generics gen-id val-expr\n> [ method-id method-proc-expr ] ...\n> maybe-properties )\n```\nLike impersonate-generics, but creates a chaperone of val-expr, which must be a structure that implements the generic interface gen-id. The chaperone applies the specified method-procs to the structure’s implementation of the corresponding method-ids, and replaces the method implementation with the result, which must be a chaperone of the original.\n> ```\nsyntax\n(redirect-generics mode gen-id val-expr"} {"text": "# 5.4 Generic Interfaces\n> [ method-id method-proc-expr ] ...\n> maybe-properties )```\nLike [impersonate-generics](#%28form._%28%28lib._racket%2Fgeneric..rkt%29._impersonate-generics%29%29), but creates an [impersonator](chaperones.html#%28tech._impersonator%29) of val-expr if mode evaluates to #f, or creates a [chaperone](chaperones.html#%28tech._chaperone%29) of val-expr otherwise.\n> ```\n(parameter)\t→\n```\nCreates a new structure type property and returns three values, just like make-struct-type-property would:\n\n- a structure type property descriptor\n\n- a property predicate procedure\n\n- a property accessor procedure\n\nAny struct that implements this property will also implement the properties and generic interfaces given in the #:property and #:methods declarations. The property val-exprs and method-defs are evaluated eagerly when the property is created, not when it is attached to a structure type.\n\n> ```\nsyntax\n\n(make-generic-struct-type-property\n> gen:name-id\n> method-def\n> ... )```\n\n\nCreates a new structure type property and returns the [structure type property descriptor](structprops.html#%28tech._structure._type._property._descriptor%29).\n\nAny struct that implements this property will also implement the [generic interface](#%28tech._generic._interface%29) given by gen:name-id with the given method-defs. The method-defs are evaluated eagerly when the property is created, not when it is attached to a structure type.\n\n------------------------------------------------------------------------\n\n# 5.5 Copying and Updating Structures\n\n### 5.5 Copying and Updating Structures\n\n>
\n\n

syntax

\n\n

([struct-copy](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct-copy%29%29) id struct-expr fld-id ...)

 
fld-id = [field-id expr]
  | [field-id #:parent parent-id expr]
\n\nCreates a new instance of the structure type id (which is defined via a [structure type defining form](define-struct.html) such as [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29)) with the same field values as the structure produced by struct-expr, except that the value of each supplied field-id is instead determined by the corresponding expr. If #:parent is specified, the parent-id must be bound to a parent structure type of id.\n\nThe id must have a [transformer](syntax-model.html#%28tech._transformer%29) binding that encapsulates information about a structure type (i.e., like the initial identifier bound by [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29)), and the binding must supply a constructor, a predicate, and all field accessors.\n\nEach field-id must correspond to a field-id in the [structure type defining forms](define-struct.html) of id (or parent-id, if present). The accessor bindings determined by different field-ids under the same id (or parent-id, if present) must be distinct. The order of the field-ids need not match the order of the corresponding fields in the structure type.\n\nThe struct-expr is evaluated first. The result must be an instance of the id structure type, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. Next, the field exprs are evaluated in order (even if the fields that correspond to the field-ids are in a different order). Finally, the new structure instance is created.\n\nThe result of struct-expr can be an instance of a sub-type of id, but the resulting copy is an immediate instance of id (not the sub-type).\n\nExamples:\n\n> ```racket\n> > ( struct fish ( color weight ) #:transparent )\n> > ( define marlin ( fish ' orange-and-white 11 ) )\n> > ( define dory ( struct-copy fish marlin [ color ' blue ] ) )\n> > dory\n> (fish 'blue 11)\n> > ( struct shark fish ( weeks-since-eating-fish ) #:transparent )\n> > ( define bruce ( shark ' grey 110 3 ) )\n> > ( define chum ( struct-copy shark bruce [ weight #:parent fish 90 ] [ weeks-since-eating-fish 0 ] ) )\n> > chum\n> (shark 'grey 90 0)\n> ; subtypes can be copied as if they were supertypes,\n> ; but the result is an instance of the supertype\n> > ( define not-really-chum ( struct-copy fish bruce [ weight 90 ] ) )\n> > not-really-chum\n> (fish 'grey 90)\n> ```\n\n------------------------------------------------------------------------\n\n# 5.6 Structure Utilities\n\n### 5.6 Structure Utilities\n\n> ```\n(struct → vector v [opaque-v) → vector?\n  v : any/c\n  opaque-v : any/c = '...\n```"} {"text": "# 5.4 Generic Interfaces\nCreates a vector representing v. The first slot of the result vector contains a symbol whose printed name has the form struct:id. Each remaining slot contains either the value of a field in v, if it is accessible via the current inspector, or opaque-v for a field that is not accessible. A single opaque-v value is used in the vector for contiguous inaccessible fields. (Consequently, the size of the vector does not match the size of the struct if more than one field is inaccessible.)\n> ```\n(struct? v)  →  any\n  v : any/c```\nReturns #t if [struct-info](inspectors.html#%28def._%28%28quote._~23~25kernel%29._struct-info%29%29) exposes any structure types of v with the current inspector, #f otherwise.\nTypically, when ([struct?](#%28def._%28%28quote._~23~25kernel%29._struct~3f%29%29) v) is true, then ([struct->vector](#%28def._%28%28quote._~23~25kernel%29._struct-~3evector%29%29) v) exposes at least one field value. It is possible, however, for the only visible types of v to contribute zero fields.\n> ```\n(struct-type? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a structure type descriptor value, #f otherwise.\n\n> ```\n(struct-constructor-procedure? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a constructor procedure generated by [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) or [make-struct-type](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._make-struct-type%29%29), #f otherwise.\n\n> ```\n(struct-predicate-procedure? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 5.4 Generic Interfaces\nReturns #t if v is a predicate procedure generated by struct or make-struct-type, #f otherwise.\n> ```\n(struct-accessor-procedure? v)  →  boolean?\n  v : any/c```\nReturns #t if v is an accessor procedure generated by [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29), [make-struct-type](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._make-struct-type%29%29), or [make-struct-field-accessor](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._make-struct-field-accessor%29%29), #f otherwise.\n> ```\n(struct-mutator-procedure? v)  →  boolean?\n  v : any/c\n```\n(parameter)\t→\t\n(-> or/c #f symbol? list?)```\n\n\nReturns #f if v is not an instance of a [prefab](structures.html#%28tech._prefab%29) structure type. Otherwise, the result is the shorted key that could be used with [make-prefab-struct](#%28def._%28%28quote._~23~25kernel%29._make-prefab-struct%29%29) to create an instance of the structure type.\n\nExamples:\n\n> ```racket\n> > ( prefab-struct-key #s ( cat \"Garfield\" ) )\n> 'cat\n> > ( struct cat ( name ) #:prefab )\n> > ( struct cute-cat cat ( shipping-dest ) #:prefab )\n> > ( cute-cat \"Nermel\" \"Abu Dhabi\" )\n> '#s((cute-cat cat 1) \"Nermel\" \"Abu Dhabi\")\n> > ( prefab-struct-key ( cute-cat \"Nermel\" \"Abu Dhabi\" ) )\n> '(cute-cat cat 1)\n> ```\n\n> ```\n(make-prefab-struct key v ...) → struct?\n  key : prefab-key?\n  v : any/c\n```\nCreates an instance of a prefab structure type, using the vs as field values. The key and the number of vs determine the prefab structure type."} {"text": "# 5.4 Generic Interfaces\nA key identifies a structure type based on a list with the following items:\n- A symbol for the structure type’s name.\n- An exact, nonnegative integer representing the number of non-automatic fields in the structure type, not counting fields from the supertype (if any).\n- A list of two items, where the first is an exact, nonnegative integer for the number of automatic fields in the structure type that are not from the supertype (if any), and the second element is an arbitrary value that is the value for the automatic fields.\n- A vector of exact, nonnegative integers that indicate mutable non-automatic fields in the structure type, counting from 0 and not including fields from the supertype (if any).\n- Nothing else, if the structure type has no supertype. Otherwise, the rest of the list is the key for the supertype.\nAn empty vector and an auto-field list that starts with 0 can be omitted. Furthermore, the first integer (which indicates the number of non-automatic fields) can be omitted, since it can be inferred from the number of supplied vs. Finally, a single symbol can be used instead of a list that contains only a symbol (in the case that the structure type has no supertype, no automatic fields, and no mutable fields).\nThe total field count must be no more than 32768. If the number of fields indicated by key is inconsistent with the number of supplied vs, the exn:fail:contract exception is raised.\nExamples:"} {"text": "# 5.4 Generic Interfaces\n> ```racket\n> > ( make-prefab-struct ' clown \"Binky\" \"pie\" )\n> '#s(clown \"Binky\" \"pie\")\n> > ( make-prefab-struct ' ( clown 2 ) \"Binky\" \"pie\" )\n> '#s(clown \"Binky\" \"pie\")\n> > ( make-prefab-struct ' ( clown 2 ( 0 #f ) # ( ) ) \"Binky\" \"pie\" )\n> '#s(clown \"Binky\" \"pie\")\n> > ( make-prefab-struct ' ( clown 1 ( 1 #f ) # ( ) ) \"Binky\" \"pie\" )\n> '#s((clown (1 #f)) \"Binky\" \"pie\")\n> > ( make-prefab-struct ' ( clown 1 ( 1 #f ) # ( 0 ) ) \"Binky\" \"pie\" )\n> '#s((clown (1 #f) #(0)) \"Binky\" \"pie\")\n> ```\n> ```\n(prefab-struct-type-key+field-count type)\n  →  (or/c #f (cons/c prefab-key? (integer-in 0 32768)))\n  type : struct-type?```\nReturns a pair containing the [prefab](structures.html#%28tech._prefab%29) key and field count for the [structure type descriptor](define-struct.html#%28tech._structure._type._descriptor%29) type if it represents a prefab structure type, #f otherwise.\nAdded in version 8.5.0.8 of package base.\n> ```\n(prefab-key → struct-type key field-count)  →  struct-type?\n  key : prefab-key?\n  field-count : (integer-in 0 32768)"} {"text": "# 5.4 Generic Interfaces\n```\nReturns a structure type descriptor for the prefab structure type specified by the combination of key and field-count.\n\nIf the number of fields indicated by key is inconsistent with field-count, the exn:fail:contract exception is raised.\n\n> ```\n(prefab-key? v)  →  boolean?\n  v : any/c```\n\n\nReturn #t if v can be a [prefab](structures.html#%28tech._prefab%29) structure type key, #f otherwise.\n\nSee [make-prefab-struct](#%28def._%28%28quote._~23~25kernel%29._make-prefab-struct%29%29) for a description of valid key shapes.\n\n#### 5.6.1 Additional Structure Utilities\n\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/struct](#%28mod-path._racket%2Fstruct%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/struct](#%28mod-path._racket%2Fstruct%29) library, not [racket/base](index.html) or [racket](index.html).\n\n> ```\n(parameter)\t→\t\n(-> any/c output-port? (or/c #t #f 0 1) void?)\n```"} {"text": "# 5.4 Generic Interfaces\nProduces a function suitable as a value for gen:custom-write or prop:custom-write. The function prints values in “constructor style.” When the value is printed as an expression, it is shown as an application of the constructor (as returned by get-constructor) to the contents (as returned by get-contents). When given to write, it is shown as an unreadable value with the constructor separated from the contents by a colon.\nExamples:\n> ```racket\n> > ( struct point ( x y ) #:methods gen:custom-write [ ( define write-proc ( make-constructor-style-printer ( lambda ( obj ) ' point ) ( lambda ( obj ) ( list ( point-x obj ) ( point-y obj ) ) ) ) ) ] )\n> > ( print ( point 1 2 ) )\n> (point 1 2)\n> > ( write ( point 1 2 ) )\n> #\n> ```\nThe function also cooperates with pretty-print:\n> ```racket\n> > ( parameterize ( ( pretty-print-columns 10 ) ) ( pretty-print ( point 3000000 4000000 ) ) )\n> (point 3000000 4000000)\n> > ( parameterize ( ( pretty-print-columns 10 ) ) ( pretty-write ( point 3000000 4000000 ) ) )\n> #\n> ```\nNote that the printer uses a separate property, prop:custom-print-quotable, to determine whether a struct instance is quotable. If so, the printer may print it in write mode it in certain contexts, such as within a list. For example:\n> ```racket\n> > ( print ( list ( point 1 2 ) ( point 3 4 ) ) )\n> '(# #)\n> ```\nUse #:property prop:custom-print-quotable 'never to prevent a struct instance from being considered quotable. For example:"} {"text": "# 5.4 Generic Interfaces\n> ```racket\n> > ( struct point2 ( x y ) #:property prop:custom-print-quotable ' never #:methods gen:custom-write [ ( define write-proc ( make-constructor-style-printer ( lambda ( obj ) ' point ) ( lambda ( obj ) ( list ( point2-x obj ) ( point2-y obj ) ) ) ) ) ] )\n> > ( print ( list ( point2 1 2 ) ( point2 3 4 ) ) )\n> (list (point 1 2) (point 3 4))\n> ```\nKeyword arguments can be simulated with unquoted-printing-string:\n> ```racket\n> ; Private implementation\n> > ( struct kwpoint-impl ( x y ) #:methods gen:custom-write [ ( define write-proc ( make-constructor-style-printer ( lambda ( obj ) ' kwpoint ) ( lambda ( obj ) ( list ( unquoted-printing-string \"#:x\" ) ( kwpoint-impl-x obj ) ( unquoted-printing-string \"#:y\" ) ( kwpoint-impl-y obj ) ) ) ) ) ] )\n> ; Public ``constructor''\n> > ( define ( kwpoint #:x x #:y y ) ( kwpoint-impl x y ) )\n> ; Example use\n> > ( print ( kwpoint #:x 1 #:y 2 ) )\n> (kwpoint #:x 1 #:y 2)\n> > ( write ( kwpoint #:x 3 #:y 4 ) )\n> #\n> ```\nAdded in version 6.3 of package base.\n> ```\n(struct → list v [#:on-opaque on-opaque) → (or/c list? #f)\n  v : any/c\n  on-opaque : (or/c 'error 'return-false 'skip) = 'error```\nReturns a list containing the struct instance v’s fields. Unlike [struct->vector](#%28def._%28%28quote._~23~25kernel%29._struct-~3evector%29%29), the struct name itself is not included."} {"text": "# 5.4 Generic Interfaces\nIf any fields of v are inaccessible via the current inspector the behavior of [struct->list](#%28def._%28%28lib._racket%2Fstruct..rkt%29._struct-~3elist%29%29) is determined by on-opaque. If on-opaque is 'error (the default), an error is raised. If it is 'return-false, [struct->list](#%28def._%28%28lib._racket%2Fstruct..rkt%29._struct-~3elist%29%29) returns #f. If it is 'skip, the inaccessible fields are omitted from the list.\nExamples:\n> ```racket\n> > ( struct open ( u v ) #:transparent )\n> > ( struct->list ( open ' a ' b ) )\n> '(a b)\n> > ( struct->list #s ( pre 1 2 3 ) )\n> '(1 2 3)\n> > ( struct secret open ( x y ) )\n> > ( struct->list ( secret 0 1 17 22 ) )\n> struct->list: expected argument of type ;\n> given: (secret 0 1 ...)\n> > ( struct->list ( secret 0 1 17 22 ) #:on-opaque ' return-false )\n> #f\n> > ( struct->list ( secret 0 1 17 22 ) #:on-opaque ' skip )\n> '(0 1)\n> > ( struct->list ' not-a-struct #:on-opaque ' return-false )\n> #f\n> > ( struct->list ' not-a-struct #:on-opaque ' skip )\n> '()\n> ```\nAdded in version 6.3 of package base.\n------------------------------------------------------------------------"} {"text": "# 5.7 Structure Type Transformer Binding"} {"text": "### 5.7 Structure Type Transformer Binding\nThe [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) form binds the name of a structure type as a [transformer](syntax-model.html#%28tech._transformer%29) binding that records the other identifiers bound to the structure type, the constructor procedure, the predicate procedure, and the field accessor and mutator procedures. This information can be used during the expansion of other expressions via [syntax-local-value](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._syntax-local-value%29%29).\nFor example, the [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) variant for subtypes uses the base type name t to find the variable struct:t containing the base type’s descriptor; it also folds the field accessor and mutator information for the base type into the information for the subtype. As another example, the [match](match.html#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%29%29) form uses a type name to find the predicates and field accessors for the structure type. The [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) form in an imported signature for [unit](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._unit%29%29) causes the [unit](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._unit%29%29) transformer to generate information about imported structure types, so that [match](match.html#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%29%29) and subtyping [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) forms work within the unit."} {"text": "# 5.7 Structure Type Transformer Binding\nThe expansion-time information for a structure type can be represented directly as a list of six elements (of the same sort that the encapsulated procedure must return):\n- an identifier that is bound to the structure type’s descriptor, or #f if none is known;\n- an identifier that is bound to the structure type’s constructor, or #f if none is known;\n- an identifier that is bound to the structure type’s predicate, or #f if none is known;\n- a list of identifiers bound to the field accessors of the structure type, optionally with #f as the list’s last element. A #f as the last element indicates that the structure type may have additional fields, otherwise the list is a reliable indicator of the number of fields in the structure type. Furthermore, the accessors are listed in reverse order for the corresponding constructor arguments. (The reverse order enables sharing in the lists for a subtype and its base type.)\n- a list of identifiers bound to the field mutators of the structure type, or #f for each field that has no known mutator, and optionally with an extra #f as the list’s last element (if the accessor list has such a #f). The list’s order and the meaning of a final #f are the same as for the accessor identifiers, and the length of the mutator list is the same as the accessor list’s length."} {"text": "# 5.7 Structure Type Transformer Binding\n- an identifier that determines a super-type for the structure type, #f if the super-type (if any) is unknown, or #t if there is no super-type. If a super-type is specified, the identifier is also bound to structure-type expansion-time information.\nInstead of this direct representation, the representation can be a structure created by [make-struct-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._make-struct-info%29%29) (or an instance of a subtype of [struct:struct-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._struct~3astruct-info%29%29)), which encapsulates a procedure that takes no arguments and returns a list of six elements. Alternately, the representation can be a structure whose type has the [prop:struct-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._prop~3astruct-info%29%29) [structure type property](structprops.html#%28tech._structure._type._property%29). Finally, the representation can be an instance of a structure type derived from [struct:struct-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._struct~3astruct-info%29%29) or with the [prop:struct-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._prop~3astruct-info%29%29) property that also implements [prop:procedure](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._prop~3aprocedure%29%29), and where the instance is further is wrapped by [make-set!-transformer](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._make-set%21-transformer%29%29). In addition, the representation may implement the [prop:struct-auto-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._prop~3astruct-auto-info%29%29) and [prop:struct-field-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._prop~3astruct-field-info%29%29) properties."} {"text": "# 5.7 Structure Type Transformer Binding\nUse [struct-info?](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._struct-info~3f%29%29) to recognize all allowed forms of the information, and use [extract-struct-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._extract-struct-info%29%29) to obtain a list from any representation.\nThe implementor of a syntactic form can expect users of the form to know what kind of information is available about a structure type. For example, the [match](match.html#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%29%29) implementation works with structure information containing an incomplete set of accessor bindings, because the user is assumed to know what information is available in the context of the [match](match.html#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%29%29) expression. In particular, the [match](match.html#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%29%29) expression can appear in a [unit](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._unit%29%29) form with an imported structure type, in which case the user is expected to know the set of fields that are listed in the signature for the structure type."} {"text": "# 5.7 Structure Type Transformer Binding\n| | |\n|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/struct-info]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/struct-info]() library, not [racket/base](index.html) or [racket](index.html).\n> ```\n(struct-info? v)  →  boolean?\n  v : any/c"} {"text": "# 5.7 Structure Type Transformer Binding\n```\nReturns #t if v is either a six-element list with the correct shape for representing structure-type information, a procedure encapsulated by make-struct-info, a structure with the prop:struct-info property, or a structure type derived from struct:struct-info or with prop:struct-info and wrapped with make-set!-transformer.\n\n> ```\n(checked-struct-info? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a procedure encapsulated by [make-struct-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._make-struct-info%29%29) and produced by [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29), but only when no parent type is specified or the parent type is also specified through a transformer binding to such a value.\n\n> ```\n(make-struct-info thunk)  →  struct-info?\n  thunk : ( →  (and/c struct-info? list?))\n```\nEncapsulates a thunk that returns structure-type information in list form. Note that accessors are listed in reverse order, as mentioned in [Structure Type Transformer Binding](). Note that the field names are not well-defined for struct-type informations that are created with this method, so it is likely not going to work well with forms like struct-copy and struct*.\nExamples:"} {"text": "# 5.7 Structure Type Transformer Binding\n> ```racket\n> > ( define ( new-pair? x ) ( displayln \"new pair?\" ) ( pair? x ) )\n> > ( define ( new-car x ) ( displayln \"new car\" ) ( car x ) )\n> > ( define ( new-cdr x ) ( displayln \"new cdr\" ) ( cdr x ) )\n> > ( define-syntax new-list ( make-struct-info ( λ ( ) ( list #f #' cons #' new-pair? ( list #' new-cdr #' new-car ) ( list #f #f ) #t ) ) ) )\n> > ( match ( list 1 2 3 ) [ ( new-list hd tl ) ( append tl ( list hd ) ) ] )\n> new pair? new car new cdr\n> '(2 3 1)\n> ```\nExamples:\n> ```racket\n> > ( struct A ( x y ) )\n> > ( define ( new-A-x a ) ( displayln \"A-x\" ) ( A-x a ) )\n> > ( define ( new-A-y a ) ( displayln \"A-y\" ) ( A-y a ) )\n> > ( define ( new-A? a ) ( displayln \"A?\" ) ( A? a ) )\n> > ( define-syntax A-info ( make-struct-info ( λ ( ) ( list #' A #' A #' new-A? ( list #' new-A-y #' new-A-x ) ( list #f #f ) #t ) ) ) )\n> > ( define-match-expander B ( syntax-rules ( ) [ ( _ x ... ) ( A-info x ... ) ] ) )\n> > ( match ( A 10 20 ) [ ( B x y ) ( list y x ) ] )\n> A? A-x A-y\n> '(20 10)\n> ```\n> ```\n(extract-struct-info v) → (and/c struct-info? list?)\n  v : struct-info?```\nExtracts the list form of the structure type information represented by v.\n>
\n

value

\n

[struct:struct-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._struct~3astruct-info%29%29) : [struct-type?](structutils.html#%28def._%28%28quote._~23~25kernel%29._struct-type~3f%29%29)

"} {"text": "# 5.7 Structure Type Transformer Binding\nThe [structure type descriptor](define-struct.html#%28tech._structure._type._descriptor%29) for the structure type returned by [make-struct-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._make-struct-info%29%29). This [structure type descriptor](define-struct.html#%28tech._structure._type._descriptor%29) is mostly useful for creating structure subtypes. The structure type includes a guard that checks an instance’s first field in the same way as [make-struct-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._make-struct-info%29%29).\n>
\n

value

\n

[prop:struct-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._prop~3astruct-info%29%29) : [struct-type-property?](structprops.html#%28def._%28%28quote._~23~25kernel%29._struct-type-property~3f%29%29)

\nThe [structure type property](structprops.html#%28tech._structure._type._property%29) for creating new structure types like [struct:struct-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._struct~3astruct-info%29%29). The property value must be a procedure of one argument that takes an instance structure and returns structure-type information in list form.\n> ```\nvalue\nprop:struct-auto-info : struct-type-property?\n(struct-auto-info? v)  →  boolean?\n  v : any/c\n(struct-auto-info-lists sai)\n  →  (list/c (listof identifier?) (listof identifier?))\n  sai : struct-auto-info?"} {"text": "# 5.7 Structure Type Transformer Binding\n```\n(parameter)\t→\t\n(-> struct-field-info-list sfi)```\n\n\nThe [prop:struct-field-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._prop~3astruct-field-info%29%29) property is implemented to provide static information about field names in a structure type. The property value must be a procedure that accepts an instance structure to which the property is given, and the result must be a list of symbols suitable as a result from [struct-field-info-list](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._struct-field-info-list%29%29).\n\nThe [struct-field-info?](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._struct-field-info~3f%29%29) predicate recognizes values that implement the [prop:struct-field-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._prop~3astruct-field-info%29%29) property.\n\nThe [struct-field-info-list](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._struct-field-info-list%29%29) function extracts a list of symbols from a value that implements the [prop:struct-field-info](#%28def._%28%28lib._racket%2Fstruct-info..rkt%29._prop~3astruct-field-info%29%29) property. The list should contain every immediate field name (that is, not including fields from its super struct type) in the reverse order.\n\nExamples:\n\n> ```racket\n> > ( struct foo ( x ) )\n> > ( struct bar foo ( y z ) )\n> > ( define-syntax ( get-bar-field-names stx ) #` ' #, ( struct-field-info-list ( syntax-local-value #' bar ) ) )\n> > ( get-bar-field-names )\n> '(z y)\n> ```\n\nAdded in version 7.7.0.9 of package base.\n\n------------------------------------------------------------------------\n\n# 6 Classes and Objects\n\n## 6 Classes and Objects\n\n> > > \"+\"[Classes and Objects](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=classes.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces classes and objects.\n\n| | |\n|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/class]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/class]() and [racket](index.html) libraries, but not [racket/base](index.html).\n\nA class specifies\n\n- a collection of fields;\n\n- a collection of methods;\n\n- initial value expressions for the fields; and\n\n- initialization variables that are bound to initialization arguments.\n\nIn the context of the class system, an object is a collection of bindings for fields that are instantiated according to a class description.\n\nThe class system allows a program to define a new class (a derived class) in terms of an existing class (the superclass) using inheritance, overriding, and augmenting:\n\n- inheritance: An object of a derived class supports methods and instantiates fields declared by the derived class’s superclass, as well as methods and fields declared in the derived class expression.\n\n- overriding: Some methods declared in a superclass can be replaced in the derived class. References to the overridden method in the superclass use the implementation in the derived class.\n\n- augmenting: Some methods declared in a superclass can be merely extended in the derived class. The superclass method specifically delegates to the augmenting method in the derived class.\n\nAn interface is a collection of method names to be implemented by a class, potentially with default implementations some methods, combined with a derivation requirement. A class implements an interface when it\n\n- declares (or inherits) a public method for each method in the interface (that does not have an implementation in the interface);\n\n- is derived from the class required by the interface, if any; and\n\n- specifically declares its intention to implement the interface.\n\nA class can implement any number of interfaces. A derived class automatically implements any interface that its superclass implements. Each class also implements an implicitly-defined interface that is associated with the class. The implicitly-defined interface contains all of the class’s public method names, and it requires that all other implementations of the interface are derived from the class. When a class implements an interface but does not explicitly declare an implementation of a method that has a default implementation in the interface, then the default implementation is used for the class.\n\nA new interface can extend one or more interfaces with additional method names; each class that implements the extended interface also implements the original interfaces. The derivation requirements of the original interface must be consistent, and the extended interface inherits the most specific derivation requirement from the original interfaces.\n\nClasses, objects, and interfaces are all values. However, a class or interface is not an object (i.e., there are no “meta-classes” or “meta-interfaces”).\n\n| |\n|--------------------------------------------------------------------------------------------------------------------------|\n|     [6.1 Creating Interfaces](createinterface.html) |\n|     [6.2 Creating Classes](createclass.html) |\n|       [6.2.1 Initialization Variables](createclass.html#%28part._clinitvars%29) |\n|       [6.2.2 Fields](createclass.html#%28part._clfields%29) |\n|       [6.2.3 Methods](createclass.html#%28part._clmethods%29) |\n|         [6.2.3.1 Method Definitions](createclass.html#%28part._clmethoddefs%29) |\n|         [6.2.3.2 Inherited and Superclass Methods](createclass.html#%28part._classinherit%29) |\n|         [6.2.3.3 Internal and External Names](createclass.html#%28part._extnames%29) |\n|     [6.3 Creating Objects](objcreation.html) |\n|     [6.4 Field and Method Access](ivaraccess.html) |\n|       [6.4.1 Methods](ivaraccess.html#%28part._methodcalls%29) |\n|       [6.4.2 Fields](ivaraccess.html#%28part._.Fields%29) |\n|       [6.4.3 Generics](ivaraccess.html#%28part._.Generics%29) |\n|     [6.5 Mixins](mixins.html) |\n|     [6.6 Traits](trait.html) |\n|     [6.7 Object and Class Contracts](Object_and_Class_Contracts.html) |\n|     [6.8 Object Equality and Hashing](objectequality.html) |\n|     [6.9 Object Serialization](objectserialize.html) |\n|     [6.10 Object Printing](objectprinting.html) |\n|     [6.11 Object, Class, and Interface Utilities](objectutils.html) |\n|     [6.12 Surrogates](Surrogates.html) |\n\n------------------------------------------------------------------------\n\n# 6.1 Creating Interfaces\n\n### 6.1 Creating Interfaces\n\n> > > \"+\"[Classes and Objects](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=classes.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces classes, objects, and interfaces.\n\n>
\n\n

syntax

\n\n

([interface](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._interface%29%29) (super-interface-expr ...) name-clause ...)

 
name-clause = id
  | (id contract-expr)
  | (id #:public default-expr)
  | (id #:override default-expr)
  | (id contract-expr #:public impl-expr)
  | (id contract-expr #:override impl-expr)
\n\nProduces an interface. The ids must be mutually distinct.\n\nEach super-interface-expr is evaluated (in order) when the [interface](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._interface%29%29) expression is evaluated. The result of each super-interface-expr must be an interface value, otherwise the [exn:fail:object](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._exn~3afail~3aobject%29%29) exception is raised. The interfaces returned by the super-interface-exprs are the new interface’s superinterfaces, which are all extended by the new interface. Any class that implements the new interface also implements all of the superinterfaces.\n\nThe result of an [interface](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._interface%29%29) expression is an interface that includes all of the specified ids, plus all identifiers from the superinterfaces. A given id may be paired with a corresponding contract-expr, and it may have a impl-expr, which supplies an implementation of id to be inherited or overridden in an implementing class. Each impl-expr must be a method-procedure; see [Method Definitions](createclass.html#%28part._clmethoddefs%29). Duplicate identifier names among the superinterfaces are ignored, as long as no more than one of them provides a default implementation for each identifier that originated in a different interface.\n\nAn interface can provide an implementation of a method using #:public if no superinterface has an implementation of the method, or using #:override otherwise. If multiple superinterfaces provide implementations of a method that originate from different ancestor interfaces, then the method must be overridden. The [super](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._super%29%29) form is not supported within an interface method implementation.\n\nIf no super-interface-exprs are provided, then the [derivation requirement](mzlib_class.html#%28tech._derivation._requirement%29) of the resulting interface is trivial: any class that implements the interface must be derived from [object%](createclass.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._object~25%29%29). Otherwise, the implementation requirement of the resulting interface is the most specific requirement from its superinterfaces. If the superinterfaces specify inconsistent [derivation requirements](mzlib_class.html#%28tech._derivation._requirement%29), then [exn:fail:object](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._exn~3afail~3aobject%29%29) exception is raised is raised.\n\nExamples:\n\n> ```racket\n> ( define file-interface<%> ( interface ( ) open close read-byte write-byte [ append-line #:public ( λ ( bts ) ( send this open ' append ) ( for ( [ b ( in-bytes bts ) ] ) ( send this write-byte b ) ) ( send this close ) ) ] ) )\n> ( define directory-interface<%> ( interface ( file-interface<%> ) [ file-list ( -> m ( listof ( is-a?/c file-interface<%> ) ) ) ] parent-directory ) )\n> ```\n\nChanged in version 8.17.0.4 of package base: Added support for #:public and #:override method implementations.\n\n> ```\nsyntax\n\n(interface* (super-interface-expr ...)\n> ( [ property-expr val-expr ] ... )\n> name-clause ... )\n \nname-clause   =   id\n    |   (id contract-expr)\n    |   (id #:public default-expr)\n    |   (id #:override default-expr)\n    |   (id contract-expr #:public default-expr)\n    |   (id contract-expr #:override default-expr)\n```"} {"text": "# 5.7 Structure Type Transformer Binding\nLike interface, but also associates to the interface the structure-type properties produced by the property-exprs with the corresponding val-exprs.\nWhenever the resulting interface (or a sub-interface derived from it) is explicitly implemented by a class through the class* form, each property is attached with its value to a structure type that instantiated by instances of the class. Specifically, the property is attached to a structure type with zero immediate fields, which is extended to produce the internal structure type for instances of the class (so that no information about fields is accessible to the structure type property’s guard, if any).\nExample:\n> ```racket\n> ( define i<%> ( interface* ( ) ( [ prop:custom-write ( lambda ( obj port mode ) ( void ) ) ] ) method1 method2 method3 ) )\n> ```\nChanged in version 8.17.0.4 of package base: Added support for #:public and #:override method implementations.\n------------------------------------------------------------------------"} {"text": "# 6.2 Creating Classes"} {"text": "### 6.2 Creating Classes\n> > > \"+\"Classes and Objects in The Racket Guide introduces classes and objects.\n>
\n

value

\n

object% : class?

\nA built-in class that has no methods fields, implements only its own interface (class → interface object%), and is transparent (i.e,. its inspector is #f, so all immediate instances are equal?). All other classes are derived from object%.\n> ```\nsyntax\n(class* superclass-expr (interface-expr ...)\n> class-clause\n> ... )\nclass-clause   =   (inspect inspector-expr)\n    |   (init init-decl ...)\n    |   (init-field init-decl ...)\n    |   (field field-decl ...)\n    |   (inherit-field maybe-renamed ...)\n    |   (init-rest id)\n    |   (init-rest)\n    |   (public maybe-renamed ...)\n    |   (pubment maybe-renamed ...)\n    |   (public-final maybe-renamed ...)\n    |   (override maybe-renamed ...)\n    |   (overment maybe-renamed ...)\n    |   (override-final maybe-renamed ...)\n    |   (augment maybe-renamed ...)\n    |   (augride maybe-renamed ...)\n    |   (augment-final maybe-renamed ...)\n    |   (private id ...)\n    |   (abstract id ...)\n    |   (inherit maybe-renamed ...)\n    |   (inherit/super maybe-renamed ...)\n    |   (inherit/inner maybe-renamed ...)\n    |   (rename-super renamed ...)\n    |   (rename-inner renamed ...)\n    |   method-definition\n    |   definition\n    |   expr\n    |   (begin class-clause ...)\ninit-decl   =   id"} {"text": "# 6.2 Creating Classes\n    |   (renamed)\n    |   (maybe-renamed default-value-expr)\nfield-decl   =   (maybe-renamed default-value-expr)\nmaybe-renamed   =   id\n    |   renamed\nrenamed   =   (internal-id external-id)\nmethod-definition   =   (define-values (id) method-procedure)\nmethod-procedure   =   (lambda kw-formals expr ...+)\n    |   (case-lambda (formals expr ...+) ...)\n    |   (#%plain-lambda formals expr ...+)\n    |   ( let-values ( [ ( id ) method-procedure ] ... )\n> method-procedure )\n    |   ( letrec-values ( [ ( id ) method-procedure ] ... )\n> method-procedure )\n    |   ( let-values ( [ ( id ) method-procedure ] ...+ )\n> id )\n    |   ( letrec-values ( [ ( id ) method-procedure ] ...+ )\n> id )\n    |   ( chaperone-procedure method-procedure wrapper-proc\n> other-arg-expr ... )```\nProduces a class value.\nThe superclass-expr expression is evaluated when the [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) expression is evaluated. The result must be a class value (possibly [object%](#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._object~25%29%29)), otherwise the [exn:fail:object](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._exn~3afail~3aobject%29%29) exception is raised. The result of the superclass-expr expression is the new class’s superclass."} {"text": "# 6.2 Creating Classes\nThe interface-expr expressions are also evaluated when the [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) expression is evaluated, after superclass-expr is evaluated. The result of each interface-expr must be an interface value, otherwise the [exn:fail:object](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._exn~3afail~3aobject%29%29) exception is raised. The interfaces returned by the interface-exprs are all implemented by the class. For each identifier in each interface, the class (or one of its ancestors) must declare a public method with the same name, otherwise the [exn:fail:object](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._exn~3afail~3aobject%29%29) exception is raised. The class’s superclass must satisfy the implementation requirement of each interface, otherwise the [exn:fail:object](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._exn~3afail~3aobject%29%29) exception is raised."} {"text": "# 6.2 Creating Classes\nAn [inspect](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inspect%29%29) class-clause selects an inspector (see [Structure Inspectors](inspectors.html)) for the class extension. The inspector-expr must evaluate to an inspector or #f when the [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is evaluated. Just as for structure types, an inspector controls access to the class’s fields, including private fields, and also affects comparisons using [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29). If no [inspect](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inspect%29%29) clause is provided, access to the class is controlled by the parent of the current inspector (see [Structure Inspectors](inspectors.html)). A syntax error is reported if more than one [inspect](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inspect%29%29) clause is specified."} {"text": "# 6.2 Creating Classes\nThe other class-clauses define initialization arguments, public and private fields, and public and private methods. For each id or maybe-renamed in a [public](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public%29%29), [override](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override%29%29), [augment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment%29%29), [pubment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._pubment%29%29), [overment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._overment%29%29), [augride](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augride%29%29), [public-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public-final%29%29), [override-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override-final%29%29), [augment-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment-final%29%29), or [private](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._private%29%29) clause, there must be one method-definition. All other definition class-clauses create private fields. All remaining exprs are initialization expressions to be evaluated when the class is instantiated (see [Creating Objects](objcreation.html))."} {"text": "# 6.2 Creating Classes\nThe result of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) expression is a new class, derived from the specified superclass and implementing the specified interfaces. Instances of the class are created with the [instantiate](objcreation.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._instantiate%29%29) form or [make-object](objcreation.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._make-object%29%29) procedure, as described in [Creating Objects](objcreation.html).\nEach class-clause is (partially) macro-expanded to reveal its shapes. If a class-clause is a [begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) expression, its sub-expressions are lifted out of the [begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) and treated as class-clauses, in the same way that [begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) is flattened for top-level and embedded definitions. Each class-clause has the [syntax property](stxprops.html#%28tech._syntax._property%29) 'class-body set to true before expansion."} {"text": "# 6.2 Creating Classes\nWithin a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form for instances of the new class, [this](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._this%29%29) is bound to the object itself; [this%](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._this~25%29%29) is bound to the class of the object; [super-instantiate](objcreation.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._super-instantiate%29%29), [super-make-object](objcreation.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._super-make-object%29%29), and [super-new](objcreation.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._super-new%29%29) are bound to forms to initialize fields in the superclass (see [Creating Objects](objcreation.html)); [super](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._super%29%29) is available for calling superclass methods (see [Method Definitions](#%28part._clmethoddefs%29)); and [inner](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inner%29%29) is available for calling subclass augmentations of methods (see [Method Definitions](#%28part._clmethoddefs%29)).\nChanged in version 8.8.0.10 of package base: Added the 'class-body syntax property to class body forms.\n>
\n

syntax

"} {"text": "# 6.2 Creating Classes\n

([class](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%29%29) superclass-expr class-clause ...)

\nLike [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29), but omits the interface-exprs, for the case that none are needed.\nExample:\n> ```racket\n> ( define book-class% ( class object% ( field ( pages 5 ) ) ( define/public ( letters ) ( * pages 500 ) ) ( super-new ) ) )\n> ```\n>
\n

syntax

\n

[this](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._this%29%29)

\nWithin a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form, [this](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._this%29%29) refers to the current object (i.e., the object being initialized or whose method was called). Use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:\n> ```racket\n> ( define ( describe obj ) ( printf \"Hello ~a\\n\" obj ) ) ( define table% ( class object% ( define/public ( describe-self ) ( describe this ) ) ( super-new ) ) )\n> > ( send ( new table% ) describe-self )\n> Hello #(struct:object:table% ...)\n> ```\n>
"} {"text": "# 6.2 Creating Classes\n

syntax

\n

[this%](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._this~25%29%29)

\nWithin a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form, [this%](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._this~25%29%29) refers to the class of the current object (i.e., the object being initialized or whose method was called). Use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:\n> ```racket\n> ( define account% ( class object% ( super-new ) ( init-field balance ) ( define/public ( add n ) ( new this% [ balance ( + n balance ) ] ) ) ) ) ( define savings% ( class account% ( super-new ) ( inherit-field balance ) ( define interest 0.04 ) ( define/public ( add-interest ) ( send this add ( * interest balance ) ) ) ) )\n> > ( let* ( [ acct ( new savings% [ balance 500 ] ) ] [ acct ( send acct add 500 ) ] [ acct ( send acct add-interest ) ] ) ( printf \"Current balance: ~a\\n\" ( get-field balance acct ) ) )\n> Current balance: 1040.0\n> ```\n>
\n

syntax

\n

([inspect](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inspect%29%29) inspector-expr)

"} {"text": "# 6.2 Creating Classes\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\n>
\n

syntax

\n

([init](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._init%29%29) init-decl ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Initialization Variables](#%28part._clinitvars%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExample:\n> ```racket\n> > ( class object% ( super-new ) ( init turnip [ ( internal-potato potato ) ] [ carrot ' good ] [ ( internal-rutabaga rutabaga ) ' okay ] ) )\n> #\n> ```\n>
\n

syntax

\n

([init-field](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._init-field%29%29) init-decl ...)

"} {"text": "# 6.2 Creating Classes\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29), [Initialization Variables](#%28part._clinitvars%29), and [Fields](#%28part._clfields%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExample:\n> ```racket\n> > ( class object% ( super-new ) ( init-field turkey [ ( internal-ostrich ostrich ) ] [ chicken 7 ] [ ( internal-emu emu ) 13 ] ) )\n> #\n> ```\n>
\n

syntax

\n

([field](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._field%29%29) field-decl ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Fields](#%28part._clfields%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExample:\n> ```racket\n> > ( class object% ( super-new ) ( field [ minestrone ' ready ] [ ( internal-coq-au-vin coq-au-vin ) ' stewing ] ) )\n> #\n> ```\n>
\n

syntax

\n

([inherit-field](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inherit-field%29%29) maybe-renamed ...)

"} {"text": "# 6.2 Creating Classes\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Fields](#%28part._clfields%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:\n> ```racket\n> ( define cookbook% ( class object% ( super-new ) ( field [ recipes ' ( caldo-verde oyakodon eggs-benedict ) ] [ pages 389 ] ) ) )\n> > ( class cookbook% ( super-new ) ( inherit-field recipes [ internal-pages pages ] ) )\n> #\n> ```\n>
\n

syntax

\n

([init-rest](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._init-rest%29%29) id)

([init-rest](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._init-rest%29%29))
\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Initialization Variables](#%28part._clinitvars%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:\n> ```racket\n> ( define fruit-basket% ( class object% ( super-new ) ( init-rest fruits ) ( displayln fruits ) ) )\n> > ( make-object fruit-basket% ' kiwi ' lychee ' melon )\n> (kiwi lychee melon)\n> (object:fruit-basket% ...)\n> ```"} {"text": "# 6.2 Creating Classes\n>
\n

syntax

\n

([public](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public%29%29) maybe-renamed ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Method Definitions](#%28part._clmethoddefs%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:\n> ```racket\n> ( define jumper% ( class object% ( super-new ) ( define ( skip ) ' skip ) ( define ( hop ) ' hop ) ( public skip [ hop jump ] ) ) )\n> > ( send ( new jumper% ) skip )\n> 'skip\n> > ( send ( new jumper% ) jump )\n> 'hop\n> ```\n>
\n

syntax

\n

([pubment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._pubment%29%29) maybe-renamed ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Method Definitions](#%28part._clmethoddefs%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:"} {"text": "# 6.2 Creating Classes\n> ```racket\n> ( define runner% ( class object% ( super-new ) ( define ( run ) ' run ) ( define ( trot ) ' trot ) ( pubment run [ trot jog ] ) ) )\n> > ( send ( new runner% ) run )\n> 'run\n> > ( send ( new runner% ) jog )\n> 'trot\n> ```\n>
\n

syntax

\n

([public-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public-final%29%29) maybe-renamed ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Method Definitions](#%28part._clmethoddefs%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:\n> ```racket\n> ( define point% ( class object% ( super-new ) ( init-field [ x 0 ] [ y 0 ] ) ( define ( get-x ) x ) ( define ( do-get-y ) y ) ( public-final get-x [ do-get-y get-y ] ) ) )\n> > ( send ( new point% [ x 1 ] [ y 3 ] ) get-y )\n> 3\n> > ( class point% ( super-new ) ( define ( get-x ) 3.14 ) ( override get-x ) )\n> class*: cannot override or augment final method\n> method name: get-x\n> class name: eval:25:0\n> ```\n>
\n

syntax

\n

([override](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override%29%29) maybe-renamed ...)

"} {"text": "# 6.2 Creating Classes\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Method Definitions](#%28part._clmethoddefs%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:\n> ```racket\n> ( define sheep% ( class object% ( super-new ) ( define/public ( bleat ) ( displayln \"baaaaaaaaah\" ) ) ) )\n> ( define confused-sheep% ( class sheep% ( super-new ) ( define ( bleat ) ( super bleat ) ( displayln \"???\" ) ) ( override bleat ) ) )\n> > ( send ( new sheep% ) bleat )\n> baaaaaaaaah\n> > ( send ( new confused-sheep% ) bleat )\n> baaaaaaaaah ???\n> ```\n>
\n

syntax

\n

([overment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._overment%29%29) maybe-renamed ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Method Definitions](#%28part._clmethoddefs%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:"} {"text": "# 6.2 Creating Classes\n> ```racket\n> ( define turkey% ( class object% ( super-new ) ( define/public ( gobble ) ( displayln \"gobble gobble\" ) ) ) )\n> ( define extra-turkey% ( class turkey% ( super-new ) ( define ( gobble ) ( super gobble ) ( displayln \"gobble gobble gobble\" ) ( inner ( void ) gobble ) ) ( overment gobble ) ) )\n> ( define cyborg-turkey% ( class extra-turkey% ( super-new ) ( define/augment ( gobble ) ( displayln \"110011111011111100010110001011011001100101\" ) ) ) )\n> > ( send ( new extra-turkey% ) gobble )\n> gobble gobble gobble gobble gobble\n> > ( send ( new cyborg-turkey% ) gobble )\n> gobble gobble gobble gobble gobble 110011111011111100010110001011011001100101\n> ```\n>
\n

syntax

\n

([override-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override-final%29%29) maybe-renamed ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Method Definitions](#%28part._clmethoddefs%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:"} {"text": "# 6.2 Creating Classes\n> ```racket\n> ( define meeper% ( class object% ( super-new ) ( define/public ( meep ) ( displayln \"meep\" ) ) ) )\n> ( define final-meeper% ( class meeper% ( super-new ) ( define ( meep ) ( super meep ) ( displayln \"This meeping ends with me\" ) ) ( override-final meep ) ) )\n> > ( send ( new meeper% ) meep )\n> meep\n> > ( send ( new final-meeper% ) meep )\n> meep This meeping ends with me\n> ```\n>
\n

syntax

\n

([augment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment%29%29) maybe-renamed ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Method Definitions](#%28part._clmethoddefs%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:\n> ```racket\n> ( define buzzer% ( class object% ( super-new ) ( define/pubment ( buzz ) ( displayln \"bzzzt\" ) ( inner ( void ) buzz ) ) ) )\n> ( define loud-buzzer% ( class buzzer% ( super-new ) ( define ( buzz ) ( displayln \"BZZZZZZZZZT\" ) ) ( augment buzz ) ) )\n> > ( send ( new buzzer% ) buzz )\n> bzzzt\n> > ( send ( new loud-buzzer% ) buzz )\n> bzzzt BZZZZZZZZZT\n> ```\n>
\n

syntax

"} {"text": "# 6.2 Creating Classes\n

([augride](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augride%29%29) maybe-renamed ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Method Definitions](#%28part._clmethoddefs%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\n>
\n

syntax

\n

([augment-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment-final%29%29) maybe-renamed ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Method Definitions](#%28part._clmethoddefs%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\n>
\n

syntax

\n

([private](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._private%29%29) id ...)

"} {"text": "# 6.2 Creating Classes\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Method Definitions](#%28part._clmethoddefs%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:\n> ```racket\n> ( define light% ( class object% ( super-new ) ( define on? #t ) ( define ( toggle ) ( set! on? ( not on? ) ) ) ( private toggle ) ( define ( flick ) ( toggle ) ) ( public flick ) ) )\n> > ( send ( new light% ) toggle )\n> send: no such method\n> method name: toggle\n> class name: light%\n> > ( send ( new light% ) flick )\n> ```\n>
\n

syntax

\n

([abstract](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._abstract%29%29) id ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Method Definitions](#%28part._clmethoddefs%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:"} {"text": "# 6.2 Creating Classes\n> ```racket\n> ( define train% ( class object% ( super-new ) ( abstract get-speed ) ( init-field [ position 0 ] ) ( define/public ( move ) ( new this% [ position ( + position ( get-speed ) ) ] ) ) ) )\n> ( define acela% ( class train% ( super-new ) ( define/override ( get-speed ) 241 ) ) )\n> ( define talgo-350% ( class train% ( super-new ) ( define/override ( get-speed ) 330 ) ) )\n> > ( new train% )\n> instantiate: cannot instantiate class with abstract methods\n> class: #\n> abstract methods:\n> get-speed\n> > ( send ( new acela% ) move )\n> (object:acela% ...)\n> ```\n>
\n

syntax

\n

([inherit](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inherit%29%29) maybe-renamed ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Inherited and Superclass Methods](#%28part._classinherit%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\nExamples:\n> ```racket\n> ( define alarm% ( class object% ( super-new ) ( define/public ( alarm ) ( displayln \"beeeeeeeep\" ) ) ) )\n> ( define car-alarm% ( class alarm% ( super-new ) ( init-field proximity ) ( inherit alarm ) ( when ( < proximity 10 ) ( alarm ) ) ) )> > ( new car-alarm% [ proximity 5 ] )\n> beeeeeeeep\n> (object:car-alarm% ...)\n> ```"} {"text": "# 6.2 Creating Classes\n>
\n

syntax

\n

([inherit/super](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inherit%2Fsuper%29%29) maybe-renamed ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Inherited and Superclass Methods](#%28part._classinherit%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\n>
\n

syntax

\n

([inherit/inner](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inherit%2Finner%29%29) maybe-renamed ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Inherited and Superclass Methods](#%28part._classinherit%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\n>
\n

syntax

\n

([rename-super](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._rename-super%29%29) renamed ...)

"} {"text": "# 6.2 Creating Classes\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Inherited and Superclass Methods](#%28part._classinherit%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\n>
\n

syntax

\n

([rename-inner](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._rename-inner%29%29) renamed ...)

\nSee [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) and [Inherited and Superclass Methods](#%28part._classinherit%29); use outside the body of a [class*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form is a syntax error.\n>
\n

syntax

\n

([public*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public%2A%29%29) (id expr) ...)

"} {"text": "# 6.2 Creating Classes\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([public](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public%29%29) id) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n>
\n

syntax

\n

([pubment*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._pubment%2A%29%29) (id expr) ...)

\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([pubment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._pubment%29%29) id) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n>
\n

syntax

\n

([public-final*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public-final%2A%29%29) (id expr) ...)

"} {"text": "# 6.2 Creating Classes\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([public-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public-final%29%29) id) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n>
\n

syntax

\n

([override*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override%2A%29%29) (id expr) ...)

\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([override](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override%29%29) id) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n>
\n

syntax

\n

([overment*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._overment%2A%29%29) (id expr) ...)

"} {"text": "# 6.2 Creating Classes\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([overment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._overment%29%29) id) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n>
\n

syntax

\n

([override-final*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override-final%2A%29%29) (id expr) ...)

\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([override-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override-final%29%29) id) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n>
\n

syntax

"} {"text": "# 6.2 Creating Classes\n

([augment*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment%2A%29%29) (id expr) ...)

\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([augment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment%29%29) id) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n>
\n

syntax

\n

([augride*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augride%2A%29%29) (id expr) ...)

\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([augride](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augride%29%29) id) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n>
\n

syntax

"} {"text": "# 6.2 Creating Classes\n

([augment-final*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment-final%2A%29%29) (id expr) ...)

\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([augment-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment-final%29%29) id) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n>
\n

syntax

\n

([private*](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._private%2A%29%29) (id expr) ...)

\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([private](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._private%29%29) id) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n>
"} {"text": "# 6.2 Creating Classes\n

syntax

\n

([define/public](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Fpublic%29%29) id expr)

([define/public](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Fpublic%29%29) (id . formals) body ...+)
\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([public](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr)) or ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([public](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) (id . formals) body ...+))\n>
\n

syntax

\n

([define/pubment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Fpubment%29%29) id expr)

([define/pubment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Fpubment%29%29) (id . formals) body ...+)
"} {"text": "# 6.2 Creating Classes\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([pubment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._pubment%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr)) or ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([pubment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._pubment%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) (id . formals) body ...+))\n>
\n

syntax

\n

([define/public-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Fpublic-final%29%29) id expr)

([define/public-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Fpublic-final%29%29) (id . formals) body ...+)
"} {"text": "# 6.2 Creating Classes\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([public-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public-final%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr)) or ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([public-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public-final%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) (id . formals) body ...+))\n>
\n

syntax

\n

([define/override](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Foverride%29%29) id expr)

([define/override](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Foverride%29%29) (id . formals) body ...+)
"} {"text": "# 6.2 Creating Classes\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([override](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr)) or ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([override](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) (id . formals) body ...+))\n>
\n

syntax

\n

([define/overment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Foverment%29%29) id expr)

([define/overment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Foverment%29%29) (id . formals) body ...+)
"} {"text": "# 6.2 Creating Classes\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([overment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._overment%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr)) or ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([overment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._overment%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) (id . formals) body ...+))\n>
\n

syntax

\n

([define/override-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Foverride-final%29%29) id expr)

([define/override-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Foverride-final%29%29) (id . formals) body ...+)
"} {"text": "# 6.2 Creating Classes\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([override-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override-final%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr)) or ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([override-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override-final%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) (id . formals) body ...+))\n>
\n

syntax

\n

([define/augment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Faugment%29%29) id expr)

([define/augment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Faugment%29%29) (id . formals) body ...+)
"} {"text": "# 6.2 Creating Classes\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([augment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr)) or ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([augment](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) (id . formals) body ...+))\n>
\n

syntax

\n

([define/augride](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Faugride%29%29) id expr)

([define/augride](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Faugride%29%29) (id . formals) body ...+)
"} {"text": "# 6.2 Creating Classes\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([augride](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augride%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr)) or ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([augride](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augride%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) (id . formals) body ...+))\n>
\n

syntax

\n

([define/augment-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Faugment-final%29%29) id expr)

([define/augment-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Faugment-final%29%29) (id . formals) body ...+)
"} {"text": "# 6.2 Creating Classes\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([augment-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment-final%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr)) or ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([augment-final](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment-final%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) (id . formals) body ...+))\n>
\n

syntax

\n

([define/private](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Fprivate%29%29) id expr)

([define/private](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Fprivate%29%29) (id . formals) body ...+)
"} {"text": "# 6.2 Creating Classes\nShorthand for ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([private](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._private%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id expr)) or ([begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) ([private](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._private%29%29) id) ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) (id . formals) body ...+))\n> ```\nsyntax\n(class/derived original-datum\n> ( name-id super-expr ( interface-expr ... ) deserialize-id-expr )\n> class-clause\n> ... )"} {"text": "# 6.2 Creating Classes\n```\nLike class*, but includes a sub-expression to be used as the source for all syntax errors within the class definition. For example, define-serializable-class expands to class/derived so that errors in the body of the class are reported in terms of define-serializable-class instead of class.\n\nThe original-datum is the original expression to use for reporting errors.\n\nThe name-id is used to name the resulting class; if it is #f, the class name is inferred.\n\nThe super-expr, interface-exprs, and class-clauses are as for class*.\n\nIf the deserialize-id-expr is not literally #f, then a serializable class is generated, and the result is two values instead of one: the class and a deserialize-info structure produced by make-deserialize-info. The deserialize-id-expr should produce a value suitable as the second argument to make-serialize-info, and it should refer to an export whose value is the deserialize-info structure.\n\nFuture optional forms may be added to the sequence that currently ends with deserialize-id-expr.\n\n#### 6.2.1 Initialization Variables\n\nA class’s initialization variables, declared with init, init-field, and init-rest, are instantiated for each object of a class. Initialization variables can be used in the initial value expressions of fields, default value expressions for initialization arguments, and in initialization expressions. Only initialization variables declared with init-field can be accessed from methods; accessing any other initialization variable from a method is a syntax error.\n\nThe values bound to initialization variables are\n\n- the arguments provided with instantiate or passed to make-object, if the object is created as a direct instance of the class; or,\n\n- the arguments passed to the superclass initialization form or procedure, if the object is created as an instance of a derived class.\n\nIf an initialization argument is not provided for an initialization variable that has an associated default-value-expr, then the default-value-expr expression is evaluated to obtain a value for the variable. A default-value-expr is only evaluated when an argument is not provided for its variable. The environment of default-value-expr includes all of the initialization variables, all of the fields, and all of the methods of the class. If multiple default-value-exprs are evaluated, they are evaluated from left to right. Object creation and field initialization are described in detail in Creating Objects.\n\nIf an initialization variable has no default-value-expr, then the object creation or superclass initialization call must supply an argument for the variable, otherwise the exn:fail:object exception is raised.\n\nInitialization arguments can be provided by name or by position. The external name of an initialization variable can be used with instantiate or with the superclass initialization form. Those forms also accept by-position arguments. The make-object procedure and the superclass initialization procedure accept only by-position arguments.\n\nArguments provided by position are converted into by-name arguments using the order of init and init-field clauses and the order of variables within each clause. When an instantiate form provides both by-position and by-name arguments, the converted arguments are placed before by-name arguments. (The order can be significant; see also Creating Objects.)\n\nUnless a class contains an init-rest clause, when the number of by-position arguments exceeds the number of declared initialization variables, the order of variables in the superclass (and so on, up the superclass chain) determines the by-name conversion.\n\nIf a class expression contains an init-rest clause, there must be only one, and it must be last. If it declares a variable, then the variable receives extra by-position initialization arguments as a list (similar to a dotted “rest argument” in a procedure). An init-rest variable can receive by-position initialization arguments that are left over from a by-name conversion for a derived class. When a derived class’s superclass initialization provides even more by-position arguments, they are prefixed onto the by-position arguments accumulated so far.\n\nIf too few or too many by-position initialization arguments are provided to an object creation or superclass initialization, then the exn:fail:object exception is raised. Similarly, if extra by-position arguments are provided to a class with an init-rest clause, the exn:fail:object exception is raised.\n\nUnused (by-name) arguments are to be propagated to the superclass, as described in Creating Objects. Multiple initialization arguments can use the same name if the class derivation contains multiple declarations (in different classes) of initialization variables with the name. See Creating Objects for further details.\n\nSee also Internal and External Names for information about internal and external names.\n\n#### 6.2.2 Fields\n\nEach field, init-field, and non-method define-values clause in a class declares one or more new fields for the class. Fields declared with field or init-field are public. Public fields can be accessed and mutated by subclasses using inherit-field. Public fields are also accessible outside the class via class-field-accessor and mutable via class-field-mutator (see Field and Method Access). Fields declared with define-values are accessible only within the class.\n\nA field declared with init-field is both a public field and an initialization variable. See Initialization Variables for information about initialization variables.\n\nAn inherit-field declaration makes a public field defined by a superclass directly accessible in the class expression. If the indicated field is not defined in the superclass, the exn:fail:object exception is raised when the class expression is evaluated. Every field in a superclass is present in a derived class, even if it is not declared with inherit-field in the derived class. The inherit-field clause does not control inheritance, but merely controls lexical scope within a class expression.\n\nWhen an object is first created, all of its fields have the # value (see Void). The fields of a class are initialized at the same time that the class’s initialization expressions are evaluated; see Creating Objects for more information.\n\nSee also Internal and External Names for information about internal and external names.\n\n#### 6.2.3 Methods\n\n##### 6.2.3.1 Method Definitions\n\nEach public, override, augment, pubment, overment, augride, public-final, override-final, augment-final, and private clause in a class declares one or more method names. Each method name must have a corresponding method-definition. The order of public, etc., clauses and their corresponding definitions (among themselves, and with respect to other clauses in the class) does not matter.\n\nAs shown in the grammar for class*, a method definition is syntactically restricted to certain procedure forms, as defined by the grammar for method-procedure; in the last two forms of method-procedure, the body id must be one of the ids bound by let-values or letrec-values. A method-procedure expression is not evaluated directly. Instead, for each method, a class-specific method procedure is created; it takes an initial object argument, in addition to the arguments the procedure would accept if the method-procedure expression were evaluated directly. The body of the procedure is transformed to access methods and fields through the object argument.\n\nA method declared with public, pubment, or public-final introduces a new method into a class. The method must not be present already in the superclass or have an implementation in any superinterface, otherwise the exn:fail:object exception is raised when the class expression is evaluated. A method declared with public can be overridden in a subclass that uses override, overment, or override-final. A method declared with pubment can be augmented in a subclass that uses augment, augride, or augment-final. A method declared with public-final cannot be overridden or augmented in a subclass.\n\nA method declared with override, overment, or override-final overrides a definition already present in the superclass or a superinterface. If the method is not already present, the exn:fail:object exception is raised when the class expression is evaluated. A method declared with override can be overridden again in a subclass that uses override, overment, or override-final. A method declared with overment can be augmented in a subclass that uses augment, augride, or augment-final. A method declared with override-final cannot be overridden further or augmented in a subclass.\n\nA method declared with augment, augride, or augment-final augments a definition already present in the superclass. If the method is not already present, the exn:fail:object exception is raised when the class expression is evaluated. A method declared with augment can be augmented further in a subclass that uses augment, augride, or augment-final. A method declared with augride can be overridden in a subclass that uses override, overment, or override-final. (Such an override merely replaces the augmentation, not the method that is augmented.) A method declared with augment-final cannot be overridden or augmented further in a subclass.\n\nA method declared with private is not accessible outside the class expression, cannot be overridden, and never overrides a method in the superclass.\n\nWhen a method is declared with override, overment, or override-final, then the superclass or superinterface implementation of the method can be called using super form. If multiple superinterfaces provide an implementation of the overridden method, then super raises exn:fail:object when it is evaluated.\n\nWhen a method is declared with pubment, augment, or overment, then a subclass augmenting method can be called using the inner form. The only difference between public-final and pubment without a corresponding inner is that public-final prevents the declaration of augmenting methods that would be ignored.\n\nA method declared with abstract must be declared without an implementation. Subclasses may implement abstract methods via the override, overment, or override-final forms. Any class that contains or inherits any abstract methods is considered abstract and cannot be instantiated.\n\n>
\n\n

syntax

\n\n

(super id arg ...)

(super id arg ... . arg-list-expr)
\n\nAlways accesses the superclass method or a superinterface method, independent of whether the method is overridden again in subclasses. Using the super form outside of class* is a syntax error. Each arg is as for #%app: either arg-expr or keyword arg-expr.\n\nThe second form is analogous to using apply with a procedure; the arg-list-expr must not be a parenthesized expression.\n\n>
\n\n

syntax

\n\n

(inner default-expr id arg ...)

(inner default-expr id arg ... . arg-list-expr)
\n\nIf the object’s class does not supply an augmenting method, then default-expr is evaluated, and the arg expressions are not evaluated. Otherwise, the augmenting method is called with the arg results as arguments, and default-expr is not evaluated. If no inner call is evaluated for a particular method, then augmenting methods supplied by subclasses are never used. Using the inner form outside of class* is an syntax error.\n\nThe second form is analogous to using apply with a procedure; the arg-list-expr must not be a parenthesized expression.\n\n##### 6.2.3.2 Inherited and Superclass Methods\n\nEach inherit, inherit/super, inherit/inner, rename-super, and rename-inner clause declares one or more methods that are defined in the class, but must be present in the superclass. The rename-super and rename-inner declarations are rarely used, since inherit/super and inherit/inner provide the same access. Also, superclass and augmenting methods are typically accessed through super and inner in a class that also declares the methods, instead of through inherit/super, inherit/inner, rename-super, or rename-inner.\n\nMethod names declared with inherit, inherit/super, or inherit/inner access overriding declarations, if any, at run time. Method names declared with inherit/super can also be used with the super form to access the superclass implementation, and method names declared with inherit/inner can also be used with the inner form to access an augmenting method, if any.\n\nMethod names declared with rename-super always access the superclass’s implementation at run-time. Methods declared with rename-inner access a subclass’s augmenting method, if any, and must be called with the form\n\n> (id (lambda () default-expr) arg ...)\n\nso that a default-expr is available to evaluate when no augmenting method is available. In such a form, lambda is a literal identifier to separate the default-expr from the arg. When an augmenting method is available, it receives the results of the arg expressions as arguments.\n\nMethods that are present in the superclass but not declared with inherit, inherit/super, or inherit/inner or rename-super are not directly accessible in the class (though they can be called with send). Every public method in a superclass is present in a derived class, even if it is not declared with inherit in the derived class; the inherit clause does not control inheritance, but merely controls lexical scope within a class expression.\n\nIf a method declared with inherit, inherit/super, inherit/inner, rename-super, or rename-inner is not present in the superclass, the exn:fail:object exception is raised when the class expression is evaluated.\n\n##### 6.2.3.3 Internal and External Names\n\nEach method declared with public, override, augment, pubment, overment, augride, public-final, override-final, augment-final, inherit, inherit/super, inherit/inner, rename-super, and rename-inner can have separate internal and external names when (internal-id external-id) is used for declaring the method. The internal name is used to access the method directly within the class expression (including within super or inner forms), while the external name is used with send and generic (see Field and Method Access). If a single id is provided for a method declaration, the identifier is used for both the internal and external names.\n\nMethod inheritance, overriding, and augmentation are based on external names only. Separate internal and external names are required for rename-super and rename-inner (for historical reasons, mainly).\n\nEach init, init-field, field, or inherit-field variable similarly has an internal and an external name. The internal name is used within the class to access the variable, while the external name is used outside the class when providing initialization arguments (e.g., to instantiate), inheriting a field, or accessing a field externally (e.g., with class-field-accessor). As for methods, when inheriting a field with inherit-field, the external name is matched to an external field name in the superclass, while the internal name is bound in the class expression.\n\nA single identifier can be used as an internal identifier and an external identifier, and it is possible to use the same identifier as internal and external identifiers for different bindings. Furthermore, within a single class, a single name can be used as an external method name, an external field name, and an external initialization argument name. Overall, each internal identifier must be distinct from all other internal identifiers, each external method name must be distinct from all other method names, each external field name must be distinct from all other field names, and each initialization argument name must be distinct from all other initialization argument names.\n\nBy default, external names have no lexical scope, which means, for example, that an external method name matches the same syntactic symbol in all uses of send. The define-local-member-name and define-member-name forms introduce scoped external names.\n\nWhen a class expression is compiled, identifiers used in place of external names must be symbolically distinct (when the corresponding external names are required to be distinct), otherwise a syntax error is reported. When no external name is bound by define-member-name, then the actual external names are guaranteed to be distinct when class expression is evaluated. When any external name is bound by define-member-name, the exn:fail:object exception is raised by class if the actual external names are not distinct.\n\n>
\n\n

syntax

\n\n

(define-local-member-name id ...)

\n\nUnless it appears as the top-level definition, binds each id so that, within the scope of the definition, each use of each id as an external name is resolved to a hidden name generated by the define-local-member-name declaration. Thus, methods, fields, and initialization arguments declared with such external-name ids are accessible only in the scope of the define-local-member-name declaration. As a top-level definition, define-local-member-name binds id to its symbolic form.\n\nThe binding introduced by define-local-member-name is a syntax binding that can be exported and imported with modules. Each evaluation of a define-local-member-name declaration generates a distinct hidden name (except as a top-level definition). The interface → method-names procedure does not expose hidden names.\n\nExamples:\n\n> ```racket\n> ( define-values ( r o ) ( let ( ) ( define-local-member-name m ) ( define c% ( class object% ( define/public ( m ) 10 ) ( super-new ) ) ) ( define o ( new c% ) ) ( values ( send o m ) o ) ) )\n> > r\n> 10\n> > ( send o m )\n> send: no such method\n> method name: m\n> class name: c%\n> ```\n\n>
\n\n

syntax

\n\n

(define-member-name id key-expr)

\n\nMaps a single external name to an external name that is determined by an expression. The value of key-expr must be the result of either a member-name-key expression or a generate-member-key call.\n\n>
\n\n

syntax

\n\n

(member-name-key identifier)

\n\nProduces a representation of the external name for id in the environment of the member-name-key expression.\n\n> ```\n(generate-member-key) → member-name-key?```\n\n\nProduces a hidden name, just like the binding for [define-local-member-name](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define-local-member-name%29%29).\n\n> ```\n(member-name-key? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 6.2 Creating Classes\nReturns #t for values produced by member-name-key and generate-member-key, #f otherwise.\n> ```\n(member-name-key=? a-key b-key) → boolean?\n  a-key : member-name-key?\n  b-key : member-name-key?```\nProduces #t if member-name keys a-key and b-key represent the same external name, #f otherwise.\n> ```\n(member-name-key-hash-code a-key)  →  integer?\n  a-key : member-name-key?\n```\nProduces an integer hash code consistent with member-name-key=? comparisons, analogous to equal-hash-code.\n\nExamples:\n\n> ```racket\n> ( define ( make-c% key ) ( define-member-name m key ) ( class object% ( define/public ( m ) 10 ) ( super-new ) ) )\n> > ( send ( new ( make-c% ( member-name-key m ) ) ) m )\n> 10\n> > ( send ( new ( make-c% ( member-name-key p ) ) ) m )\n> send: no such method\n> method name: m\n> class name: eval:57:0\n> > ( send ( new ( make-c% ( member-name-key p ) ) ) p )\n> 10\n> ( define ( fresh-c% ) ( let ( [ key ( generate-member-key ) ] ) ( values ( make-c% key ) key ) ) ) ( define-values ( fc% key ) ( fresh-c% ) )\n> > ( send ( new fc% ) m )\n> send: no such method\n> method name: m\n> class name: eval:57:0\n> > ( let ( ) ( define-member-name p key ) ( send ( new fc% ) p ) )\n> 10\n> ```\n\n------------------------------------------------------------------------\n\n# 6.3 Creating Objects\n\n### 6.3 Creating Objects\n\nThe make-object procedure creates a new object with by-position initialization arguments, the new form creates a new object with by-name initialization arguments, and the instantiate form creates a new object with both by-position and by-name initialization arguments.\n\nAll fields in the newly created object are initially bound to the special # value (see Void). Initialization variables with default value expressions (and no provided value) are also initialized to #. After argument values are assigned to initialization variables, expressions in field clauses, init-field clauses with no provided argument, init clauses with no provided argument, private field definitions, and other expressions are evaluated. Those expressions are evaluated as they appear in the class expression, from left to right.\n\nSometime during the evaluation of the expressions, superclass-declared initializations must be evaluated once by using the super-make-object procedure, super-new form, or super-instantiate form.\n\nBy-name initialization arguments to a class that have no matching initialization variable are implicitly added as by-name arguments to a super-make-object, super-new, or super-instantiate invocation, after the explicit arguments. If multiple initialization arguments are provided for the same name, the first (if any) is used, and the unused arguments are propagated to the superclass. (Note that converted by-position arguments are always placed before explicit by-name arguments.) The initialization procedure for the object% class accepts zero initialization arguments; if it receives any by-name initialization arguments, then exn:fail:object exception is raised.\n\nIf the end of initialization is reached for any class in the hierarchy without invoking the superclass’s initialization, the exn:fail:object exception is raised. Also, if superclass initialization is invoked more than once, the exn:fail:object exception is raised.\n\nFields inherited from a superclass are not initialized until the superclass’s initialization procedure is invoked. In contrast, all methods are available for an object as soon as the object is created; the overriding of methods is not affected by initialization (unlike objects in C++).\n\n> ```\n(make-object class init-v ...) → object?\n  class : class?\n  init-v : any/c```\n\n\nCreates an instance of class. The init-vs are passed as initialization arguments, bound to the initialization variables of class for the newly created object as described in [Initialization Variables](createclass.html#%28part._clinitvars%29). If class is not a class, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\n>
\n\n

syntax

\n\n

([new](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._new%29%29) class-expr (id by-name-expr) ...)

\n\nCreates an instance of the value of class-expr (which must be a class), and the value of each by-name-expr is provided as a by-name argument for the corresponding id.\n\n>
\n\n

syntax

\n\n

([instantiate](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._instantiate%29%29) class-expr (by-pos-expr ...) (id by-name-expr) ...)

\n\nCreates an instance of the value of class-expr (which must be a class), and the values of the by-pos-exprs are provided as by-position initialization arguments. In addition, the value of each by-name-expr is provided as a by-name argument for the corresponding id.\n\n> ```\n(parameter)\t→\t\n(-> listof (cons/c symbol? any/c))\n```"} {"text": "# 6.2 Creating Classes\nLike (apply make-object cls pos-vs), but named-vs supplies named arguments in addition to the by-position arguments supplied by pos-vs.\nExamples:\n> ```racket\n> > ( define point% ( class object% ( super-new ) ( init-field x y ) ) )\n> > ( define p ( dynamic-instantiate point% ' ( 1 ) ' ( [ y . 2 ] ) ) )\n> > ( get-field x p )\n> 1\n> > ( get-field y p )\n> 2\n> ```\nAdded in version 8.8.0.1 of package base.\n>
\n

syntax

\n

super-make-object

\nProduces a procedure that takes by-position arguments an invokes superclass initialization. See [Creating Objects]() for more information.\n>
\n

syntax

\n

(super-instantiate (by-pos-expr ...) (id by-expr ...) ...)

\nInvokes superclass initialization with the specified by-position and by-name arguments. See [Creating Objects]() for more information.\n>
\n

syntax

\n

(super-new (id by-name-expr ...) ...)

\nInvokes superclass initialization with the specified by-name arguments. See [Creating Objects]() for more information.\n------------------------------------------------------------------------"} {"text": "# 6.4 Field and Method Access"} {"text": "### 6.4 Field and Method Access\nIn expressions within a class definition, the initialization variables, fields, and methods of the class are all part of the environment. Within a method body, only the fields and other methods of the class can be referenced; a reference to any other class-introduced identifier is a syntax error. Elsewhere within the class, all class-introduced identifiers are available, and fields and initialization variables can be mutated with set!."} {"text": "#### 6.4.1 Methods\nMethod names used within a class can only be used in the procedure position of an application expression; any other use is a syntax error.\nTo allow methods to be applied to lists of arguments, a method application can have the following form:\n> > | |\n> > |-------------------------------------|\n> > | (method-id arg ... . arg-list-expr) |\nThis form calls the method in a way analogous to (apply method-id arg ... arg-list-expr). The arg-list-expr must not be a parenthesized expression.\nMethods are called from outside a class with the send, send/apply, and send/keyword-apply forms.\n>
\n

syntax

\n

(send obj-expr method-id arg ...)

(send obj-expr method-id arg ... . arg-list-expr)
\nEvaluates obj-expr to obtain an object, and calls the method with (external) name method-id on the object, providing the arg results as arguments. Each arg is as for #%app: either arg-expr or keyword arg-expr. In the second form, arg-list-expr cannot be a parenthesized expression.\nIf obj-expr does not produce an object, the exn:fail:contract exception is raised. If the object has no public method named method-id, the exn:fail:object exception is raised.\n>
\n

syntax

\n

(send/apply obj-expr method-id arg ... arg-list-expr)

"} {"text": "# 6.4 Field and Method Access\nLike the dotted form of send, but arg-list-expr can be any expression.\n> ```\nsyntax\n(send/keyword-apply obj-expr method-id\n> keyword-list-expr value-list-expr\n> arg ... arg-list-expr )```\nLike [send/apply](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._send%2Fapply%29%29), but with expressions for keyword and argument lists like [keyword-apply](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._keyword-apply%29%29).\n> ```\n(parameter)\t→\n```\nCalls the method on obj whose name matches method-name, passing along all given vs and kw-args.\n\n>
\n\n

syntax

\n\n

(send* obj-expr msg ...+)

 
msg = (method-id arg ...)
  | (method-id arg ... . arg-list-expr)
\n\nCalls multiple methods (in order) of the same object. Each msg corresponds to a use of send.\n\nFor example,\n\n> ```racket\n> ( send* edit ( begin-edit-sequence )\n> ( insert \"Hello\" )\n> ( insert #\\newline )\n> ( end-edit-sequence ) )\n> ```\n\nis the same as\n\n> ```racket\n> ( let ( [ o edit ] )\n> ( send o begin-edit-sequence )\n> ( send o insert \"Hello\" )\n> ( send o insert #\\newline )\n> ( send o end-edit-sequence ) )\n> ```\n\n>
\n\n

syntax

\n\n

(send+ obj-expr msg ...)

 
msg = (method-id arg ...)
  | (method-id arg ... . arg-list-expr)
\n\nCalls methods (in order) starting with the object produced by obj-expr. Each method call will be invoked on the result of the last method call, which is expected to be an object. Each msg corresponds to a use of send.\n\nThis is the functional analogue of send*.\n\nExamples:\n\n> ```racket\n> ( define point% ( class object% ( super-new ) ( init-field [ x 0 ] [ y 0 ] ) ( define/public ( move-x dx ) ( new this% [ x ( + x dx ) ] [ y y ] ) ) ( define/public ( move-y dy ) ( new this% [ y ( + y dy ) ] [ x x ] ) ) ( define/public ( get-pair ) ( cons x y ) ) ) )\n> > ( send+ ( new point% ) ( move-x 5 ) ( move-y 7 ) ( move-x 12 ) ( get-pair ) )\n> '(17 . 7)\n> ```\n\n> ```\nsyntax\n\n(with-method ([id (obj-expr method-id)] ...)\n> body ...+ )```\n\n\nExtracts methods from an object and binds a local name that can be applied directly (in the same way as declared methods within a class) for each method. Each obj-expr must produce an object, which must have a public method named by the corresponding method-id. The corresponding id is bound so that it can be applied directly (see [Methods](#%28part._methodcalls%29)).\n\nExample:\n\n> ```racket\n> ( let ( [ s ( new stack% ) ] )\n> ( with-method ( [ push ( s push! ) ]\n> [ pop ( s pop! ) ] )\n> ( push 10 )\n> ( push 9 )\n> ( pop ) ) )\n> ```\n\nis the same as\n\n> ```racket\n> ( let ( [ s ( new stack% ) ] )\n> ( send s push! 10 )\n> ( send s push! 9 )\n> ( send s pop! ) )\n> ```\n\n#### 6.4.2 Fields\n\n>
\n\n

syntax

\n\n

([get-field](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._get-field%29%29) id obj-expr)

\n\nExtracts the field with (external) name id from the value of obj-expr.\n\nIf obj-expr does not produce an object, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. If the object has no id field, the [exn:fail:object](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._exn~3afail~3aobject%29%29) exception is raised.\n\n> ```\n(parameter)\t→\n```"} {"text": "# 6.4 Field and Method Access\n(external)\t→```\nSets the field from obj with the (external) name that matches field-name to v. If the object has no field matching field-name, the [exn:fail:object](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._exn~3afail~3aobject%29%29) exception is raised.\n>
\n

syntax

\n

([field-bound?](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._field-bound~3f%29%29) id obj-expr)

\nProduces #t if the object result of obj-expr has a field with (external) name id, #f otherwise.\nIf obj-expr does not produce an object, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n>
\n

syntax

\n

([class-field-accessor](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class-field-accessor%29%29) class-expr field-id)

\nReturns an accessor procedure that takes an instance of the class produced by class-expr and returns the value of the object’s field with (external) name field-id."} {"text": "# 6.4 Field and Method Access\nIf class-expr does not produce a class, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. If the class has no field-id field, the [exn:fail:object](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._exn~3afail~3aobject%29%29) exception is raised.\n>
\n

syntax

\n

([class-field-mutator](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class-field-mutator%29%29) class-expr field-id)

\nReturns a mutator procedure that takes an instance of the class produced by class-expr and a value, and sets the value of the object’s field with (external) name field-id to the given value. The result is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13).\nIf class-expr does not produce a class, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. If the class has no field-id field, the [exn:fail:object](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._exn~3afail~3aobject%29%29) exception is raised."} {"text": "#### 6.4.3 Generics\nA generic can be used instead of a method name to avoid the cost of relocating a method by name within a class.\n>
\n

syntax

\n

([generic](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._generic%29%29) class-or-interface-expr id)

\nProduces a generic that works on instances of the class or interface produced by class-or-interface-expr (or an instance of a class/interface derived from class-or-interface) to call the method with (external) name id.\nIf class-or-interface-expr does not produce a class or interface, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. If the resulting class or interface does not contain a method named id, the [exn:fail:object](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._exn~3afail~3aobject%29%29) exception is raised.\n>
\n

syntax

\n

([send-generic](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._send-generic%29%29) obj-expr generic-expr arg ...)

([send-generic](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._send-generic%29%29) obj-expr generic-expr arg ... . arg-list-expr)
"} {"text": "# 6.4 Field and Method Access\nCalls a method of the object produced by obj-expr as indicated by the generic produced by generic-expr. Each arg is as for [#%app](application.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~23~25app%29%29): either arg-expr or keyword arg-expr. The second form is analogous to calling a procedure with [apply](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._apply%29%29), where arg-list-expr is not a parenthesized expression.\nIf obj-expr does not produce an object, or if generic-expr does not produce a generic, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. If the result of obj-expr is not an instance of the class or interface encapsulated by the result of generic-expr, the [exn:fail:object](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._exn~3afail~3aobject%29%29) exception is raised.\n> ```\n(parameter)\t→\t\n(-> or/c class? interface?)"} {"text": "# 6.4 Field and Method Access\n```\nLike the generic form, but as a procedure that accepts a symbolic method name.\n\n------------------------------------------------------------------------\n\n# 6.5 Mixins\n\n### 6.5 Mixins\n\n> ```\nsyntax\n\n(mixin (interface-expr ...) (interface-expr ...)\n> class-clause ... )```\n\n\nProduces a mixin, which is a procedure that encapsulates a class extension, leaving the superclass unspecified. Each time that a mixin is applied to a specific superclass, it produces a new derived class using the encapsulated extension.\n\nThe given class must implement interfaces produced by the first set of interface-exprs. The result of the procedure is a subclass of the given class that implements the interfaces produced by the second set of interface-exprs. The class-clauses are as for [class*](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29), to define the class extension encapsulated by the mixin.\n\nEvaluation of a [mixin](#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._mixin%29%29) form checks that the class-clauses are consistent with both sets of interface-exprs.\n\n------------------------------------------------------------------------\n\n# 6.6 Traits\n\n### 6.6 Traits\n\n| | |\n|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/trait]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/trait]() library, not [racket/base](index.html) or [racket](index.html).\n\nA trait is a collection of methods that can be converted to a [mixin](mixins.html#%28tech._mixin%29) and then applied to a [class](mzlib_class.html#%28tech._clas%29). Before a trait is converted to a mixin, the methods of a trait can be individually renamed, and multiple traits can be merged to form a new trait.\n\n>
\n\n

syntax

\n\n

([trait](#%28form._%28%28lib._racket%2Ftrait..rkt%29._trait%29%29) trait-clause ...)

 
trait-clause = ([public](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public%29%29) maybe-renamed ...)
  | ([pubment](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._pubment%29%29) maybe-renamed ...)
  | ([public-final](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public-final%29%29) maybe-renamed ...)
  | ([override](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override%29%29) maybe-renamed ...)
  | ([overment](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._overment%29%29) maybe-renamed ...)
  | ([override-final](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override-final%29%29) maybe-renamed ...)
  | ([augment](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment%29%29) maybe-renamed ...)
  | ([augride](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augride%29%29) maybe-renamed ...)
  | ([augment-final](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._augment-final%29%29) maybe-renamed ...)
  | ([inherit](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inherit%29%29) maybe-renamed ...)
  | ([inherit/super](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inherit%2Fsuper%29%29) maybe-renamed ...)
  | ([inherit/inner](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inherit%2Finner%29%29) maybe-renamed ...)
  | method-definition
  | ([field](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._field%29%29) field-declaration ...)
  | ([inherit-field](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inherit-field%29%29) maybe-renamed ...)
\n\nCreates a [trait](#%28tech._trait%29). The body of a [trait](#%28form._%28%28lib._racket%2Ftrait..rkt%29._trait%29%29) form is similar to the body of a [class*](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29) form, but restricted to non-private method definitions. In particular, the grammar of maybe-renamed, method-definition, and field-declaration are the same as for [class*](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29), and every method-definition must have a corresponding declaration (one of [public](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public%29%29), [override](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._override%29%29), etc.). As in [class](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%29%29), uses of method names in direct calls, [super](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._super%29%29) calls, and [inner](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inner%29%29) calls depend on bringing method names into scope via [inherit](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inherit%29%29), [inherit/super](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inherit%2Fsuper%29%29), [inherit/inner](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._inherit%2Finner%29%29), and other method declarations in the same trait; an exception, compared to [class](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%29%29) is that [overment](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._overment%29%29) binds a method name only in the corresponding method, and not in other methods of the same trait. Finally, macros such as [public*](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public%2A%29%29) and [define/public](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define%2Fpublic%29%29) work in [trait](#%28form._%28%28lib._racket%2Ftrait..rkt%29._trait%29%29) as in [class](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%29%29).\n\nExternal identifiers in [trait](#%28form._%28%28lib._racket%2Ftrait..rkt%29._trait%29%29), [trait-exclude](#%28form._%28%28lib._racket%2Ftrait..rkt%29._trait-exclude%29%29), [trait-exclude-field](#%28form._%28%28lib._racket%2Ftrait..rkt%29._trait-exclude-field%29%29), [trait-alias](#%28form._%28%28lib._racket%2Ftrait..rkt%29._trait-alias%29%29), [trait-rename](#%28form._%28%28lib._racket%2Ftrait..rkt%29._trait-rename%29%29), and [trait-rename-field](#%28form._%28%28lib._racket%2Ftrait..rkt%29._trait-rename-field%29%29) forms are subject to binding via [define-member-name](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define-member-name%29%29) and [define-local-member-name](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define-local-member-name%29%29). Although [private](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._private%29%29) methods or fields are not allowed in a [trait](#%28form._%28%28lib._racket%2Ftrait..rkt%29._trait%29%29) form, they can be simulated by using a [public](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._public%29%29) or [field](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._field%29%29) declaration and a name whose scope is limited to the [trait](#%28form._%28%28lib._racket%2Ftrait..rkt%29._trait%29%29) form.\n\n> ```\n(trait? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 6.4 Field and Method Access\nReturns #t if v is a trait, #f otherwise.\n> ```\n(trait → mixin tr)  →  (class? . → . class?)\n  tr : trait?\n```\n\n\nConverts a [trait](#%28tech._trait%29) to a [mixin](mixins.html#%28tech._mixin%29), which can be applied to a [class](mzlib_class.html#%28tech._clas%29) to produce a new [class](mzlib_class.html#%28tech._clas%29). An expression of the form\n\n> ```racket\n> ( trait->mixin\n> ( trait\n> trait-clause ... ) )\n> ```\n\nis equivalent to\n\n> ```racket\n> ( lambda ( % )\n> ( class %\n> trait-clause ...\n> ( super-new ) ) )\n> ```\n\nNormally, however, a trait’s methods are changed and combined with other traits before converting to a mixin.\n\n> ```\n(trait-sum tr ...+) → trait?\n  tr : trait?\n```\n(implicit)\t→\t\n(-> i.e., defined with define-local-member-name)```\nProduces a contract for an object, where the object is an instance of a class that conforms to class-contract.\n> ```\n(parameter)\t→\t\n(-> listof symbol?)"} {"text": "# 6.4 Field and Method Access\n```\nProduces a contract for an object, similar to object/c but where the names and contracts for both methods and fields can be computed dynamically. The list of names and contracts for both methods and field respectively must have the same lengths.\n\n>
\n\n

syntax

\n\n

(object-contract member-spec ...)

 
member-spec = (method-id method-contract)
  | (field field-id contract-expr)
     
method-contract = ( →  dom ... range)
  | 
(  →  * ( mandatory-dom ... )\n> ( optional-dom ... )\n> rest\n> range )
  | 
(  →  d ( mandatory-dependent-dom ... )\n> ( optional-dependent-dom ... )\n> dependent-rest\n> pre-cond\n> dep-range )
     
dom = dom-expr
  | keyword dom-expr
     
range = range-expr
  | (values range-expr ...)
  | any
     
mandatory-dom = dom-expr
  | keyword dom-expr
     
optional-dom = dom-expr
  | keyword dom-expr
     
rest = 
  | #:rest rest-expr
     
mandatory-dependent-dom = [id dom-expr]
  | keyword [id dom-expr]
     
optional-dependent-dom = [id dom-expr]
  | keyword [id dom-expr]
     
dependent-rest = 
  | #:rest id rest-expr
     
pre-cond = 
  | #:pre-cond boolean-expr
     
dep-range = any
  | [id range-expr] post-cond
  | (values [id range-expr] ...) post-cond
     
post-cond = 
  | #:post-cond boolean-expr
\n\nProduces a contract for an object.\n\nEach of the contracts for a method has the same semantics as the corresponding function contract, but the syntax of the method contract must be written directly in the body of the object-contract—much like the way that methods in class definitions use the same syntax as regular function definitions, but cannot be arbitrary procedures. Unlike the method contracts for class/c, the implicit this argument is not part of the contract. To allow for the use of this in dependent contracts, → d contracts implicitly bind this to the object itself.\n\n>
\n\n

value

\n\n

mixin-contract : contract?

\n\nA function contract that recognizes mixins. It guarantees that the input to the function is a class and the result of the function is a subclass of the input.\n\n> ```\n(make-mixin-contract type ...) → contract?\n  type : (or/c class? interface?)```\n\n\nProduces a [function contract](function-contracts.html#%28tech._function._contract%29) that guarantees the input to the function is a class that implements/subclasses each type, and that the result of the function is a subclass of the input.\n\n> ```\n(is-a?/c type)  →  flat-contract?\n  type : (or/c class? interface?)\n```"} {"text": "# 6.4 Field and Method Access\nAccepts a class or interface and returns a flat contract that recognizes objects that instantiate the class/interface.\nSee is-a?.\n> ```\n(implementation?/c interface)  →  flat-contract?\n  interface : interface?```\nReturns a flat contract that recognizes classes that implement interface.\nSee [implementation?](objectutils.html#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._implementation~3f%29%29).\n> ```\n(subclass?/c class)  →  flat-contract?\n  class : class?\n```\nReturns a flat contract that recognizes classes that are subclasses of class.\n\nSee subclass?.\n\n------------------------------------------------------------------------\n\n# 6.8 Object Equality and Hashing\n\n### 6.8 Object Equality and Hashing\n\nBy default, objects that are instances of different classes or that are instances of a non-transparent class are equal? only if they are eq?. Like transparent structures, two objects that are instances of the same transparent class (i.e., every superclass of the class has #f as its inspector) are equal? when their field values are equal?.\n\nTo customize the way that a class instance is compared to other instances by equal?, implement the equal<%> interface.\n\n
\n\n

interface

\n\n

equal<%> : interface?

\n\nThe equal<%> interface includes three methods, which are analogous to the functions provided for a structure type with prop:equal+hash:\n\n- equal-to? — Takes two arguments. The first argument is an object that is an instance of the same class (or a subclass that does not re-declare its implementation of equal<%>) and that is being compared to the target object. The second argument is an equal?-like procedure of two arguments that should be used for recursive equality testing. The result should be a true value if the object and the first argument of the method are equal, #f otherwise.\n\n- equal-hash-code-of — Takes one argument, which is a procedure of one argument that should be used for recursive hash-code computation. The result should be an exact integer representing the target object’s hash code.\n\n- equal-secondary-hash-code-of — Takes one argument, which is a procedure of one argument that should be used for recursive hash-code computation. The result should be an exact integer representing the target object’s secondary hash code.\n\nThe equal<%> interface is unusual in that declaring the implementation of the interface is different from inheriting the interface. Two objects can be equal only if they are instances of classes whose most specific ancestor to explicitly implement equal<%> is the same ancestor.\n\nSee prop:equal+hash for more information on equality comparisons and hash codes. The equal<%> interface is implemented with interface* and prop:equal+hash.\n\nExample:\n\n> ```racket\n> #lang racket\n> ;; Case insensitive words:\n> ( define ci-word%\n> ( class* object% ( equal<%> )\n> ;; Initialization\n> ( init-field word )\n> ( super-new )\n> ;; We define equality to ignore case:\n> ( define/public ( equal-to? other recur )\n> ( string-ci=? word ( get-field word other ) ) )\n> ;; The hash codes need to be insensitive to casing as well.\n> ;; We'll just downcase the word and get its hash code.\n> ( define/public ( equal-hash-code-of hash-code )\n> ( hash-code ( string-downcase word ) ) )\n> ( define/public ( equal-secondary-hash-code-of hash-code )\n> ( hash-code ( string-downcase word ) ) ) ) )\n> ;; We can create a hash with a single word:\n> ( define h ( make-hash ) )\n> ( hash-set! h ( new ci-word% [ word \"inconceivable!\" ] ) ' value )\n> ;; Lookup into the hash should be case-insensitive, so that\n> ;; both of these should return 'value.\n> ( hash-ref h ( new ci-word% [ word \"inconceivable!\" ] ) )\n> ( hash-ref h ( new ci-word% [ word \"INCONCEIVABLE!\" ] ) )\n> ;; Comparison fails if we use a non-ci-word%:\n> ( hash-ref h \"inconceivable!\" ' i-dont-think-it-means-what-you-think-it-means )\n> ```\n\n------------------------------------------------------------------------\n\n# 6.9 Object Serialization\n\n### 6.9 Object Serialization\n\n> ```\nsyntax\n\n(define-serializable-class* class-id superclass-expr\n> ( interface-expr ... )\n> class-clause ... )```\n\n\nBinds class-id to a class, where superclass-expr, the interface-exprs, and the class-clauses are as in [class*](createclass.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._class%2A%29%29).\n\nThis form can only be used at the top level, either within a module or outside. The class-id identifier is bound to the new class, and deserialize-info:class-id is also defined; if the definition is within a module, then the latter is provided from a deserialize-info submodule via [module+](module.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._module%2B%29%29).\n\nSerialization for the class works in one of two ways:\n\n- If the class implements the built-in interface [externalizable<%>](#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._externalizable~3c~25~3e%29%29), then an object is serialized by calling its externalize method; the result can be anything that is serializable (but, obviously, should not be the object itself). Deserialization creates an instance of the class with no initialization arguments, and then calls the object’s internalize method with the result of externalize (or, more precisely, a deserialized version of the serialized result of a previous call).\n\n To support this form of serialization, the class must be instantiable with no initialization arguments. Furthermore, cycles involving only instances of the class (and other such classes) cannot be serialized.\n\n- If the class does not implement [externalizable<%>](#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._externalizable~3c~25~3e%29%29), then every superclass of the class must be either serializable or transparent (i.e,. have #f as its inspector). Serialization and deserialization are fully automatic, and may involve cycles of instances.\n\n To support cycles of instances, deserialization may create an instance of the call with all fields as the undefined value, and then mutate the object to set the field values. Serialization support does not otherwise make an object’s fields mutable.\n\nIn the second case, a serializable subclass can implement [externalizable<%>](#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._externalizable~3c~25~3e%29%29), in which case the externalize method is responsible for all serialization (i.e., automatic serialization is lost for instances of the subclass). In the first case, all serializable subclasses implement [externalizable<%>](#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._externalizable~3c~25~3e%29%29), since a subclass implements all of the interfaces of its parent class.\n\nIn either case, if an object is an immediate instance of a subclass (that is not itself serializable), the object is serialized as if it was an immediate instance of the serializable class. In particular, overriding declarations of the externalize method are ignored for instances of non-serializable subclasses.\n\n> ```\nsyntax\n\n(define-serializable-class class-id superclass-expr\n> class-clause ... )\n```"} {"text": "# 6.4 Field and Method Access\nLike define-serializable-class*, but without interface expressions (analogous to class).\n
\n

interface

\n

externalizable<%> : interface?

\nThe externalizable<%> interface includes only the externalize and internalize methods. See define-serializable-class* for more information.\n------------------------------------------------------------------------"} {"text": "# 6.10 Object Printing"} {"text": "### 6.10 Object Printing\nTo customize the way that a class instance is printed by print, write and display, implement the printable<%> interface.\n>
\n

value

\n

printable<%> : interface?

\nThe printable<%> interface includes only the custom-print, custom-write, and custom-display methods. The custom-print method accepts two arguments: the destination port and the current quasiquote depth as an exact nonnegative integer. The custom-write and custom-display methods each accepts a single argument, which is the destination port to write or display the object.\nCalls to the custom-print, custom-write, or custom-display methods are like calls to a procedure attached to a structure type through the prop:custom-write property. In particular, recursive printing can trigger an escape from the call.\nSee prop:custom-write for more information. The printable<%> interface is implemented with interface* and prop:custom-write.\n>
\n

value

\n

writable<%> : interface?

\nLike printable<%>, but includes only the custom-write and custom-display methods. A print request is directed to custom-write.\n------------------------------------------------------------------------"} {"text": "# 6.11 Object, Class, and Interface Utilities"} {"text": "### 6.11 Object, Class, and Interface Utilities\n> ```\n(object? v) → boolean?\n  v : any/c```\nReturns #t if v is an object, #f otherwise.\nExamples:\n> ```racket\n> > ( object? ( new object% ) )\n> #t\n> > ( object? object% )\n> #f\n> > ( object? \"clam chowder\" )\n> #f\n> ```\n> ```\n(class? v)  →  boolean?\n  v : any/c\n```\n\n\nReturns #t if v is a class, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( class? object% )\n> #t\n> > ( class? ( class object% ( super-new ) ) )\n> #t\n> > ( class? ( new object% ) )\n> #f\n> > ( class? \"corn chowder\" )\n> #f\n> ```\n\n> ```\n(interface? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is an interface, #f otherwise.\nExamples:\n> ```racket\n> > ( interface? ( interface ( ) empty cons first rest ) )\n> #t\n> > ( interface? object% )\n> #f\n> > ( interface? \"gazpacho\" )\n> #f\n> ```\n> ```\n(generic? v)  →  boolean?\n  v : any/c"} {"text": "# 6.11 Object, Class, and Interface Utilities\n```\nReturns #t if v is a generic, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( define c% ( class object% ( super-new ) ( define/public ( m x ) ( + 3.14 x ) ) ) )\n> > ( generic? ( generic c% m ) )\n> #t\n> > ( generic? c% )\n> #f\n> > ( generic? \"borscht\" )\n> #f\n> ```\n\n> ```\n(object=? a b) → boolean?\n  a : object?\n  b : object?```\n\n\nDetermines whether a and b were returned from the same call to [new](objcreation.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._new%29%29) or not. If the two objects have fields, this procedure determines whether mutating a field of one would change that field in the other.\n\nThis procedure is similar in spirit to [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) but also works properly with contracts (and has a stronger guarantee).\n\nExamples:\n\n> ```racket\n> > ( define obj-1 ( new object% ) )\n> > ( define obj-2 ( new object% ) )\n> > ( define/contract obj-3 ( object/c ) obj-1 )\n> > ( object=? obj-1 obj-1 )\n> #t\n> > ( object=? obj-1 obj-2 )\n> #f\n> > ( object=? obj-1 obj-3 )\n> #t\n> > ( eq? obj-1 obj-1 )\n> #t\n> > ( eq? obj-1 obj-2 )\n> #f\n> > ( eq? obj-1 obj-3 )\n> #f\n> ```\n\n> ```\n(object-or-false=? a b) → boolean?\n  a : (or/c object? #f)\n  b : (or/c object? #f)\n```\nLike object=?, but accepts #f for either argument and returns #t if both arguments are #f.\nExamples:\n> ```racket\n> > ( object-or-false=? #f ( new object% ) )\n> #f\n> > ( object-or-false=? ( new object% ) #f )\n> #f\n> > ( object-or-false=? #f #f )\n> #t\n> ```\nAdded in version 6.1.1.8 of package base.\n> ```"} {"text": "# 6.11 Object, Class, and Interface Utilities\n(object=-hash-code o) → fixnum?\n  o : object?```\nReturns the hash code for o that corresponds to the equality relation [object=?](#%28def._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._object~3d~3f%29%29).\nAdded in version 7.1.0.6 of package base.\n> ```\n(object → vector object [opaque-v) → vector?\n  object : object?\n  opaque-v : any/c = #f\n```\nReturns a vector representing object that shows its inspectable fields, analogous to struct → vector.\n\nExamples:\n\n> ```racket\n> > ( object → vector ( new object% ) )\n> '#(object:object% ...)\n> > ( object → vector ( new ( class object% ( super-new ) ( field [ x 5 ] [ y 10 ] ) ) ) )\n> '#(object:eval:113:0 ...)\n> ```\n\n> ```\n(class → interface class) → interface?\n  class : class?```\n\n\nReturns the interface implicitly defined by class.\n\nExample:\n\n> ```racket\n> > ( class->interface object% )\n> #\n> ```\n\n> ```\n(object-interface object)  →  interface?\n  object : object?\n```\nReturns the interface implicitly defined by the class of object.\nExample:\n> ```racket\n> > ( object-interface ( new object% ) )\n> #\n> ```\n> ```\n(is-a? v type)  →  boolean?\n  v : any/c\n  type : (or/c interface? class?)"} {"text": "# 6.11 Object, Class, and Interface Utilities\n```\n\n\nReturns #t if v is an instance of a class type or a class that implements an interface type, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( define point<%> ( interface ( ) get-x get-y ) )\n> > ( define 2d-point% ( class* object% ( point<%> ) ( super-new ) ( field [ x 0 ] [ y 0 ] ) ( define/public ( get-x ) x ) ( define/public ( get-y ) y ) ) )\n> > ( is-a? ( new 2d-point% ) 2d-point% )\n> #t\n> > ( is-a? ( new 2d-point% ) point<%> )\n> #t\n> > ( is-a? ( new object% ) 2d-point% )\n> #f\n> > ( is-a? ( new object% ) point<%> )\n> #f\n> ```\n\n> ```\n(subclass? v cls)  →  boolean?\n  v : any/c\n  cls : class?\n```\nReturns #t if v is a class derived from (or equal to) cls, #f otherwise.\nExamples:\n> ```racket\n> > ( subclass? ( class object% ( super-new ) ) object% )\n> #t\n> > ( subclass? object% ( class object% ( super-new ) ) )\n> #f\n> > ( subclass? object% object% )\n> #t\n> ```\n> ```\n(implementation? v intf)  →  boolean?\n  v : any/c\n  intf : interface?\n```\n\n\nReturns #t if v is a class that implements intf, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( define i<%> ( interface ( ) go ) )\n> > ( define c% ( class* object% ( i<%> ) ( super-new ) ( define/public ( go ) ' go ) ) )\n> > ( implementation? c% i<%> )\n> #t\n> > ( implementation? object% i<%> )\n> #f\n> ```\n\n> ```\n(interface-extension? v intf)  →  boolean?\n  v : any/c\n  intf : interface?\n```\n(parameter)\t→```\nReturns #t if intf (or any of its ancestor interfaces) includes a member with the name sym, #f otherwise.\nExamples:"} {"text": "# 6.11 Object, Class, and Interface Utilities\n> ```racket\n> > ( define i<%> ( interface ( ) get-x get-y ) )\n> > ( method-in-interface? ' get-x i<%> )\n> #t\n> > ( method-in-interface? ' get-z i<%> )\n> #f\n> ```\n> ```\n(parameter)\t→\t\n(-> listof symbol?)\n```\n(parameter)\t→\t\n(-> get-x get-y)```\n\n\nReturns #t if object has a method named sym that accepts cnt arguments, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( define c% ( class object% ( super-new ) ( define/public ( m x [ y 0 ] ) ( + x y ) ) ) )\n> > ( object-method-arity-includes? ( new c% ) ' m 1 )\n> #t\n> > ( object-method-arity-includes? ( new c% ) ' m 2 )\n> #t\n> > ( object-method-arity-includes? ( new c% ) ' m 3 )\n> #f\n> > ( object-method-arity-includes? ( new c% ) ' n 1 )\n> #f\n> ```\n\n> ```\n(parameter)\t→\t\n(-> listof symbol?)\n```\nReturns a list of all of the names of the fields bound in object, including fields inherited from superinterfaces, but not including fields whose names are local (i.e., declared with define-local-member-name).\nExamples:\n> ```racket\n> > ( field-names ( new object% ) )\n> '()\n> > ( field-names ( new ( class object% ( super-new ) ( field [ x 0 ] [ y 0 ] ) ) ) )\n> '(x y)\n> ```\n> ```\n(object-info object) → (or/c class? #f) boolean?\n  object : object?```\nReturns two values, analogous to the return values of [struct-info](inspectors.html#%28def._%28%28quote._~23~25kernel%29._struct-info%29%29):\n- class: a class or #f; the result is #f if the current inspector does not control any class for which the object is an instance."} {"text": "# 6.11 Object, Class, and Interface Utilities\n- skipped?: #f if the first result corresponds to the most specific class of object, #t otherwise.\n> ```\n(parameter)\t→\t\n(-> listof symbol?)\n```\n(inclusive)\t→\t\n(-> listof symbol?)```\n\n\nAdds a seal to a given class keyed with the symbol key. The given unsealed-inits, unsealed-fields, and unsealed-methods list corresponding class members that are unaffected by sealing.\n\nWhen a class has any seals, the inst-proc procedure is called on instantiation (normally, this is used to raise an error on instantiation) and the member-proc function is called (again, this is normally used to raise an error) when a subclass attempts to add class members that are not listed in the unsealed lists.\n\nThe inst-proc is called with the class value on which an instantiation was attempted. The member-proc is called with the class value and the list of initialization argument, field, or method names.\n\n> ```\n(parameter)\t→\t\n(-> class? any)\n```\n(parameter)\t→\t\n(-> any)```"} {"text": "# 6.11 Object, Class, and Interface Utilities\nProduces a unit that encapsulates its unit-body-expr-or-defns. Expressions in the [unit](#%28form._%28%28lib._racket%2Funit..rkt%29._unit%29%29) body can refer to identifiers bound by the sig-specs of the [import](#%28form._%28%28lib._racket%2Funit..rkt%29._import%29%29) clause, and the body must include one definition for each identifier of a sig-spec in the [export](#%28form._%28%28lib._racket%2Funit..rkt%29._export%29%29) clause. An identifier that is exported cannot be [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29)ed in either the defining unit or importing units, although the implicit assignment to initialize the variable may be visible as a mutation.\nEach import or export sig-spec ultimately refers to a sig-id, which is an identifier that is bound to a signature by [define-signature](#%28form._%28%28lib._racket%2Funit..rkt%29._define-signature%29%29). The [lexical information](syntax-model.html#%28tech._lexical._information%29) of each identifier imported through a sig-id starts with the lexical information of the sig-id; see [define-signature](#%28form._%28%28lib._racket%2Funit..rkt%29._define-signature%29%29) form more information.\nIn a specific import or export position, the set of identifiers bound or required by a particular sig-id can be adjusted in a few ways:"} {"text": "# 6.11 Object, Class, and Interface Utilities\n- ([prefix](#%28form._%28%28lib._racket%2Funit..rkt%29._prefix%29%29) id sig-spec) as an import binds the same as sig-spec, except that each binding is prefixed with id. As an export, this form causes definitions using the id prefix to satisfy the exports required by sig-spec.\n- ([rename](#%28form._%28%28lib._racket%2Funit..rkt%29._rename%29%29) sig-spec (id id) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) as an import binds the same as sig-spec, except that the first id is used for the binding instead of the second id (where sig-spec by itself must imply a binding that is [bound-identifier=?](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._bound-identifier~3d~3f%29%29) to second id). As an export, this form causes a definition for the first id to satisfy the export named by the second id in sig-spec.\n- ([only](#%28form._%28%28lib._racket%2Funit..rkt%29._only%29%29) sig-spec id [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) as an import binds the same as sig-spec, but restricted to just the listed ids (where sig-spec by itself must imply a binding that is [bound-identifier=?](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._bound-identifier~3d~3f%29%29) to each id). This form is not allowed for an export."} {"text": "# 6.11 Object, Class, and Interface Utilities\n- ([except](#%28form._%28%28lib._racket%2Funit..rkt%29._except%29%29) sig-spec id [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) as an import binds the same as sig-spec, but excluding all listed ids (where sig-spec by itself must imply a binding that is [bound-identifier=?](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._bound-identifier~3d~3f%29%29) to each id). This form is not allowed for an export.\nAs suggested by the grammar, these adjustments to a signature can be nested arbitrarily.\nA unit’s declared imports are matched with actual supplied imports by signature. That is, the order in which imports are supplied to a unit when linking is irrelevant; all that matters is the signature implemented by each supplied import. One actual import must be provided for each declared import. Similarly, when a unit implements multiple signatures, the order of the export signatures does not matter.\nTo support multiple imports or exports for the same signature, an import or export can be tagged using the form ([tag](#%28form._%28%28lib._racket%2Funit..rkt%29._tag%29%29) id sig-spec). When an import declaration of a unit is tagged, then one actual import must be given the same tag (with the same signature) when the unit is linked. Similarly, when an export declaration is tagged for a unit, then references to that particular export must explicitly use the tag."} {"text": "# 6.11 Object, Class, and Interface Utilities\nA unit is prohibited syntactically from importing two signatures that are not distinct, unless they have different tags; two signatures are distinct only if they share no ancestor through [extends](#%28form._%28%28lib._racket%2Funit..rkt%29._extends%29%29). The same syntactic constraint applies to exported signatures. In addition, a unit is prohibited syntactically from importing the same identifier twice (after renaming and other transformations on a sig-spec), exporting the same identifier twice (again, after renaming), or exporting an identifier that is imported.\nWhen units are linked, the bodies of the linked units are executed in an order that is specified at the linking site. An optional ([init-depend](#%28form._%28%28lib._racket%2Funit..rkt%29._init-depend%29%29) tagged-sig-id [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) declaration constrains the allowed orders of linking by specifying that the current unit must be initialized after the unit that supplies the corresponding import. Each tagged-sig-id in an [init-depend](#%28form._%28%28lib._racket%2Funit..rkt%29._init-depend%29%29) declaration must have a corresponding import in the [import](#%28form._%28%28lib._racket%2Funit..rkt%29._import%29%29) clause.\n> ```\nsyntax\n(define-signature sig-id extension-decl\n> ( sig-elem ... ) )\nextension-decl   =  \n    |   extends sig-id\nsig-elem   =   id"} {"text": "# 6.11 Object, Class, and Interface Utilities\n    |   (define-syntaxes (id ...) expr)\n    |   (define-values (id ...) expr)\n    |   (define-values-for-export (id ...) expr)\n    |   (contracted [id contract] ...)\n    |   (open sig-spec)\n    |   (struct id (field ...) struct-option ...)\n    |   (sig-form-id . datum)\nfield   =   id\n    |   [id #:mutable]\nstruct-option   =   #:mutable\n    |   #:constructor-name constructor-id\n    |   #:extra-constructor-name constructor-id\n    |   #:omit-constructor\n    |   #:omit-define-syntaxes\n    |   #:omit-define-values\n```\nBinds an identifier sig-id to a signature that specifies a group of bindings for import or export:\n\n- Each id in a signature declaration means that a unit implementing the signature must supply a variable definition for the id. That is, id is available for use in units importing the signature, and id must be defined by units exporting the signature.\n\n- Each define-syntaxes form in a signature declaration introduces a macro that is available for use in any unit that imports the signature. Free variables in the definition’s expr refer to other identifiers in the signature first, or the context of the define-signature form if the signature does not include the identifier.\n\n- Each define-values form in a signature declaration introduces code that effectively prefixes every unit that imports the signature. Free variables in the definition’s expr are treated the same as for define-syntaxes.\n\n- Each define-values-for-export form in a signature declaration introduces code that effectively suffixes every unit that exports the signature. Free variables in the definition’s expr are treated the same as for define-syntaxes.\n\n- Each contracted form in a signature declaration means that a unit exporting the signature must supply a variable definition for each id in that form. If the signature is imported, then uses of id inside the unit are protected by the appropriate contracts using the unit as the negative blame. If the signature is exported, then the exported values are protected by the appropriate contracts which use the unit as the positive blame, but internal uses of the exported identifiers are not protected. Variables in the contract expressions are treated the same as for define-syntaxes.\n\n- Each (open sig-spec) adds to the signature everything specified by sig-spec.\n\n- Each (struct id (field ...) struct-option ...) adds all of the identifiers that would be bound by the struct form, where the extra option #:omit-constructor omits the constructor identifier.\n\n- Each (sig-form-id . datum) extends the signature in a way that is defined by sig-form-id, which must be bound by define-signature-form. One such binding is for struct/ctc.\n\nWhen a define-signature form includes an extends clause, then the define signature automatically includes everything in the extended signature. Furthermore, any implementation of the new signature can be used as an implementation of the extended signature.\n\nThe lexical information of each id within a signature is compared to the lexical information of sig-id. The extra scopes of id relative to sig-id are recorded for the id. When the sig-id is used as a reference (e.g., in the import clause of unit), a variant of id is created for the referencing context by starting with the lexical information of the referencing sig-id, and then adding the extra scopes for id.\n\n>
\n\n

syntax

\n\n

(open sig-spec)

\n\nAllowed only in a sig-elem; see define-signature.\n\n>
\n\n

syntax

\n\n

(define-values-for-export (id ...) expr)

\n\nAllowed only in a sig-elem; see define-signature.\n\n>
\n\n

syntax

\n\n

(contracted [id contract] ...)

\n\nAllowed only in a sig-elem; see define-signature.\n\n>
\n\n

syntax

\n\n

(only sig-spec id ...)

\n\nAllowed only in a sig-spec; see unit.\n\n>
\n\n

syntax

\n\n

(except sig-spec id ...)

\n\nAllowed only in a sig-spec; see unit.\n\n>
\n\n

syntax

\n\n

(rename sig-spec (id id) ...)

\n\nAllowed only in a sig-spec; see unit.\n\n>
\n\n

syntax

\n\n

(prefix id sig-spec)

\n\nAllowed only in a sig-spec; see unit.\n\n>
\n\n

syntax

\n\n

(import tagged-sig-spec ...)

\n\nAllowed only in certain forms; see, for example, unit.\n\n>
\n\n

syntax

\n\n

(export tagged-sig-spec ...)

\n\nAllowed only in certain forms; see, for example, unit.\n\n>
\n\n

syntax

\n\n

(link linkage-decl ...)

\n\nAllowed only in certain forms; see, for example, compound-unit.\n\n>
\n\n

syntax

\n\n

(tag id sig-spec)

(tag id sig-id)
\n\nAllowed only in certain forms; see, for example, unit.\n\n>
\n\n

syntax

\n\n

(init-depend tagged-sig-id ...)

\n\nAllowed only in a init-depend-decl; see unit.\n\n>
\n\n

syntax

\n\n

extends

\n\nAllowed only within define-signature.\n\n------------------------------------------------------------------------\n\n# 7.2 Invoking Units\n\n### 7.2 Invoking Units\n\n>
\n\n

syntax

\n\n

(invoke-unit unit-expr)

(invoke-unit unit-expr (import tagged-sig-spec ...))
\n\nInvokes the unit produced by unit-expr. For each of the unit’s imports, the invoke-unit expression must contain a tagged-sig-spec in the import clause; see unit for the grammar of tagged-sig-spec. If the unit has no imports, the import clause can be omitted.\n\nWhen no tagged-sig-specs are provided, unit-expr must produce a unit that expects no imports. To invoke the unit, all bindings are first initialized to the # value. Next, the unit’s body definitions and expressions are evaluated in order; in the case of a definition, evaluation sets the value of the corresponding variable(s). Finally, the result of the last expression in the unit is the result of the invoke-unit expression.\n\nEach supplied tagged-sig-spec takes bindings from the surrounding context and turns them into imports for the invoked unit. The unit need not declare an import for every provided tagged-sig-spec, but one tagged-sig-spec must be provided for each declared import of the unit. For each variable identifier in each provided tagged-sig-spec, the value of the identifier’s binding in the surrounding context is used for the corresponding import in the invoked unit.\n\n> ```\nsyntax\n\n(define-values/invoke-unit unit-expr\n> ( import tagged-sig-spec ... )\n> ( export tagged-sig-spec ... )\n> maybe-results-clause )\n \nmaybe-results-clause   =  \n    |   (values result-id ...)\n    |   (values result-id ... . rest-results-id)```\n\n\nLike [invoke-unit](#%28form._%28%28lib._racket%2Funit..rkt%29._invoke-unit%29%29), but the values of the unit’s exports are copied to new bindings.\n\nThe unit produced by unit-expr is linked and invoked as for [invoke-unit](#%28form._%28%28lib._racket%2Funit..rkt%29._invoke-unit%29%29). In addition, the [export](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._export%29%29) clause is treated as a kind of import into the local definition context. That is, for every binding that would be available in a unit that used the [export](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._export%29%29) clause’s tagged-sig-spec as an import, a definition is generated for the context of the [define-values/invoke-unit](#%28form._%28%28lib._racket%2Funit..rkt%29._define-values%2Finvoke-unit%29%29) form.\n\nIf no maybe-results-clause is provided, the unit body may return any number of values, all of which are ignored. Otherwise, the values returned from the unit body are bound to the given result-ids, in order. If no rest-results-id is provided, the body must return exactly as many values as there are result-ids, but if it is provided, the body may return arbitrarily many more, and rest-results-id is bound to a list containing the extra results.\n\nChanged in version 8.8.0.7 of package base: Added maybe-results-clause.\n\n------------------------------------------------------------------------\n\n# 7.3 Linking Units and Creating Compound Units\n\n### 7.3 Linking Units and Creating Compound Units\n\n> ```\nsyntax\n\n(compound-unit\n> ( import link-binding ... )\n> ( export tagged-link-id ... )\n> ( link linkage-decl ... ) )\n \nlink-binding   =   (link-id : tagged-sig-id)\n         \ntagged-link-id   =   (tag id link-id)\n    |   link-id\n         \nlinkage-decl   =   ((link-binding ...) unit-expr tagged-link-id ...)\n```"} {"text": "# 6.11 Object, Class, and Interface Utilities\nLinks several units into one new compound unit without immediately invoking any of the linked units. The unit-exprs in the link clause determine the units to be linked in creating the compound unit. The unit-exprs are evaluated when the compound-unit form is evaluated.\nThe import clause determines the imports of the compound unit. Outside the compound unit, these imports behave as for a plain unit; inside the compound unit, they are propagated to some of the linked units. The export clause determines the exports of the compound unit. Again, outside the compound unit, these exports are treated the same as for a plain unit; inside the compound unit, they are drawn from the exports of the linked units. Finally, the left-hand and right-hand parts of each declaration in the link clause specify how the compound unit’s imports and exports are propagated to the linked units.\nIndividual elements of an imported or exported signature are not available within the compound unit. Instead, imports and exports are connected at the level of whole signatures. Each specific import or export (i.e., an instance of some signature, possibly tagged) is given a link-id name. Specifically, a link-id is bound by the import clause or the left-hand part of a declaration in the link clause. A bound link-id is referenced in the right-hand part of a declaration in the link clause or by the export clause."} {"text": "# 6.11 Object, Class, and Interface Utilities\nThe left-hand side of a link declaration gives names to each expected export of the unit produced by the corresponding unit-expr. The actual unit may export additional signatures, and it may export an extension of a specific signature instead of just the specified one. If the unit does not export one of the specified signatures (with the specified tag, if any), the exn:fail:contract exception is raised when the compound-unit form is evaluated.\nThe right-hand side of a link declaration specifies the imports to be supplied to the unit produced by the corresponding unit-expr. The actual unit may import fewer signatures, and it may import a signature that is extended by the specified one. If the unit imports a signature (with a particular tag) that is not included in the supplied imports, the exn:fail:contract exception is raised when the compound-unit form is evaluated. Each link-id supplied as an import must be bound either in the import clause or in some declaration within the link clause.\nThe order of declarations in the link clause determines the order of invocation of the linked units. When the compound unit is invoked, the unit produced by the first unit-expr is invoked first, then the second, and so on. If the order specified in the link clause is inconsistent with init-depend declarations of the actual units, then the exn:fail:contract exception is raised when the compound-unit form is evaluated.\n------------------------------------------------------------------------"} {"text": "# 7.4 Inferred Linking"} {"text": "### 7.4 Inferred Linking\n> ```\nsyntax\n(define-unit unit-id\n> ( import tagged-sig-spec ... )\n> ( export tagged-sig-spec ... )\n> init-depends-decl\n> unit-body-expr-or-defn\n> ... )```\nBinds unit-id to both a unit and static information about the unit.\nEvaluating a reference to a unit-id bound by [define-unit](#%28form._%28%28lib._racket%2Funit..rkt%29._define-unit%29%29) produces a unit, just like evaluating an id bound by ([define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) id ([unit](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._unit%29%29) [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29))). In addition, however, unit-id can be used in [compound-unit/infer](#%28form._%28%28lib._racket%2Funit..rkt%29._compound-unit%2Finfer%29%29). See [unit](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._unit%29%29) for information on tagged-sig-spec, init-depends-decl, and unit-body-expr-or-defn.\n> ```\nsyntax\n(compound-unit/infer\n> ( import tagged-infer-link-import ... )\n> ( export tagged-infer-link-export ... )\n> ( link infer-linkage-decl ... ) )\ntagged-infer-link-import   =   tagged-sig-id\n    |   (link-id : tagged-sig-id)\ntagged-infer-link-export   =   (tag id infer-link-export)\n    |   infer-link-export\ninfer-link-export   =   link-id\n    |   sig-id\ninfer-linkage-decl   =   ( ( link-binding ... ) unit-id\n> tagged-link-id ... )\n    |   unit-id"} {"text": "# 7.4 Inferred Linking\n```\nLike compound-unit. Syntactically, the difference between compound-unit and compound-unit/infer is that the unit-expr for a linked unit is replaced with a unit-id, where a unit-id is bound by define-unit (or one of the other unit-binding forms that we introduce later in this section). Furthermore, an import can name just a sig-id without locally binding a link-id, and an export can be based on a sig-id instead of a link-id, and a declaration in the link clause can be simply a unit-id with no specified exports or imports.\n\nThe compound-unit/infer form expands to compound-unit by adding sig-ids as needed to the import clause, by replacing sig-ids in the export clause by link-ids, and by completing the declarations of the link clause. This completion is based on static information associated with each unit-id. Links and exports can be inferred when all signatures exported by the linked units are distinct from each other and from all imported signatures, and when all imported signatures are distinct. Two signatures are distinct only if they share no ancestor through extends.\n\nThe long form of a link declaration can be used to resolve ambiguity by giving names to some of a unit’s exports and supplying specific bindings for some of a unit’s imports. The long form need not name all of a unit’s exports or supply all of a unit’s imports if the remaining parts can be inferred.\n\nWhen a unit declares initialization dependencies, compound-unit/infer checks that the link declaration is consistent with those dependencies, and it reports a syntax error if not.\n\nLike compound-unit, the compound-unit/infer form produces a (compound) unit without statically binding information about the result unit’s imports and exports. That is, compound-unit/infer consumes static information, but it does not generate it. Two additional forms, define-compound-unit and define-compound-unit/infer, generate static information (where the former does not consume static information).\n\nChanged in version 6.1.1.8 of package base: Added static checking of the link clause with respect to declared initialization dependencies.\n\n> ```\nsyntax\n\n(define-compound-unit id\n> ( import link-binding ... )\n> ( export tagged-link-id ... )\n> ( link linkage-decl ... ) )```\n\n\nLike [compound-unit](compoundunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._compound-unit%29%29), but binds static information about the compound unit like [define-unit](#%28form._%28%28lib._racket%2Funit..rkt%29._define-unit%29%29), including the propagation of initialization-dependency information (on remaining imports) from the linked units.\n\n> ```\nsyntax\n\n(define-compound-unit/infer id\n> ( import link-binding ... )\n> ( export tagged-infer-link-export ... )\n> ( link infer-linkage-decl ... ) )\n```"} {"text": "# 7.4 Inferred Linking\nLike compound-unit/infer, but binds static information about the compound unit like define-compound-unit.\n> ```\nsyntax\n(define-unit-binding unit-id\n> unit-expr\n> ( import tagged-sig-spec ...+ )\n> ( export tagged-sig-spec ...+ )\n> init-depends-decl )```\nLike [define-unit](#%28form._%28%28lib._racket%2Funit..rkt%29._define-unit%29%29), but the unit implementation is determined from an existing unit produced by unit-expr. The imports and exports of the unit produced by unit-expr must be consistent with the declared imports and exports, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised when the [define-unit-binding](#%28form._%28%28lib._racket%2Funit..rkt%29._define-unit-binding%29%29) form is evaluated.\n>
\n

syntax

"} {"text": "# 7.4 Inferred Linking\n

([invoke-unit/infer](#%28form._%28%28lib._racket%2Funit..rkt%29._invoke-unit%2Finfer%29%29) unit-spec)

 
unit-spec = unit-id
  | ([link](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._link%29%29) link-unit-id ...)
\nLike [invoke-unit](invokingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._invoke-unit%29%29), but uses static information associated with unit-id to infer which imports must be assembled from the current context. If given a link form containing multiple link-unit-ids, then the units are first linked via [define-compound-unit/infer](#%28form._%28%28lib._racket%2Funit..rkt%29._define-compound-unit%2Finfer%29%29)."} {"text": "# 7.4 Inferred Linking\nWhen assembling imports from the current context, the [lexical information](syntax-model.html#%28tech._lexical._information%29) of a unit-id is used for constructing the lexical information of the signatures for the unit’s imports (i.e., the lexical information that would normally be derived from the signature reference). See [define-signature](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._define-signature%29%29) for more information.\n> ```\nsyntax\n(define-values/invoke-unit/infer\n> unit-spec\n> maybe-exports\n> maybe-results-clause )\n( define-values/invoke-unit/infer\n> ( export tagged-sig-spec ... )\n> unit-spec )\nunit-spec   =   unit-id\n    |   (link link-unit-id ...)\nmaybe-exports   =  \n    |   (export tagged-sig-spec ...)\nmaybe-results-clause   =  \n    |   (values result-id ...)\n    |   (values result-id ... . rest-results-id)"} {"text": "# 7.4 Inferred Linking\n```\nLike define-values/invoke-unit, but uses static information associated with unit-id to infer which imports must be assembled from the current context and, if no export clause is present, which exports should be bound by the definition. If given a link form containing multiple link-unit-ids, then the units are first linked via define-compound-unit/infer.\n\nSimilar to invoke-unit/infer, the lexical information of a unit-id is used for constructing the lexical information of the signatures for the unit’s inferred imports and inferred exports (i.e., the lexical information that would normally be derived from a signature reference). See define-signature for more information.\n\nIf maybe-results-clause is provided, the values returned by the unit body are bound in the same way as define-values/invoke-unit.\n\nFor backwards compatibility, an export clause is allowed to appear before unit-spec (in which case no maybe-results-clause may be provided). New programs should provide unit-spec first (which is consistent with define-values/invoke-unit).\n\nChanged in version 8.8.0.7 of package base: Allowed unit-spec to appear before maybe-exports for consistency with define-values/invoke-unit and added maybe-results-clause.\n\n------------------------------------------------------------------------\n\n# 7.5 Generating A Unit from Context\n\n### 7.5 Generating A Unit from Context\n\n>
\n\n

syntax

\n\n

(unit-from-context tagged-sig-spec)

\n\nCreates a unit that implements an interface using bindings in the enclosing environment. The generated unit is essentially the same as\n\n> ```racket\n> ( unit\n> ( import )\n> ( export tagged-sig-spec )\n> ( define id expr ) ... )\n> ```\n\nfor each id that must be defined to satisfy the exports, and each corresponding expr produces the value of id in the environment of the unit-from-context expression. (The unit cannot be written as above, however, since each id definition within the unit shadows the binding outside the unit form.)\n\nSee unit for the grammar of tagged-sig-spec.\n\n>
\n\n

syntax

\n\n

(define-unit-from-context id tagged-sig-spec)

\n\nLike unit-from-context, in that a unit is constructed from the enclosing environment, and like define-unit, in that id is bound to static information to be used later with inference.\n\n------------------------------------------------------------------------\n\n# 7.6 Structural Matching\n\n### 7.6 Structural Matching\n\n> ```\nsyntax\n\n(unit/new-import-export\n> ( import tagged-sig-spec ... )\n> ( export tagged-sig-spec ... )\n> init-depends-decl\n> ( ( tagged-sig-spec ... ) unit-expr tagged-sig-spec ) )```\n\n\nSimilar to [unit](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._unit%29%29), except the body of the unit is determined by an existing unit produced by unit-expr. The result is a unit whose implementation is unit-expr, but whose imports, exports, and initialization dependencies are as in the [unit/new-import-export](#%28form._%28%28lib._racket%2Funit..rkt%29._unit%2Fnew-import-export%29%29) form (instead of as in the unit produced by unit-expr).\n\nThe final clause of the [unit/new-import-export](#%28form._%28%28lib._racket%2Funit..rkt%29._unit%2Fnew-import-export%29%29) form determines the connection between the old and new imports and exports. The connection is similar to the way that [compound-unit](compoundunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._compound-unit%29%29) propagates imports and exports; the difference is that the connection between [import](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._import%29%29) and the right-hand side of the link clause is based on the names of elements in signatures, rather than the names of the signatures. That is, a tagged-sig-spec on the right-hand side of the link clause need not appear as a tagged-sig-spec in the [import](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._import%29%29) clause, but each of the bindings implied by the linking tagged-sig-spec must be implied by some tagged-sig-spec in the [import](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._import%29%29) clause. Similarly, each of the bindings implied by an [export](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._export%29%29) tagged-sig-spec must be implied by some left-hand-side tagged-sig-spec in the linking clause.\n\n> ```\nsyntax\n\n(define-unit/new-import-export unit-id\n> ( import tagged-sig-spec ... )\n> ( export tagged-sig-spec ... )\n> init-depends-decl\n> ( ( tagged-sig-spec ... ) unit-expr tagged-sig-spec ) )\n```"} {"text": "# 7.4 Inferred Linking\nLike unit/new-import-export, but binds static information to unit-id like define-unit.\n> ```\nsyntax\n(unit/s\n> ( import tagged-sig-spec ... )\n> ( export tagged-sig-spec ... )\n> init-depends-decl\n> unit-id )```\nLike [unit/new-import-export](#%28form._%28%28lib._racket%2Funit..rkt%29._unit%2Fnew-import-export%29%29), but the linking clause is inferred, so unit-id must have the appropriate static information.\n> ```\nsyntax\n(define-unit/s name-id\n> ( import tagged-sig-spec ... )\n> ( export tagged-sig-spec ... )\n> init-depends-decl\n> unit-id )\n```\nLike unit/s, but binds static information to name-id like define-unit.\n\n------------------------------------------------------------------------\n\n# 7.7 Extending the Syntax of Signatures\n\n### 7.7 Extending the Syntax of Signatures\n\n>
\n\n

syntax

\n\n

(define-signature-form sig-form-id expr)

(define-signature-form (sig-form-id id) body ...+)
(define-signature-form (sig-form-id id intro-id) body ...+)
\n\nBinds sig-form-id for use within a define-signature form.\n\nIn the first form, the result of expr must be a transformer procedure that accepts one argument. In the second form, sig-form-id is bound to a transformer procedure whose argument is id and whose body is the bodys. The third form is like the second one, but intro-id is bound to a procedure that is analogous to syntax-local-introduce for the signature-form expansion.\n\nThe result of the transformer procedure must be a list of syntax objects, which are substituted for a use of sig-form-id in a define-signature expansion. (The result is a list so that the transformer can produce multiple declarations; define-signature has no splicing begin form.)\n\nChanged in version 8.1.0.7 of package base: Added support for the form with a transformer expr.\n\n>
\n\n

syntax

\n\n

(struct/ctc id ([field contract-expr] ...) struct-option ...)

 
field = id
  | [id #:mutable]
     
struct-option = #:mutable
  | #:omit-constructor
  | #:omit-define-syntaxes
  | #:omit-define-values
\n\nFor use with define-signature. The struct/ctc form works similarly to struct, but the constructor, predicate, field accessors, and field mutators are contracted appropriately.\n\n------------------------------------------------------------------------\n\n# 7.8 Unit Utilities\n\n### 7.8 Unit Utilities\n\n> ```\n(unit? v) → boolean?\n  v : any/c```\n\n\nReturns #t if v is a unit, #f otherwise.\n\n>
\n\n

syntax

\n\n

([provide-signature-elements](#%28form._%28%28lib._racket%2Funit..rkt%29._provide-signature-elements%29%29) sig-spec ...)

\n\nExpands to a [provide](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) of all identifiers implied by the sig-specs. See [unit](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._unit%29%29) for the grammar of sig-spec.\n\n------------------------------------------------------------------------\n\n# 7.9 Unit Contracts\n\n### 7.9 Unit Contracts\n\n> ```\nsyntax\n\n(unit/c\n> ( import sig-spec-block ... )\n> ( export sig-spec-block ... )\n> init-depends-decl\n> optional-body-ctc )\n \nsig-spec-block   =   (tagged-sig-spec [id contract] ...)\n    |   tagged-sig-spec\n         \ninit-depends-decl   =  \n    |   (init-depend tagged-sig-id ...)\n         \noptional-body-ctc   =  \n    |   contract\n    |   (values contract ...)\n```"} {"text": "# 7.4 Inferred Linking\nA unit contract wraps a unit and checks both its imported and exported identifiers to ensure that they match the appropriate contracts. This allows the programmer to add contract checks to a single unit value without adding contracts to the imported and exported signatures.\nThe unit value must import a subset of the import signatures and export a superset of the export signatures listed in the unit contract. Additionally, the unit value must declare initialization dependencies that are a subset of those specified in the unit contract. Any identifier which is not listed for a given signature is left alone. Variables used in a given contract expression first refer to other variables in any of the listed signatures, and then to the context of the unit/c expression. If a body contract is specified then the result of invoking the unit value is wrapped with the given contract, otherwise the values are returned as-is.\nChanged in version 8.8.0.7 of package base: Changed sig-spec-block to allow arbitrary tagged-sig-specs instead of only allowing tagged-sig-ids. Made bindings from all signatures visible in the scope of each contract expression instead of only the bindings from the same signature. Additionally, contracts on signature bindings are enforced within contract expressions.\n> ```\nsyntax\n(define-unit/contract unit-id\n> ( import sig-spec-block ... )\n> ( export sig-spec-block ... )\n> init-depends-decl\n> optional-body-ctc\n> unit-body-expr-or-defn\n> ... )\nsig-spec-block   =   (tagged-sig-spec [id contract] ...)\n    |   tagged-sig-spec"} {"text": "# 7.4 Inferred Linking\noptional-body-ctc   =  \n    |   #:invoke/contract contract\n    |   #:invoke/contract (values contract ...)```\nThe [define-unit/contract](#%28form._%28%28lib._racket%2Funit..rkt%29._define-unit%2Fcontract%29%29) form defines a unit compatible with link inference whose imports and exports are contracted with a unit contract. The unit name is used for the positive blame of the contract.\nChanged in version 8.8.0.7 of package base: Made bindings from all signatures visible in the scope of each contract expression instead of only the bindings from the same signature. Additionally, contracts on signature bindings are enforced within contract expressions.\n------------------------------------------------------------------------"} {"text": "# 7.10 Single-Unit Modules"} {"text": "### 7.10 Single-Unit Modules\nAs a language name with [#lang](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=Module_Syntax.html%23%2528part._hash-lang%2529&version=8.18.0.13), [racket/unit](mzlib_unit.html) provides all bindings of [racket/unit](mzlib_unit.html) and [racket/base](index.html) except for %#module-begin, and the [racket/unit](mzlib_unit.html) module body is treated as a unit body. The body must match the following module-body grammar:\n```\nmodule-body   =   require-decl ...\n(import tagged-sig-expr ...)\n( export tagged-sig-expr ... )\ninit-depends-decl\nunit-body-expr-or-defn\n...\n         \n  require-decl   =   (require require-spec ...)\n    |   (begin require-decl ...)\n    |   derived-require-form```\n\n\nAfter any number of require-decls, the content of the module is the same as a [unit](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._unit%29%29) body with access to [racket/base](index.html).\n\nThe resulting unit is exported as base@, where base is derived from the enclosing module’s name (i.e., its symbolic name, or its path without the directory and file suffix). If the module name ends in -unit, then base corresponds to the module name before -unit. Otherwise, the module name serves as base.\n\n------------------------------------------------------------------------\n\n# 7.11 Single-Signature Modules\n\n### 7.11 Single-Signature Modules\n\n| | |\n|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  [#lang](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=Module_Syntax.html%23%2528part._hash-lang%2529&version=8.18.0.13) [racket/signature]() |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe [racket/signature]() language treats a module body as a unit signature in the same way that [racket/unit](mzlib_unit.html) treats [a module body as unit body](single-unit.html): it provides all bindings of [racket/signature]() and [racket/base](index.html) except for %#module-begin.\n\nThe body must match the following module-body grammar:\n\n| | | | | |\n|--------------:|:----|:---:|:----|:-------------------------------------------------------------------------------------------------------------------------------------------------------------|\n|   module-body |   | = |   | ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) require-spec ...) ... sig-elem ... |\n\nSee [define-signature](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._define-signature%29%29) for the grammar of sig-elem. Unlike the body of a [racket/unit](mzlib_unit.html) module, a [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) in a [racket/signature]() module must be a literal use of [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29).\n\nThe resulting signature is exported as base^, where base is derived from the enclosing module’s name (i.e., its symbolic name, or its path without the directory and file suffix). If the module name ends in -sig, then base corresponds to the module name before -sig. Otherwise, the module name serves as base.\n\nA [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) form as a sig-elem is consistent with the definitions introduced by [define-struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-struct%29%29), as opposed to definitions introduced by [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29). (That behavior was originally a bug, but it is preserved for compatibility.)\n\n------------------------------------------------------------------------\n\n# 7.12 Transformer Helpers\n\n### 7.12 Transformer Helpers\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/unit-exptime]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe [racket/unit-exptime]() library provides procedures that are intended for use by macro transformers. In particular, the library is typically imported using [for-syntax](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-syntax%29%29) into a module that defines macro with [define-syntax](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29).\n\n> ```\n(parameter)\t→\t\n(-> list/c (cons/c (or/c symbol? #f)\n identifier?))\n```"} {"text": "# 7.10 Single-Unit Modules\nIf unit-identifier is bound to static unit information via define-unit (or other such forms), the result is two values. The first value is for the unit’s imports, and the second is for the unit’s exports. Each result value is a list, where each list element pairs a symbol or #f with an identifier. The symbol or #f indicates the import’s or export’s tag (where #f indicates no tag), and the identifier indicates the binding of the corresponding signature.\nIf unit-identifier is not bound to static unit information, then the exn:fail:syntax exception is raised. In that case, the given err-syntax argument is used as the source of the error, where unit-identifier is used as the detail source location.\n> ```\n(signature-members   sig-identifier        \n    err-syntax)   →   (or/c identifier? #f)\n(listof identifier?)\n(listof identifier?)\n(listof identifier?)\n  sig-identifier : identifier?\n  err-syntax : syntax?```\nIf sig-identifier is bound to static unit information via [define-signature](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._define-signature%29%29) (or other such forms), the result is four values:\n- an identifier or #f indicating the signature (of any) that is extended by the sig-identifier binding;\n- a list of identifiers representing the variables supplied/required by the signature;\n- a list of identifiers for variable definitions in the signature (i.e., variable bindings that are provided on import, but not defined by units that implement the signature); and"} {"text": "# 7.10 Single-Unit Modules\n- a list of identifiers with syntax definitions in the signature.\nEach of the result identifiers is given lexical information that is based on sig-identifier, so the names are suitable for reference or binding in the context of sig-identifier. See [define-signature](creatingunits.html#%28form._%28%28lib._racket%2Funit..rkt%29._define-signature%29%29) for more information.\nIf sig-identifier is not bound to a signature, then the [exn:fail:syntax](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3asyntax%29%29) exception is raised. In that case, the given err-syntax argument is used as the source of the error, where sig-identifier is used as the detail source location.\n> ```\n(parameter)\t→\t\n(-> list/c (cons/c (or/c symbol? #f)\n identifier?))"} {"text": "# 7.10 Single-Unit Modules\n```\nIf unit-identifier is bound to static unit information via define-unit (or other such forms), the result is a list of pairs. Each pair combines a tag (or #f for no tag) and a signature name, indicating an initialization dependency of the unit on the specified import (i.e., the same tag and signature are included in the first result from unit-static-signatures).\n\nIf unit-identifier is not bound to static unit information, then the exn:fail:syntax exception is raised. In that case, the given err-syntax argument is used as the source of the error, where unit-identifier is used as the detail source location.\n\nAdded in version 6.1.1.8 of package base.\n\n------------------------------------------------------------------------\n\n# 8 Contracts\n\n## 8 Contracts\n\n> > > \"+\"Contracts in The Racket Guide introduces contracts.\n\nThe contract system guards one part of a program from another. Programmers specify the behavior of a module’s exports via (provide (contract-out ....)) or (require (contract-in ...)), and the contract system enforces those constraints.\n\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/contract]()) |  package: base |\n\nThe bindings documented in this section are provided by the [racket/contract]() and racket libraries, but not racket/base.\n\nContracts come in two forms: those constructed by the various operations listed in this section of the manual, and various ordinary Racket values that double as contracts, including\n\n- symbols, booleans, keywords, and null, which are treated as contracts that recognize themselves, using eq?,\n\n- strings, byte strings, characters, +nan.0, and +nan.f, which are treated as contracts that recognize themselves using equal?,\n\n- numbers (except +nan.0 and +nan.f), which are treated as contracts that recognize themselves using =,\n\n- regular expressions, which are treated as contracts that recognize byte strings and strings that match the regular expression, and\n\n- predicates: any procedure of arity 1 is treated as a predicate. During contract checking, it is applied to the values that appear and should return #f to indicate that the contract failed, and anything else to indicate it passed.\n\nContract combinators are functions such as → and listof that take contracts and produce other contracts.\n\nContracts in Racket are subdivided into three different categories:\n\n- Flat contracts can be fully checked immediately for a given value. These kinds of contracts are essentially predicate functions. Using flat-contract-predicate, you can extract the predicate from an arbitrary flat contract; some flat contracts can be applied like functions, in which case they accept a single argument and return #t or #f to indicate if the given value would be accepted by the contract. All of the flat contracts returned by functions in this library can be used directly as predicates, but ordinary Racket values that double as flat contracts (e.g., numbers or symbols) cannot.\n\nThe function flat-contract? recognizes a flat contract.\n\n- Chaperone contracts may wrap a value in such a way that it signals contract violations later, as the value is used, but are guaranteed to not otherwise change behavior. For example, a function contract wraps a function value and later checks inputs and outputs; any properties that the function value had before being wrapped by the contract are preserved by the contract wrapper.\n\nAll flat contracts may be used where chaperone contracts are expected (but not vice-versa). The function chaperone-contract? recognizes a chaperone contract.\n\n- Impersonator contracts may wrap values and do not provide any guarantees. Impersonator contracts may hide properties of values, or even make them completely opaque (e.g, new-∀/c).\n\nAll contracts may be used where impersonator contracts are expected. The function impersonator-contract? recognizes an impersonator contract.\n\nFor more about this hierarchy, see the section “Impersonators and Chaperones” as well as a research paper \\[Strickland12\\] on chaperones, impersonators, and how they can be used to implement contracts.\n\nChanged in version 6.1.1.8 of package base: Changed +nan.0 and +nan.f to be equal?-based contracts.\n\n| |\n|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n|     8.1 Data-structure Contracts |\n|     8.2 Function Contracts |\n|     8.3 Parametric Contracts |\n|     8.4 Lazy Data-structure Contracts |\n|     8.5 Structure Type Property Contracts |\n|     8.6 Attaching Contracts to Values |\n|       8.6.1 Nested Contract Boundaries |\n|       8.6.2 Low-level Contract Boundaries |\n|     8.7 Building New Contract Combinators |\n|       8.7.1 Blame Objects |\n|       8.7.2 Contracts as structs |\n|       8.7.3 Obligation Information in Check Syntax |\n|       8.7.4 Utilities for Building New Combinators |\n|     8.8 Contract Utilities |\n|     8.9 racket/contract/base |\n|     8.10 Collapsible Contracts |\n|     8.11 Legacy Contracts |\n|     8.12 Random generation |\n\n------------------------------------------------------------------------\n\n# 8.1 Data-structure Contracts\n\n### 8.1 Data-structure Contracts\n\n> ```\n(flat-contract-with-explanation get-explanation\n   [ #:name name)  \n\n  →  flat-contract?\n  get-explanation : ( →  any/c (or/c boolean? ( →  blame? any)))\n  name : any/c = (object-name get-explanation)```\n\n\nProvides a way to use flat contracts that, when a contract fails, provide more information about the failure.\n\nIf get-explanation returns a boolean, then that boolean value is treated as the predicate in a [flat contract](contracts.html#%28tech._flat._contract%29). If it returns a procedure, then it is treated similarly to returning #f, except the result procedure is called to actually signal the contract violation.\n\nThe name argument is used as the name of the contract; it defaults to the name of the get-explanation function.\n\n> ```racket\n> ( flat-contract-with-explanation\n> ( λ ( val )\n> ( cond\n> [ ( even? val ) #t ]\n> [ else\n> ( λ ( blame )\n> ( define more-information ...do-some-complex-computation-here... )\n> ( raise-blame-error blame val\n> ' ( expected: \"an even number\" given: \"~e\"\n> \"and, here is more help: ~s\" )\n> val more-information ) ) ] ) ) )\n> ```\n\n> ```\n(flat-named-contract name\n    flat-contract        \n   [ generator)   →   flat-contract?\n\n  name : any/c\n  flat-contract : flat-contract?\n   generator   :   (or/c #f ( →  exact-nonnegative-integer? ( →  any/c)))\n      =   #f\n```"} {"text": "# 7.10 Single-Unit Modules\nProduces a flat contract like flat-contract, but with the name name.\nFor example,\n> ```racket\n> ( define/contract i\n> ( flat-named-contract\n> ' odd-integer\n> ( lambda ( x ) ( and ( integer? x ) ( odd? x ) ) ) )\n> 2 )\n> ```\nThe generator argument adds a generator for the flat-named-contract. See contract-random-generate for more information.\n>
\n

value

\n

any/c : flat-contract?

\nA flat contract that accepts any value.\nWhen using this contract as the result portion of a function contract, consider using any instead; using any leads to better memory performance, but it also allows multiple results.\n>
\n

value

\n

none/c : flat-contract?

\nA flat contract that accepts no values.\n> ```\n(or/c contract ...) → contract?\n  contract : contract?```\nTakes any number of [contracts](contracts.html#%28tech._contract%29) and returns a [contract](contracts.html#%28tech._contract%29) that accepts any value that any one of the contracts accepts individually."} {"text": "# 7.10 Single-Unit Modules\nThe [or/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) result tests any value by applying the contracts in order, from left to right, with the exception that it always moves the non-[flat contracts](contracts.html#%28tech._flat._contract%29) (if any) to the end, checking them last. Thus, a contract such as ([or/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) ([not/c](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._not%2Fc%29%29) [real?](number-types.html#%28def._%28%28quote._~23~25kernel%29._real~3f%29%29)) [positive?](number-types.html#%28def._%28%28quote._~23~25kernel%29._positive~3f%29%29)) is guaranteed to only invoke the [positive?](number-types.html#%28def._%28%28quote._~23~25kernel%29._positive~3f%29%29) predicate on real numbers.\nIf all of the arguments are procedures or [flat contracts](contracts.html#%28tech._flat._contract%29), the result is a [flat contract](contracts.html#%28tech._flat._contract%29). If only one of the arguments is a higher-order contract, the result is a contract that just checks the flat contracts and, if they don’t pass, applies the higher-order contract."} {"text": "# 7.10 Single-Unit Modules\nIf there are multiple higher-order contracts, [or/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) uses [contract-first-order-passes?](Building_New_Contract_Combinators.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract-first-order-passes~3f%29%29) to distinguish between them. More precisely, when an [or/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) is checked, it first checks all of the [flat contracts](contracts.html#%28tech._flat._contract%29). If none of them pass, it calls [contract-first-order-passes?](Building_New_Contract_Combinators.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract-first-order-passes~3f%29%29) with each of the higher-order contracts. If only one returns true, [or/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) uses that contract. If none of them return true, it signals a contract violation. If more than one returns true, it also signals a contract violation. For example, this contract\n> ```racket\n> ( or/c ( -> number? number? )\n> ( -> string? string? string? ) )\n> ```\ndoes not accept a function like this one: ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) args [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) since it cannot tell which of the two arrow contracts should be used with the function."} {"text": "# 7.10 Single-Unit Modules\nIf all of its arguments are [list-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._list-contract~3f%29%29)s, then [or/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) returns a [list-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._list-contract~3f%29%29).\n> ```\n(first-or/c contract ...) → contract?\n  contract : contract?\n```\nTakes any number of contracts and returns a contract that accepts any value that any one of the contracts accepts individually.\n\nThe first-or/c result tests any value by applying the contracts in order from left to right. Thus, a contract such as (first-or/c (not/c real?) positive?) is guaranteed to only invoke the positive? predicate on real numbers.\n\nIf all of the arguments are procedures or flat contracts, the result is a flat contract and similarly if all of the arguments are chaperone contracts the result is too. Otherwise, the result is an impersonator contract.\n\nIf there are multiple higher-order contracts, first-or/c uses contract-first-order-passes? to distinguish between them. More precisely, when an first-or/c is checked, it checks the first order passes of the first contract against the value. If it succeeds, then it uses only that contract. If it fails, then it moves to the second contract, continuing until it finds one of the contracts where the first order check succeeds. If none of them do, a contract violation is signaled.\n\nFor example, this contract\n\n> ```racket\n> ( first-or/c ( → number? number? )\n> ( → string? string? string? ) )\n> ```\n\naccepts the function (λ args 0), applying the ( → number? number?) contract to the function because it comes first, even though ( → string? string? string?) also applies.\n\nIf all of its arguments are list-contract?s, then first-or/c returns a list-contract?.\n\n> ```\n(and/c contract ...) → contract?\n  contract : contract?```\n\n\nTakes any number of [contracts](contracts.html#%28tech._contract%29) and returns a [contract](contracts.html#%28tech._contract%29) that accepts any value that satisfies all of the contracts simultaneously.\n\nIf all of the arguments are procedures or [flat contracts](contracts.html#%28tech._flat._contract%29), the result is a [flat contract](contracts.html#%28tech._flat._contract%29).\n\nThe contract produced by [and/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) tests any value by applying the contracts in order, from left to right.\n\nThis means that [and/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) can be used to guard predicates that are not total in contracts. For example, this contract is well-behaved, correctly blaming the definition of whoops-not-a-number for not being a number:\n\nExample:\n\n> ```racket\n> > ( define/contract whoops-not-a-number ( and/c real? even? ) \"four\" )\n> whoops-not-a-number: broke its own contract\n> promised: real?\n> produced: \"four\"\n> in: an and/c case of\n> (and/c real? even?)\n> contract from:\n> (definition whoops-not-a-number)\n> blaming: (definition whoops-not-a-number)\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\n\nbut if the arguments to [and/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) are reversed, then the contract itself raises an error:\n\nExample:\n\n> ```racket\n> > ( define/contract whoops-not-a-number ( and/c even? real? ) \"four\" )\n> even?: contract violation\n> expected: integer?\n> given: \"four\"\n> ```\n\nIf more than one of the contracts are not [flat contracts](contracts.html#%28tech._flat._contract%29), then the order in which the higher-order parts of the contract are tested can be counter-intuitive. As an example, consider this function that uses [and/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) in a higher-order manner with contracts that always succeed, but that print when they are called, in order for us to see the order in which they are called.\n\nExamples:\n\n> ```racket\n> > ( define ( ( show-me n ) x ) ( printf \"show-me ~a\\n\" n ) #t )\n> > ( define/contract identity-with-complex-printing-contract ( and/c ( -> ( show-me 4 ) ( show-me 5 ) ) ( -> ( show-me 3 ) ( show-me 6 ) ) ( -> ( show-me 2 ) ( show-me 7 ) ) ( -> ( show-me 1 ) ( show-me 8 ) ) ) ( λ ( x ) x ) )\n> > ( identity-with-complex-printing-contract 101 )\n> show-me 1 show-me 2 show-me 3 show-me 4 show-me 5 show-me 6 show-me 7 show-me 8\n> 101\n> ```\n\nThe checking order is just like the usual ordering when a contract is double-wrapped. The contract that is first put on has its domain checked second but its range checked first and we see a similar pattern here in this example, because [and/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) simply applies the contracts in order.\n\n> ```\n(not/c flat-contract)  →  flat-contract?\n  flat-contract : flat-contract?\n```"} {"text": "# 7.10 Single-Unit Modules\nAccepts a [flat contract](contracts.html#%28tech._flat._contract%29) or a predicate and returns a [flat contract](contracts.html#%28tech._flat._contract%29) that checks the inverse of the argument.\n> ```\n(=/c z)  →  flat-contract?\n  z : real?\n```\n\n\nReturns a [flat contract](contracts.html#%28tech._flat._contract%29) that requires the input to be a number and [=](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._~3d%29%29) to z.\n\n>
\n\n

procedure

\n\n

([

  n : [real?](number-types.html#%28def._%28%28quote._~23~25kernel%29._real~3f%29%29)
\n\nReturns a [flat contract](contracts.html#%28tech._flat._contract%29) that requires the input to be a number and [<](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._~3c%29%29) than n.\n\n> ```\n(>/c n)  →  flat-contract?\n  n : real?\n```\nLike .\n>
\n

procedure

\n

(<=/c n)  →  flat-contract?

  n : real?
\nLike ```\n(>=/c n)  →  flat-contract?\n  n : real?```"} {"text": "# 7.10 Single-Unit Modules\nLike [=](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._~3e~3d%29%29).\n> ```\n(between/c n m)  →  flat-contract?\n  n : real?\n  m : real?\n```\nReturns a flat contract that requires the input to be a real number between n and m or equal to one of them.\n\n> ```\n(real-in n m)  →  flat-contract?\n  n : real?\n  m : real?```\n\n\nAn alias for [between/c](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._between%2Fc%29%29).\n\n> ```\n(integer-in j k)  →  flat-contract?\n  j : (or/c exact-integer? #f)\n  k : (or/c exact-integer? #f)\n```\nReturns a flat contract that requires the input to be an exact integer between j and k, inclusive. If either j or k is #f, then the range is unbounded on that end.\nExamples:"} {"text": "# 7.10 Single-Unit Modules\n> ```racket\n> > ( define/contract two-digit-number ( integer-in 10 99 ) 23 )\n> > ( define/contract not-a-two-digit-number ( integer-in 10 99 ) 124 )\n> not-a-two-digit-number: broke its own contract\n> promised: (integer-in 10 99)\n> produced: 124\n> in: (integer-in 10 99)\n> contract from:\n> (definition not-a-two-digit-number)\n> blaming: (definition not-a-two-digit-number)\n> (assuming the contract is correct)\n> at: eval:3:0\n> > ( define/contract negative-number ( integer-in #f -1 ) -4 )\n> > ( define/contract not-a-negative-number ( integer-in #f -1 ) 4 )\n> not-a-negative-number: broke its own contract\n> promised: (integer-in #f -1)\n> produced: 4\n> in: (integer-in #f -1)\n> contract from:\n> (definition not-a-negative-number)\n> blaming: (definition not-a-negative-number)\n> (assuming the contract is correct)\n> at: eval:5:0\n> ```\nChanged in version 6.8.0.2 of package base: Allow j and k to be #f\n> ```\n(complex/c real imag)  →  flat-contract?\n  real : flat-contract?\n  imag : flat-contract?```\nReturns a [flat contract](contracts.html#%28tech._flat._contract%29) that accepts complex numbers whose real parts match real and whose imaginary parts match imag.\nExamples:"} {"text": "# 7.10 Single-Unit Modules\n> ```racket\n> > ( define/contract can-be-converted-to-exact ( complex/c rational? rational? ) +inf.0 )\n> can-be-converted-to-exact: broke its own contract\n> promised: a complex number with\n> real part: rational?\n> imaginary part: rational?\n> produced: +inf.0\n> in: (complex/c rational? rational?)\n> contract from:\n> (definition can-be-converted-to-exact)\n> blaming: (definition can-be-converted-to-exact)\n> (assuming the contract is correct)\n> at: eval:2:0\n> > ( define/contract complex-integer ( complex/c integer? integer? ) 1+2i )\n> ```\nAdded in version 8.11.1.10 of package base.\n> ```\n(char-in a b)  →  flat-contract?\n  a : char?\n  b : char?"} {"text": "# 7.10 Single-Unit Modules\n```\nReturns a flat contract that requires the input to be a character whose code point number is between the code point numbers of a and b, inclusive.\n\n>
\n\n

value

\n\n

natural-number/c : flat-contract?

\n\nA flat contract that requires the input to be an exact non-negative integer.\n\n> ```\n(string-len/c len) → flat-contract?\n  len : real?```\n\n\nReturns a [flat contract](contracts.html#%28tech._flat._contract%29) that recognizes strings that have fewer than len characters.\n\n>
\n\n

value

\n\n

[false/c](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._false%2Fc%29%29) : [flat-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._flat-contract~3f%29%29)

\n\nAn alias for #f for backwards compatibility.\n\n>
\n\n

value

\n\n

[printable/c](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._printable%2Fc%29%29) : [flat-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._flat-contract~3f%29%29)

\n\nA [flat contract](contracts.html#%28tech._flat._contract%29) that recognizes values that can be written out and read back in with [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29) and [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29).\n\n> ```\n(one-of/c v ...+) → flat-contract?\n  v : any/c\n```"} {"text": "# 7.10 Single-Unit Modules\n(parameter)\t→```\nAccepts any number of symbols and returns a [flat contract](contracts.html#%28tech._flat._contract%29) that recognizes those symbols.\nThis is a backwards compatibility constructor; it merely passes its arguments to [or/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29).\n> ```\n(vectorof c\n   [ #:immutable immutable        \n    #:flat? flat?        \n    #:eager eager)   →   contract?\n  c : contract?\n  immutable : (or/c #t #f 'dont-care) = 'dont-care\n  flat? : boolean? = #f\n  eager : (or/c #t #f exact-nonnegative-integer?) = #t\n```\nReturns a contract that recognizes vectors. The elements of the vector must match c.\n\nIf the flat? argument is #t, then the resulting contract is a flat contract, and the c argument must also be a flat contract. Such flat contracts will be unsound if applied to mutable vectors, as they will not check future operations on the vector.\n\nIf the immutable argument is #t and the c argument is a flat contract and the eager argument is #t, the result will be a flat contract. If the c argument is a chaperone contract, then the result will be a chaperone contract.\n\nIf the eager argument is #t, then immutable vectors are checked eagerly when c is a flat contract. If the eager argument is a number n, then immutable vectors are checked eagerly when c is a flat contract and the length of the vector is less than or equal to n.\n\nWhen a higher-order vectorof contract is applied to a vector, the result is not eq? to the input. The result will be a copy for immutable vectors and a chaperone or impersonator of the input for mutable vectors, unless the c argument is a flat contract and the vector is immutable, in which case the result is the original vector.\n\nChanged in version 6.3.0.5 of package base: Changed flat vector contracts to not copy immutable vectors. \nChanged in version 6.7.0.3: Added the #:eager option.\n\n> ```\n(vector-immutableof c)  →  contract?\n  c : contract?```\n\n\nReturns the same [contract](contracts.html#%28tech._contract%29) as ([vectorof](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fvector..rkt%29._vectorof%29%29) c #:immutable #t). This form exists for backwards compatibility.\n\n> ```\n(vector/c c\n    ...        \n   [ #:immutable immutable        \n    #:flat? flat?)   →   contract?\n\n  c : contract?\n  immutable : (or/c #t #f 'dont-care) = 'dont-care\n  flat? : boolean? = #f\n```"} {"text": "# 7.10 Single-Unit Modules\nReturns a contract that recognizes vectors whose lengths match the number of contracts given. Each element of the vector must match its corresponding contract.\nIf the flat? argument is #t, then the resulting contract is a flat contract, and the c arguments must also be flat contracts. Such flat contracts will be unsound if applied to mutable vectors, as they will not check future operations on the vector.\nIf the immutable argument is #t and the c arguments are flat contracts, the result will be a flat contract. If the c arguments are chaperone contracts, then the result will be a chaperone contract.\nWhen a higher-order vector/c contract is applied to a vector, the result is not eq? to the input. The result will be a copy for immutable vectors and a chaperone or impersonator of the input for mutable vectors.\n> ```\n(vector-immutable/c c ...) → contract?\n  c : contract?```\nReturns the same contract as ([vector/c](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fvector..rkt%29._vector%2Fc%29%29) c [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) #:immutable #t). This form exists for reasons of backwards compatibility.\n> ```\n(box/c in-c\n   [ c        \n    #:immutable immutable        \n    #:flat? flat?)   →   contract?\n  in-c : contract?\n  c : contract? = in-c\n  immutable : (or/c #t #f 'dont-care) = 'dont-care\n  flat? : boolean? = #f"} {"text": "# 7.10 Single-Unit Modules\n```\nReturns a contract that recognizes boxes. The content of the box must match c, and mutations on mutable boxes must match in-c.\n\nIf the flat? argument is #t, then the resulting contract is a flat contract, and the out argument must also be a flat contract. Such flat contracts will be unsound if applied to mutable boxes, as they will not check future operations on the box.\n\nIf the immutable argument is #t and the c argument is a flat contract, the result will be a flat contract. If the c argument is a chaperone contract, then the result will be a chaperone contract.\n\nWhen a higher-order box/c contract is applied to a box, the result is not eq? to the input. The result will be a copy for immutable boxes and either a chaperone or impersonator of the input for mutable boxes.\n\n> ```\n(box-immutable/c c)  →  contract?\n  c : contract?```\n\n\nReturns the same contract as ([box/c](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fbox..rkt%29._box%2Fc%29%29) c #:immutable #t). This form exists for reasons of backwards compatibility.\n\n> ```\n(listof c)  →  list-contract?\n  c : contract?\n```\nReturns a contract that recognizes a list whose every element matches the contract c. Beware that when this contract is applied to a value, the result is not necessarily eq? to the input.\nExamples:"} {"text": "# 7.10 Single-Unit Modules\n> ```racket\n> > ( define/contract some-numbers ( listof number? ) ( list 1 2 3 ) )\n> > ( define/contract just-one-number ( listof number? ) 11 )\n> just-one-number: broke its own contract\n> promised: list?\n> produced: 11\n> in: (listof number?)\n> contract from: (definition just-one-number)\n> blaming: (definition just-one-number)\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\n> ```\n(non-empty-listof c)  →  list-contract?\n  c : contract?```\nReturns a contract that recognizes non-empty lists whose elements match the contract c. Beware that when this contract is applied to a value, the result is not necessarily [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to the input.\nExamples:\n> ```racket\n> > ( define/contract some-numbers ( non-empty-listof number? ) ( list 1 2 3 ) )\n> > ( define/contract not-enough-numbers ( non-empty-listof number? ) ( list ) )\n> not-enough-numbers: broke its own contract\n> promised: (and/c list? pair?)\n> produced: '()\n> in: (non-empty-listof number?)\n> contract from:\n> (definition not-enough-numbers)\n> blaming: (definition not-enough-numbers)\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\n> ```\n(list*of ele-c [last-c) → contract?\n  ele-c : contract?\n  last-c : contract? = ele-c"} {"text": "# 7.10 Single-Unit Modules\n```\nReturns a contract that recognizes improper lists whose elements match the contract ele-c and whose last position matches last-c. If an improper list is created with cons, then its car position is expected to match ele-c and its cdr position is expected to be (list*of ele-c list-c). Otherwise, it is expected to match last-c. Beware that when this contract is applied to a value, the result is not necessarily eq? to the input.\n\nExamples:\n\n> ```racket\n> > ( define/contract improper-numbers ( list*of number? ) ( cons 1 ( cons 2 3 ) ) )\n> > ( define/contract not-improper-numbers ( list*of number? ) ( list 1 2 3 ) )\n> not-improper-numbers: broke its own contract\n> promised: number?\n> produced: '()\n> in: an element of\n> (list*of number?)\n> contract from:\n> (definition not-improper-numbers)\n> blaming: (definition not-improper-numbers)\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\n\nAdded in version 6.1.1.1 of package base. \nChanged in version 6.4.0.4: Added the last-c argument.\n\n> ```\n(cons/c car-c cdr-c)  →  contract?\n  car-c : contract?\n  cdr-c : contract?```\n\n\nProduces a contract that recognizes pairs whose first and second elements match car-c and cdr-c, respectively. Beware that when this contract is applied to a value, the result is not necessarily [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to the input.\n\nIf the cdr-c contract is a [list-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._list-contract~3f%29%29), then [cons/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._cons%2Fc%29%29) returns a [list-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._list-contract~3f%29%29).\n\nExamples:\n\n> ```racket\n> > ( define/contract a-pair-of-numbers ( cons/c number? number? ) ( cons 1 2 ) )\n> > ( define/contract not-a-pair-of-numbers ( cons/c number? number? ) ( cons #f #t ) )\n> not-a-pair-of-numbers: broke its own contract\n> promised: number?\n> produced: #f\n> in: the car of\n> (cons/c number? number?)\n> contract from:\n> (definition not-a-pair-of-numbers)\n> blaming: (definition not-a-pair-of-numbers)\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\n\nChanged in version 6.0.1.13 of package base: Added the [list-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._list-contract~3f%29%29) propagating behavior.\n\n>
\n\n

syntax

\n\n

([cons/dc](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._cons%2Fdc%29%29) [car-id contract-expr] [cdr-id (car-id) contract-expr] cons/dc-option)

([cons/dc](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._cons%2Fdc%29%29) [car-id (cdr-id) contract-expr] [cdr-id contract-expr] cons/dc-option)
 
cons/dc-option = 
  | #:flat
  | #:chaperone
  | #:impersonator
\n\nProduces a contract that recognizes pairs whose first and second elements match the expressions after car-id and cdr-id, respectively.\n\nIn the first case, the contract on the cdr-id portion of the contract may depend on the value in the car-id portion of the pair and in the second case, the reverse is true.\n\nExamples:\n\n> ```racket\n> > ( define/contract an-ordered-pair-of-reals ( cons/dc [ hd real? ] [ tl ( hd ) ( >=/c hd ) ] ) ( cons 1 2 ) )\n> > ( define/contract not-an-ordered-pair-of-reals ( cons/dc [ hd real? ] [ tl ( hd ) ( >=/c hd ) ] ) ( cons 2 1 ) )\n> not-an-ordered-pair-of-reals: broke its own contract\n> promised: (>=/c 2)\n> produced: 1\n> in: the cdr of\n> (cons/dc (hd real?) (tl (hd) (>=/c hd)))\n> contract from:\n> (definition not-an-ordered-pair-of-reals)\n> blaming: (definition not-an-ordered-pair-of-reals)\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\n\nAdded in version 6.1.1.6 of package base.\n\n> ```\n(list/c c ...) → list-contract?\n  c : contract?\n```"} {"text": "# 7.10 Single-Unit Modules\nProduces a contract for a list. The number of elements in the list must match the number of arguments supplied to [list/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._list%2Fc%29%29), and each element of the list must match the corresponding contract. Beware that when this contract is applied to a value, the result is not necessarily [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to the input.\n> ```\n(*list/c prefix suffix ...)  →  list-contract?\n  prefix : contract?\n  suffix : contract?\n```\n\n\nProduces a contract for a list. The number of elements in the list must be at least as long as the number of suffix contracts and the tail of the list must match those contracts, one for each element. The beginning portion of the list can be arbitrarily long, and each element must match prefix.\n\nBeware that when this contract is applied to a value, the result is not necessarily [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to the input.\n\nExamples:\n\n> ```racket\n> > ( define/contract a-list-of-numbers-ending-with-two-integers ( *list/c number? integer? integer? ) ( list 1/2 4/5 0+1i -1 1 322 ) )\n> > ( define/contract not-enough-integers-at-the-end ( *list/c number? integer? integer? integer? ) ( list 1/2 4/5 1/2 321 322 ) )\n> not-enough-integers-at-the-end: broke its own contract\n> promised: integer?\n> produced: 1/2\n> in: the 3rd to the last element of\n> (*list/c number? integer? integer? integer?)\n> contract from:\n> (definition not-enough-integers-at-the-end)\n> blaming: (definition not-enough-integers-at-the-end)\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\n\n> ```\n(treelist/c ctc [#:flat? flat? #:lazy? lazy?) → contract?\n  ctc : contract?\n  flat? : any/c = (flat-contract? ctc)\n  lazy? : any/c = #f\n```"} {"text": "# 7.10 Single-Unit Modules\nProduces a contract for treelists whose elements match ctc.\nIf flat? is a true value then ctc must be a flat contract. In that situation, the result of treelist/c will also be a flat contract.\nIf lazy? is a true value, then ctc must be a chaperone contract and the resulting contract will be a chaperone contract. In that situation, the contracts on the elements of the treelist are not checked until the values are accessed.\nIf both flat? and lazy? are #f, then the contract will copy the treelist as part of the process of checking the contract and the result will be a chaperone contract if ctc is a chaperone contract.\nAt least one of flat? and lazy? must be #f.\nExamples:\n> ```racket\n> > ( define/contract natural-treelist ( treelist/c natural? ) ( treelist 1 2 3 ) )\n> > ( define/contract unnatural-treelist ( treelist/c natural? ) ( treelist -1 -2 -3 ) )\n> unnatural-treelist: broke its own contract\n> promised: natural?\n> produced: -1\n> in: the elements of\n> (treelist/c natural?)\n> contract from:\n> (definition unnatural-treelist)\n> blaming: (definition unnatural-treelist)\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\nAdded in version 8.12.0.7 of package base. \nChanged in version 8.15.0.2: Changed the default value of lazy? from (and (chaperone-contract? ctc) (not (flat-contract? ctc))) to #f.\n> ```\n(mutable-treelist/c ctc)  →  contract?\n  ctc : contract?```\nProduces a contract for [mutable treelists](treelist.html#%28tech._mutable._treelist%29) whose elements match ctc.\nExamples:"} {"text": "# 7.10 Single-Unit Modules\n> ```racket\n> > ( define/contract natural-treelist ( mutable-treelist/c natural? ) ( mutable-treelist 0 1 2 3 ) )\n> > ( mutable-treelist-ref natural-treelist 1 )\n> 1\n> > ( define/contract unnatural-treelist ( mutable-treelist/c natural? ) ( mutable-treelist -1 2 3 ) )\n> > ( mutable-treelist-ref unnatural-treelist 0 )\n> unnatural-treelist: broke its own contract\n> promised: natural?\n> produced: -1\n> in: the elements of\n> (mutable-treelist/c natural?)\n> contract from:\n> (definition unnatural-treelist)\n> blaming: (definition unnatural-treelist)\n> (assuming the contract is correct)\n> at: eval:4:0\n> > ( mutable-treelist-set! unnatural-treelist 2 -3 )\n> unnatural-treelist: contract violation\n> expected: natural?\n> given: -3\n> in: the elements of\n> (mutable-treelist/c natural?)\n> contract from:\n> (definition unnatural-treelist)\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:4:0\n> ```\nAdded in version 8.12.0.11 of package base.\n> ```\n(syntax/c c)  →  flat-contract?\n  c : flat-contract?"} {"text": "# 7.10 Single-Unit Modules\n```\n(val)\t→```\n\n\nProduces a contract on parameters whose values must match out. When the value in the contracted parameter is set, it must match in.\n\nIf impersonator? is a true value, then [parameter/c](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._parameter%2Fc%29%29) always returns an [impersonator contract](contracts.html#%28tech._impersonator._contract%29). If it is #f, then the result will be a [chaperone contract](contracts.html#%28tech._chaperone._contract%29) when both in and out are [chaperone contracts](contracts.html#%28tech._chaperone._contract%29), and an [impersonator contract](contracts.html#%28tech._impersonator._contract%29) otherwise.\n\nExamples:\n\n> ```racket\n> > ( define/contract current-snack ( parameter/c string? ) ( make-parameter \"potato-chip\" ) )\n> > ( define baked/c ( flat-named-contract ' baked/c ( λ ( s ) ( regexp-match #rx\"baked\" s ) ) ) )\n> > ( define/contract current-dinner ( parameter/c string? baked/c ) ( make-parameter \"turkey\" ( λ ( s ) ( string-append \"roasted \" s ) ) ) )\n> > ( current-snack ' not-a-snack )\n> current-snack: contract violation\n> expected: string?\n> given: 'not-a-snack\n> in: the parameter of\n> (parameter/c string?)\n> contract from: (definition current-snack)\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:2:0\n> > ( parameterize ( [ current-dinner \"tofurkey\" ] ) ( current-dinner ) )\n> current-dinner: broke its own contract\n> promised: baked/c\n> produced: \"roasted tofurkey\"\n> in: the parameter of\n> (parameter/c string? baked/c)\n> contract from: (definition current-dinner)\n> blaming: (definition current-dinner)\n> (assuming the contract is correct)\n> at: eval:4:0\n> ```\n\n> ```\n(procedure-arity-includes/c n)  →  flat-contract?\n  n : exact-nonnegative-integer?\n```"} {"text": "# 7.10 Single-Unit Modules\nProduces a contract for procedures that accept n argument (i.e,. the procedure? contract is implied).\n> ```\n(hash/c key\n    val        \n   [ #:immutable immutable        \n    #:flat? flat?)   →   contract?\n  key : chaperone-contract?\n  val : contract?\n  immutable : (or/c #t #f 'dont-care) = 'dont-care\n  flat? : boolean? = #f```\nProduces a contract that recognizes [hash](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash%29%29) tables with keys and values as specified by the key and val arguments.\nExamples:\n> ```racket\n> > ( define/contract good-hash ( hash/c integer? boolean? ) ( hash 1 #t 2 #f 3 #t ) )\n> > ( define/contract bad-hash ( hash/c integer? boolean? ) ( hash 1 \"elephant\" 2 \"monkey\" 3 \"manatee\" ) )\n> bad-hash: broke its own contract\n> promised: boolean?\n> produced: \"elephant\"\n> in: the values of\n> (hash/c integer? boolean?)\n> contract from: (definition bad-hash)\n> blaming: (definition bad-hash)\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\nThere are a number of technicalities that control how [hash/c](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fhash..rkt%29._hash%2Fc%29%29) contracts behave.\n- If the flat? argument is #t, then the resulting contract is a [flat contract](contracts.html#%28tech._flat._contract%29), and the key and val arguments must also be [flat contracts](contracts.html#%28tech._flat._contract%29).\n Examples:"} {"text": "# 7.10 Single-Unit Modules\n > ```racket\n > > ( flat-contract? ( hash/c integer? boolean? ) )\n > #f\n > > ( flat-contract? ( hash/c integer? boolean? #:flat? #t ) )\n > #t\n > > ( hash/c integer? ( -> integer? integer? ) #:flat? #t )\n > hash/c: contract violation\n > expected: flat-contract?\n > given: (-> integer? integer?)\n > ```\n Such [flat contracts](contracts.html#%28tech._flat._contract%29) will be unsound if applied to mutable hash tables, as they will not check future mutations to the hash table.\n Examples:\n > ```racket\n > > ( define original-h ( make-hasheq ) )\n > > ( define/contract ctc-h ( hash/c integer? boolean? #:flat? #t ) original-h )\n > > ( hash-set! original-h 1 \"not a boolean\" )\n > > ( hash-ref ctc-h 1 )\n > \"not a boolean\"\n > ```\n- If the immutable argument is #t and the key and val arguments are [flat-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._flat-contract~3f%29%29)s, the result will be a [flat-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._flat-contract~3f%29%29).\n Example:\n > ```racket\n > > ( flat-contract? ( hash/c integer? boolean? #:immutable #t ) )\n > #t\n > ```"} {"text": "# 7.10 Single-Unit Modules\n If either the domain or the range is a [chaperone-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._chaperone-contract~3f%29%29), then the result will be a [chaperone-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._chaperone-contract~3f%29%29).\n Examples:\n > ```racket\n > > ( flat-contract? ( hash/c ( -> integer? integer? ) boolean? #:immutable #t ) )\n > #f\n > > ( chaperone-contract? ( hash/c ( -> integer? integer? ) boolean? #:immutable #t ) )\n > #t\n > ```\n- \n If the key argument is a [chaperone-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._chaperone-contract~3f%29%29) but not a [flat-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._flat-contract~3f%29%29), then the resulting contract can be applied only to [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29)-based hash tables.\n Example:\n > ```racket\n > > ( define/contract h ( hash/c ( -> integer? integer? ) any/c ) ( make-hasheq ) )\n > h: broke its own contract;\n > promised equal?-based hash table due to higher-order domain\n > contract\n > produced: '#hasheq()\n > in: (hash/c (-> integer? integer?) any/c)\n > contract from: (definition h)\n > blaming: (definition h)\n > (assuming the contract is correct)\n > at: eval:2:0\n > ```"} {"text": "# 7.10 Single-Unit Modules\n Also, when such a [hash/c](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fhash..rkt%29._hash%2Fc%29%29) contract is applied to a hash table, the result is not [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to the input. The result of applying the contract will be a copy for immutable hash tables, and either a [chaperone](chaperones.html#%28tech._chaperone%29) or [impersonator](chaperones.html#%28tech._impersonator%29) of the original hash table for mutable hash tables.\n> ```\nsyntax\n(hash/dc [key-id key-contract-expr] [value-id (key-id) value-contract-expr]\n> hash/dc-option )\nhash/dc-option   =  \n    |   #:immutable immutable?-expr hash/dc-option\n    |   #:kind kind-expr hash/dc-option"} {"text": "# 7.10 Single-Unit Modules\n```\nCreates a contract for hash? tables with keys matching key-contract-expr and where the contract on the values can depend on the key itself, since key-id will be bound to the corresponding key before evaluating the values-contract-expr.\n\nIf immutable?-expr is #t, then only immutable? hashes are accepted. If it is #f then immutable? hashes are always rejected. It defaults to 'dont-care, in which case both mutable and immutable hashes are accepted.\n\nIf kind-expr evaluates to 'flat, then key-contract-expr and value-contract-expr are expected to evaluate to flat-contract?s. If it is 'chaperone, then they are expected to be chaperone-contract?s, and it may also be 'impersonator, in which case they may be any contract?s. The default is 'chaperone.\n\nExamples:\n\n> ```racket\n> > ( define/contract h ( hash/dc [ k real? ] [ v ( k ) ( >=/c k ) ] ) ( hash 1 3 2 4 ) )\n> > ( define/contract h ( hash/dc [ k real? ] [ v ( k ) ( >=/c k ) ] ) ( hash 3 1 4 2 ) )\n> h: broke its own contract\n> promised: (>=/c 3)\n> produced: 1\n> in: the values of\n> (hash/dc (k real?) (v (k) (>=/c k)))\n> contract from: (definition h)\n> blaming: (definition h)\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\n\n> ```\n(channel/c val) → contract?\n  val : contract?```\n\n\nProduces a contract that recognizes [channel](channel.html#%28tech._channel%29)s that communicate values as specified by the val argument.\n\nIf the val argument is a [chaperone contract](contracts.html#%28tech._chaperone._contract%29), then the resulting contract is a [chaperone contract](contracts.html#%28tech._chaperone._contract%29). Otherwise, the resulting contract is an impersonator contract. When a channel contract is applied to a channel, the resulting channel is not [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to the input.\n\nExamples:\n\n> ```racket\n> > ( define/contract chan ( channel/c string? ) ( make-channel ) )\n> > ( thread ( λ ( ) ( channel-get chan ) ) )\n> #\n> > ( channel-put chan ' not-a-string )\n> chan: contract violation\n> expected: string?\n> given: 'not-a-string\n> in: (channel/c string?)\n> contract from: (definition chan)\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\n\n>
\n\n

syntax

\n\n

([prompt-tag/c](#%28form._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._prompt-tag%2Fc%29%29) contract ... maybe-call/cc)

 
maybe-call/cc = 
  | #:call/cc contract
  | #:call/cc ([values](values.html#%28def._%28%28quote._~23~25kernel%29._values%29%29) contract ...)
 
  contract : [contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract~3f%29%29)
\n\nTakes any number of contracts and returns a contract that recognizes continuation prompt tags and will check any aborts or prompt handlers that use the contracted prompt tag.\n\nEach contract will check the corresponding value passed to an [abort-current-continuation](cont.html#%28def._%28%28quote._~23~25kernel%29._abort-current-continuation%29%29) and handled by the handler of a call to [call-with-continuation-prompt](cont.html#%28def._%28%28quote._~23~25kernel%29._call-with-continuation-prompt%29%29).\n\nIf all of the contracts are [chaperone contracts](contracts.html#%28tech._chaperone._contract%29), the resulting contract will also be a [chaperone](chaperones.html#%28tech._chaperone%29) contract. Otherwise, the contract is an [impersonator](chaperones.html#%28tech._impersonator%29) contract.\n\nIf maybe-call/cc is provided, then the provided contracts are used to check the return values from a continuation captured with [call-with-current-continuation](cont.html#%28def._%28%28quote._~23~25kernel%29._call-with-current-continuation%29%29).\n\nExamples:\n\n> ```racket\n> > ( define/contract tag ( prompt-tag/c ( -> number? string? ) ) ( make-continuation-prompt-tag ) )\n> > ( call-with-continuation-prompt ( lambda ( ) ( number->string ( call-with-composable-continuation ( lambda ( k ) ( abort-current-continuation tag k ) ) ) ) ) tag ( lambda ( k ) ( k \"not a number\" ) ) )\n> tag: contract violation\n> expected: number?\n> given: \"not a number\"\n> in: the 1st argument of\n> (prompt-tag/c\n> (-> number? string?)\n> #:call/cc)\n> contract from: (definition tag)\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\n\n> ```\n(continuation-mark-key/c contract)  →  contract?\n  contract : contract?\n```"} {"text": "# 7.10 Single-Unit Modules\n(parameter)\t→\t\n(-> listof symbol?)```\nReturns a contract that recognizes [synchronizable event](sync.html#%28tech._synchronizable._event%29)s whose [synchronization result](sync.html#%28tech._synchronization._result%29)s are checked by the given contracts.\nThe resulting contract is always a [chaperone](chaperones.html#%28tech._chaperone%29) contract and its arguments must all be [chaperone contracts](contracts.html#%28tech._chaperone._contract%29).\nExamples:\n> ```racket\n> > ( define/contract my-evt ( evt/c evt? ) always-evt )\n> > ( define/contract failing-evt ( evt/c number? number? ) ( alarm-evt ( + ( current-inexact-milliseconds ) 50 ) ) )\n> > ( sync my-evt )\n> #\n> > ( sync failing-evt )\n> failing-evt: broke its own contract\n> promised: event that produces 2 values\n> produced: event that produces 1 values\n> in: (evt/c number? number?)\n> contract from: (definition failing-evt)\n> blaming: (definition failing-evt)\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\n>
\n

syntax

\n

([flat-rec-contract](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._flat-rec-contract%29%29) id flat-contract-expr ...)

\nConstructs a recursive [flat contract](contracts.html#%28tech._flat._contract%29). A flat-contract-expr can refer to id to refer recursively to the generated contract.\nFor example, the contract"} {"text": "# 7.10 Single-Unit Modules\n> ```racket\n> ( flat-rec-contract sexp\n> ( cons/c sexp sexp )\n> number?\n> symbol? )\n> ```\nis a [flat contract](contracts.html#%28tech._flat._contract%29) that checks for (a limited form of) S-expressions. It says that a sexp is either two sexps combined with [cons](pairs.html#%28def._%28%28quote._~23~25kernel%29._cons%29%29), or a number, or a symbol.\nNote that if the contract is applied to a circular value, contract checking will not terminate.\n>
\n

syntax

\n

([flat-murec-contract](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._flat-murec-contract%29%29) ([id flat-contract-expr ...] ...) body ...+)

\nA generalization of [flat-rec-contract](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._flat-rec-contract%29%29) for defining several mutually recursive [flat contracts](contracts.html#%28tech._flat._contract%29) simultaneously. Each id is visible in the entire [flat-murec-contract](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._flat-murec-contract%29%29) form, and the result of the final body is the result of the entire form.\n>
\n

syntax

\n

[any](#%28form._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%29%29)

"} {"text": "# 7.10 Single-Unit Modules\nRepresents a contract that is always satisfied. In particular, it can accept multiple values. It can only be used in a result position of contracts like [->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29). Using [any](#%28form._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%29%29) elsewhere is a syntax error.\n> ```\n(promise/c c)  →  contract?\n  c : contract?\n```\n\n\nConstructs a contract on a promise. The contract does not force the promise, but when the promise is forced, the contract checks that the result value meets the contract c.\n\n> ```\n(flat-contract predicate)  →  flat-contract?\n  predicate : ( →  any/c any/c)\n```\nConstructs a [flat contract](contracts.html#%28tech._flat._contract%29) from predicate. A value satisfies the contract if the predicate returns a true value.\nThis function is a holdover from before predicates could be used directly as [flat contracts](contracts.html#%28tech._flat._contract%29). It exists today for backwards compatibility.\n> ```\n(flat-contract-predicate v)  →  ( →  any/c any/c)\n  v : flat-contract?"} {"text": "# 7.10 Single-Unit Modules\n```\nExtracts the predicate from a flat contract.\n\nNote that most flat contracts can be used directly as predicates, but not all. This function can be used to build predicates for ordinary Racket values that double as contracts, such as numbers and symbols. When building a contract combinator that needs to explicitly convert ordinary racket values to flat contracts, consider using coerce-flat-contract instead of flat-contract-predicate so that the combinator can raise errors that use the combinator’s name in the error message.\n\n> ```\n(property/c accessor ctc [#:name name) → flat-contract?\n  accessor : ( →  any/c any/c)\n  ctc : flat-contract?\n  name : any/c = (object-name accessor)```\n\n\nConstructs a [flat contract](contracts.html#%28tech._flat._contract%29) that checks that the first-order property accessed by accessor satisfies ctc. The resulting contract is equivalent to\n\n> ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) (v) (ctc (accessor v)))\n\nexcept that more information is included in error messages produced by violations of the contract. The name argument is used to describe the property being checked in error messages.\n\nExamples:\n\n> ```racket\n> > ( define/contract ( sum-triple lst ) ( -> ( and/c ( listof number? ) ( property/c length ( =/c 3 ) ) ) number? ) ( + ( first lst ) ( second lst ) ( third lst ) ) )\n> > ( sum-triple ' ( 1 2 3 ) )\n> 6\n> > ( sum-triple ' ( 1 2 ) )\n> sum-triple: contract violation\n> expected: (=/c 3)\n> given: 2\n> in: the length of\n> an and/c case of\n> the 1st argument of\n> (->\n> (and/c\n> (listof number?)\n> (property/c length (=/c 3)))\n> number?)\n> contract from: (function sum-triple)\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\n\nAdded in version 7.3.0.11 of package base.\n\n> ```\n(suggest/c c field message)  →  contract?\n  c : contract?\n  field : string?\n  message : string?\n```"} {"text": "# 7.10 Single-Unit Modules\n(mandatory)\t→\t\n(->)```\nLike [->*](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%2A%29%29), except the number of arguments and results can be computed at runtime, instead of being fixed at compile-time. Passing #f as the #:range-contracts argument produces a contract like one where [any](data-structure-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%29%29) is used with [->](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) or [->*](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%2A%29%29).\nFor many uses, [dynamic->*](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._dynamic-~3e%2A%29%29)’s result is slower than [->*](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%2A%29%29) (or [->](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29)), but for some it has comparable speed. The name of the contract returned by [dynamic->*](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._dynamic-~3e%2A%29%29) uses the [->](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) or [->*](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%2A%29%29) syntax.\n>
\n

syntax

\n

([unconstrained-domain->](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._unconstrained-domain-~3e%29%29) range-expr ...)

"} {"text": "# 7.10 Single-Unit Modules\nConstructs a contract that accepts a function, but makes no constraint on the function’s domain. The range-exprs determine the number of results and the contract for each result.\nGenerally, this contract must be combined with another contract to ensure that the domain is actually known to be able to safely call the function itself.\nFor example, the contract\n> ```racket\n> ( provide\n> ( contract-out\n> [ f ( -> d ( [ size natural-number/c ]\n> [ proc ( and/c ( unconstrained-domain-> number? )\n> ( lambda ( p )\n> ( procedure-arity-includes? p size ) ) ) ] )\n> ( )\n> [ _ number? ] ) ] ) )\n> ```\nsays that the function f accepts a natural number and a function. The domain of the function that f accepts must include a case for size arguments, meaning that f can safely supply size arguments to its input.\nFor example, the following is a definition of f that cannot be blamed using the above contract:\n> ```racket\n> ( define ( f i g )\n> ( apply g ( build-list i add1 ) ) )\n> ```\n>
\n

value

\n

[predicate/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._predicate%2Fc%29%29) : [contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract~3f%29%29)

"} {"text": "# 7.10 Single-Unit Modules\nEquivalent to ([->](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29) [boolean?](booleans.html#%28def._%28%28quote._~23~25kernel%29._boolean~3f%29%29)). Previously, this contract was necessary as it included an additional optimization that was not included in [->](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29). Now however, [->](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) performs the same optimization, so the contract should no longer be used. The contract is still provided for backward compatibility.\n>
\n

value

\n

[the-unsupplied-arg](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._the-unsupplied-arg%29%29) : [unsupplied-arg?](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._unsupplied-arg~3f%29%29)

\nUsed by [->i](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3ei%29%29) (and [->d](#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3ed%29%29)) to bind optional arguments that are not supplied by a call site.\n> ```\n(unsupplied-arg? v)  →  boolean?\n  v : any/c"} {"text": "# 7.10 Single-Unit Modules\n```\n(parameter)\t→\t\n(-> x ...)```\n\n\nConstructs a new universal contract.\n\nUniversal contracts accept all values when in negative positions (e.g., function inputs) and wrap them in an opaque struct, hiding the precise value. In positive positions (e.g. function returns), a universal contract accepts only values that were previously accepted in negative positions (by checking for the wrappers).\n\nThe name is used to identify the contract in error messages and defaults to a name based on the lexical context of [new-∀/c](#%28def._%28%28lib._racket%2Fcontract%2Fparametric..rkt%29._new-~e2~88~80%2Fc%29%29).\n\nFor example, this contract:\n\n> ```racket\n> ( let ( [ a ( new-∀/c ' a ) ] )\n> ( -> a a ) )\n> ```\n\ndescribes the identity function (or a non-terminating function). That is, the first use of the a appears in a negative position and thus inputs to that function are wrapped with an opaque struct. Then, when the function returns, it is checked to determine whether the result is wrapped, since the second a appears in a positive position.\n\nThe [new-∀/c](#%28def._%28%28lib._racket%2Fcontract%2Fparametric..rkt%29._new-~e2~88~80%2Fc%29%29) contract constructor is dual to [new-∃/c](#%28def._%28%28lib._racket%2Fcontract%2Fparametric..rkt%29._new-~e2~88~83%2Fc%29%29).\n\n> ```\n(parameter)\t→\t\n(-> or/c symbol? #f)\n```\nConstructs a new existential contract."} {"text": "# 7.10 Single-Unit Modules\nExistential contracts accept all values when in positive positions (e.g., function returns) and wrap them in an opaque struct, hiding the precise value. In negative positions (e.g. function inputs), they accepts only values that were previously accepted in positive positions (by checking for the wrappers).\nThe name is used to identify the contract in error messages and defaults to a name based on the lexical context of new-∀/c.\nFor example, this contract:\n> ```racket\n> ( let ( [ a ( new-∃/c ' a ) ] )\n> ( → ( → a a )\n> any/c ) )\n> ```\ndescribes a function that accepts the identity function (or a non-terminating function) and returns an arbitrary value. That is, the first use of the a appears in a positive position and thus inputs to that function are wrapped with an opaque struct. Then, when the function returns, it is checked to see if the result is wrapped, since the second a appears in a negative position.\nThe new-∃/c construct constructor is dual to new-∀/c.\n------------------------------------------------------------------------"} {"text": "# 8.4 Lazy Data-structure Contracts"} {"text": "### 8.4 Lazy Data-structure Contracts\n>
\n

syntax

\n

(contract-struct id (field-id ...))

\n> NOTE: This library is deprecated; use struct, instead. Lazy struct contracts no longer require a separate struct declaration; instead struct/dc and struct/c work directly with struct and define-struct.\nLike struct, but with two differences: they do not define field mutators, and they define two contract constructors: id/c and id/dc. The first is a procedure that accepts as many arguments as there are fields and returns a contract for struct values whose fields match the arguments. The second is a syntactic form that also produces contracts on the structs, but the contracts on later fields may depend on the values of earlier fields.\nThe generated contract combinators are lazy: they only verify the contract holds for the portion of some data structure that is actually inspected. More precisely, a lazy data structure contract is not checked until a selector extracts a field of a struct.\n> > ```\n(id/dc field-spec ...)\nfield-spec   =   [field-id contract-expr]\n    |   [field-id (field-id ...) contract-expr]```"} {"text": "# 8.4 Lazy Data-structure Contracts\n>\n> In each field-spec case, the first field-id specifies which field the contract applies to; the fields must be specified in the same order as the original [contract-struct](#%28form._%28%28lib._racket%2Fcontract%2Fprivate%2Fds..rkt%29._contract-struct%29%29). The first case is for when the contract on the field does not depend on the value of any other field. The second case is for when the contract on the field does depend on some other fields, and the parenthesized field-ids indicate which fields it depends on; these dependencies can only be to earlier fields.\n>
\n

syntax

\n

([define-contract-struct](#%28form._%28%28lib._racket%2Fcontract%2Fprivate%2Fds..rkt%29._define-contract-struct%29%29) id (field-id ...))

"} {"text": "# 8.4 Lazy Data-structure Contracts\n> NOTE: This library is deprecated; use [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29), instead. Lazy struct contracts no longer require a separate struct declaration; instead [struct/dc](data-structure-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fprivate%2Fstruct-dc..rkt%29._struct%2Fdc%29%29) and [struct/c](data-structure-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fprivate%2Fstruct-dc..rkt%29._struct%2Fc%29%29) work directly with [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) and [define-struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-struct%29%29).\nLike [contract-struct](#%28form._%28%28lib._racket%2Fcontract%2Fprivate%2Fds..rkt%29._contract-struct%29%29), but where the constructor’s name is make-id, much like [define-struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-struct%29%29).\n------------------------------------------------------------------------"} {"text": "# 8.5 Structure Type Property Contracts\n8.18.0.13"} {"text": "### 8.5 Structure Type Property Contracts\n> ```\n(struct-type-property/c value-contract)  →  contract?\n  value-contract : contract?\n```\nProduces a contract for a structure type property. When the contract is applied to a struct type property, it produces a wrapped struct type property that applies value-contract to the value associated with the property when it used to create a new struct type (via struct, make-struct-type, etc).\n\nThe struct type property’s accessor function is not affected; if it is exported, it must be protected separately.\n\nAs an example, consider the following module. It creates a structure type property, prop, whose value should be a function mapping a structure instance to a numeric predicate. The module also exports app-prop, which extracts the predicate from a structure instance and applies it to a given value.\n\n> ```racket\n> > ( module propmod racket ( require racket/contract ) ( define-values ( prop prop? prop-ref ) ( make-struct-type-property ' prop ) ) ( define ( app-prop x v ) ( ( ( prop-ref x ) x ) v ) ) ( provide/contract [ prop? ( → any/c boolean? ) ] [ prop ( struct-type-property/c ( → prop? ( → integer? boolean? ) ) ) ] [ app-prop ( → prop? integer? boolean? ) ] ) ( provide prop-ref ) )\n> ```\n\nThe structmod module creates a structure type named s with a single field; the value of prop is a function that extracts the field value from an instance. Thus the field ought to be an integer predicate, but notice that structmod places no contract on s enforcing that constraint.\n\n> ```racket\n> > ( module structmod racket ( require ' propmod ) ( struct s ( f ) #:property prop ( lambda ( s ) ( s-f s ) ) ) ( provide ( struct-out s ) ) )\n> > ( require ' propmod ' structmod )\n> ```\n\nFirst we create an s instance with an integer predicate, so the constraint on prop is in fact satisfied. The first call to app-prop is correct; the second simply violates the contract of app-prop.\n\n> ```racket\n> > ( define s1 ( s even? ) )\n> > ( app-prop s1 5 )\n> #f\n> > ( app-prop s1 ' apple )\n> app-prop: contract violation\n> expected: integer?\n> given: 'apple\n> in: the 2nd argument of\n> ( → prop? integer? boolean?)\n> contract from: propmod\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\n\nWe are able to create s instances with values other than integer predicates, but applying app-prop on them blames structmod, because the function associated with prop—that is, (lambda (s) (s-f s))—does not always produce a value satisfying ( → integer? boolean?).\n\n> ```racket\n> > ( define s2 ( s \"not a fun\" ) )\n> > ( app-prop s2 5 )\n> prop: contract violation\n> expected: a procedure\n> given: \"not a fun\"\n> in: the range of\n> the struct property value of\n> (struct-type-property/c\n> ( → prop? ( → integer? boolean?)))\n> contract from: propmod\n> blaming: structmod\n> (assuming the contract is correct)\n> at: eval:2:0\n> > ( define s3 ( s list ) )\n> > ( app-prop s3 5 )\n> prop: contract violation\n> expected: boolean?\n> given: '(5)\n> in: the range of\n> the range of\n> the struct property value of\n> (struct-type-property/c\n> ( → prop? ( → integer? boolean?)))\n> contract from: propmod\n> blaming: structmod\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\n\nThe fix would be to propagate the obligation inherited from prop to s:\n\n> ```racket\n> ( provide ( contract-out\n> [ struct s ( [ f ( → integer? boolean? ) ] ) ] ) )\n> ```\n\nFinally, if we directly apply the property accessor, prop-ref, and then misuse the resulting function, the propmod module is blamed:\n\n> ```racket\n> > ( ( prop-ref s3 ) ' apple )\n> prop: broke its own contract\n> promised: prop?\n> produced: 'apple\n> in: the 1st argument of\n> the struct property value of\n> (struct-type-property/c\n> ( → prop? ( → integer? boolean?)))\n> contract from: propmod\n> blaming: propmod\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\n\nThe propmod module has an obligation to ensure a function associated with prop is applied only to values satisfying prop?. By directly providing prop-ref, it enables that constraint to be violated (and thus it is blamed), even though the bad application actually occurs elsewhere.\n\nGenerally there is no need to provide a structure type property accessor at all; it is typically only used by other functions within the module. But if it must be provided, it should be protected thus:\n\n> ```racket\n> ( provide ( contract-out\n> [ prop-ref ( → prop? ( → prop? ( → integer? boolean? ) ) ) ] ) )\n> ```\n\n------------------------------------------------------------------------\n\n# 8.6 Attaching Contracts to Values\n\n### 8.6 Attaching Contracts to Values\n\n>
\n\n

syntax

\n\n

(contract-in module-path in-out-item ...)

\n\n

syntax

\n\n

(contract-out unprotected-submodule in-out-item ...)

 
in-out-item = [id contract-expr]
  | (rename internal-id external-id contract-expr)
  | 
( struct id/ignored ( [ id contract-expr ] ... )\n> struct-option )
  | #:∃ poly-variables
  | #:exists poly-variables
  | #:∀ poly-variables
  | #:forall poly-variables
     
unprotected-submodule = 
  | #:unprotected-submodule submodule-name
     
poly-variables = id
  | (id ...)
     
id/ignored = id
  | (id ignored-id)
     
struct-option = 
  | #:omit-constructor
\n\nUse contract-in in require and contract-out in provide (currently only for the same phase level as the provide form; for example, contract-out cannot be nested within for-syntax). Each identifier in contract-out is provided from the enclosing module and each one in contract-in is required from the named module. In addition, uses of the identifies must live up to the contract specified by contract-expr for each export.\n\nThe contract-out and contract-in forms treat modules as units of blame. The module that provides each identifier is expected to meet the positive (co-variant) positions of the contract. Each module that imports the provided variable must obey the negative (contra-variant) positions of the contract. Only uses of the contracted variable outside the module that provides them are checked. Inside the providing module, no contract checking occurs.\n\nIn a contract-out form, each contract-expr in a contract-out form is effectively moved to the end of the enclosing module, so a contract-expr can refer to variables that are defined later in the same module.\n\nThe rename form exports the first variable (the internal name) with the name specified by the second variable (the external name).\n\nThe struct form gives contracts to a structure-type definition id, and each field has a contract that dictates the contents of the fields. Unlike a struct definition, however, all of the fields (and their contracts) must be listed. The contract on the fields that the sub-struct shares with its parent are only used in the contract for the sub-struct’s constructor, and the selector or mutators for the super-struct are not provided. The exported structure-type name always doubles as a constructor, even if the original structure-type name does not act as a constructor. If the #:omit-constructor option is present, the constructor is not provided. The second form of id/ignored, which has both id and ignored-id, is deprecated and allowed in the grammar only for backward compatibility, where ignored-id is ignored. The first form should be used instead.\n\nNote that if the struct is created with serializable-struct or define-serializable-struct, contract-out does not protect struct instances that are created via deserialize. Consider using struct-guard/c instead.\n\nThe #:∃, #:exists, #:∀, and #:forall clauses define new abstract contracts. The variables are bound in the remainder of the contract-out form to new contracts that hide the values they accept and ensure that the exported functions are treated parametrically. See new-∃/c and new-∀/c for details on how the clauses hide the values.\n\nIf #:unprotected-submodule appears, the identifier that follows it is used as the name of a submodule that contract-out generates. The submodule exports all of the names in the contract-out, but without contracts. In particular, the original structure-type name is exported for each struct form, which means #:omit-constructor only omits the extra constructor, if any.\n\nThe implementation of contract-out uses syntax-property to attach properties to the code it generates that records the syntax of the contracts in the fully expanded program. Specifically, the symbol 'provide/contract-original-contract is bound to vectors of two elements, the exported identifier and a syntax object for the expression that produces the contract controlling the export.\n\nExamples:\n\n> ```racket\n> > ( module math-example racket/base ( require racket/contract ) ; Compute the reciprocal of a real number ( define ( recip x ) ( / 1 x ) ) ( provide ( contract-out [ recip ( → ( and/c real? ( not/c zero? ) ) real? ) ] ) ) )\n> > ( require ' math-example )\n> > ( recip 3 )\n> 1/3\n> > ( recip 1+2i )\n> recip: contract violation\n> expected: real?\n> given: 1+2i\n> in: an and/c case of\n> the 1st argument of\n> ( → (and/c real? (not/c zero?)) real?)\n> contract from: math-example\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\n\nChanged in version 7.3.0.3 of package base: Added #:unprotected-submodule. \nChanged in version 7.7.0.9: Started ignoring ignored-id. \nChanged in version 8.12.0.13: Added contract-in \nChanged in version 8.13.0.1: Added rename and struct to contract-in\n\n>
\n\n

syntax

\n\n

(recontract-out id ...)

\n\nA provide-spec for use in provide (currently, just like contract-out, only for the same phase level as the provide form).\n\nIt re-exports id, but with positive blame associated to the module containing recontract-out instead of the location of the original site of id.\n\nThis can be useful when a public module wants to export an identifier from a private module but where any contract violations should be reported in terms of the public module instead of the private one.\n\nExamples:\n\n> ```racket\n> > ( module private-implementation racket/base ( require racket/contract ) ( define ( recip x ) ( / 1 x ) ) ( define ( non-zero? x ) ( not ( = x 0 ) ) ) ( provide/contract [ recip ( → ( and/c real? non-zero? ) ( between/c -1 1 ) ) ] ) )\n> > ( module public racket/base ( require racket/contract ' private-implementation ) ( provide ( recontract-out recip ) ) )\n> > ( require ' public )\n> > ( recip +nan.0 )\n> recip: broke its own contract\n> promised: (between/c -1 1)\n> produced: +nan.0\n> in: the range of\n> ( → \n> (and/c real? non-zero?)\n> (between/c -1 1))\n> contract from: public\n> blaming: public\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\n\nReplacing the use of recontract-out with just recip would result in a contract violation blaming the private module.\n\n>
\n\n

syntax

\n\n

(provide/contract unprotected-submodule in-out-item ...)

\n\nA legacy shorthand for (provide (contract-out unprotected-submodule in-out-item ...)), except that a contract-expr within provide/contract is evaluated at the position of the provide/contract form instead of at the end of the enclosing module.\n\n>
\n\n

syntax

\n\n

(struct-guard/c contract-expr ...)

\n\nReturns a procedure suitable to be passed as the #:guard argument to struct, serializable-struct (and related forms). The guard procedure ensures that each contract protects the corresponding field values, as long as the struct is not mutated. Mutations are not protected.\n\nExamples:\n\n> ```racket\n> > ( struct snake ( weight hungry? ) #:guard ( struct-guard/c real? boolean? ) )\n> > ( snake 1.5 \"yep\" )\n> snake, field 2: contract violation\n> expected: boolean?\n> given: \"yep\"\n> in: boolean?\n> contract from: top-level\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\n\n#### 8.6.1 Nested Contract Boundaries\n\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require racket/contract/region) |  package: base |\n\n>
\n\n

syntax

\n\n

(with-contract blame-id (wc-export ...) free-var-list ... body ...+)

(with-contract blame-id results-spec free-var-list ... body ...+)
 
wc-export = (id contract-expr)
     
result-spec = #:result contract-expr
  | #:results (contract-expr ...)
     
free-var-list = 
  | #:freevar id contract-expr
  | #:freevars ([id contract-expr] ...)
\n\nGenerates a local contract boundary.\n\nThe first with-contract form cannot appear in expression position. All names defined within the first with-contract form are visible externally, but those names listed in the wc-export list are protected with the corresponding contract. The body of the form allows definition/expression interleaving if its context does.\n\nThe second with-contract form must appear in expression position. The final body expression should return the same number of values as the number of contracts listed in the result-spec, and each returned value is contracted with its respective contract. The sequence of body forms is treated as for let.\n\nThe blame-id is used for the positive positions of contracts paired with exported ids. Contracts broken within the with-contract body will use the blame-id for their negative position.\n\nIf a free-var-list is given, then any uses of the free variables inside the body will be protected with contracts that blame the context of the with-contract form for the positive positions and the with-contract form for the negative ones.\n\n>
\n\n

syntax

\n\n

(define/contract id contract-expr free-var-list init-value-expr)

(define/contract (head args) contract-expr free-var-list body ...+)
\n\nWorks like define, except that the contract contract-expr is attached to the bound value. For the definition of head and args, see define. For the definition of free-var-list, see with-contract.\n\nExamples:\n\n> ```racket\n> > ( define/contract distance ( >=/c 0 ) 43.52 )\n> > ( define/contract ( furlongs → feet fr ) ( → real? real? ) ( * 660 fr ) )\n> ; a contract violation expected here:\n> > ( furlongs → feet \"not a furlong\" )\n> furlongs → feet: contract violation\n> expected: real?\n> given: \"not a furlong\"\n> in: the 1st argument of\n> ( → real? real?)\n> contract from: (function furlongs → feet)\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\n\nThe define/contract form treats the individual definition as a contract region. The definition itself is responsible for positive (co-variant) positions of the contract, and references to id outside of the definition must meet the negative positions of the contract. Since the contract boundary is between the definition and the surrounding context, references to id inside the define/contract form are not checked.\n\nExamples:\n\n> ```racket\n> ; an unsual predicate that prints when called\n> > ( define ( printing-int? x ) ( displayln \"I was called\" ) ( exact-integer? x ) )\n> > ( define/contract ( fact n ) ( → printing-int? printing-int? ) ( if ( zero? n ) 1 ( * n ( fact ( sub1 n ) ) ) ) )\n> > ( fact 5 ) ; only prints twice, not for each recursive call\n> I was called I was called\n> 120\n> ```\n\nIf a free-var-list is given, then any uses of the free variables inside the body will be protected with contracts that blame the context of the define/contract form for the positive positions and the define/contract form for the negative ones.\n\nExamples:\n\n> ```racket\n> > ( define ( integer → binary-string n ) ( number → string n 2 ) )\n> > ( define/contract ( numbers → strings lst ) ( → ( listof number? ) ( listof string? ) ) #:freevar integer → binary-string ( → exact-integer? string? ) ; mistake, lst might contain inexact numbers ( map integer → binary-string lst ) )\n> > ( numbers → strings ' ( 4.0 3.3 5.8 ) )\n> integer → binary-string: contract violation\n> expected: exact-integer?\n> given: 4.0\n> in: the 1st argument of\n> ( → exact-integer? string?)\n> contract from: top-level\n> blaming: (function numbers → strings)\n> (assuming the contract is correct)\n> at: eval:3:0\n> ```\n\n> ```\nsyntax\n\n(struct/contract struct-id ([field contract-expr] ...)\n> struct-option ... )\n( struct/contract struct-id super-struct-id\n> ( [ field contract-expr ] ... )\n> struct-option ... )```\n\n\nWorks like [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29), except that the arguments to the constructor, accessors, and mutators are protected by contracts. For the definitions of field and struct-option, see [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29).\n\nThe [struct/contract](#%28form._%28%28lib._racket%2Fcontract%2Fregion..rkt%29._struct%2Fcontract%29%29) form only allows a subset of the struct-option keywords: #:mutable, #:transparent, #:auto-value, #:omit-define-syntaxes, and #:property.\n\nExamples:\n\n> ```racket\n> > ( struct/contract fruit ( [ seeds number? ] ) )\n> > ( fruit 60 )\n> #\n> > ( fruit #f )\n> fruit: contract violation\n> expected: number?\n> given: #f\n> in: the 1st argument of\n> (-> number? symbol? any)\n> contract from: (struct fruit)\n> blaming: top-level\n> (assuming the contract is correct)\n> > ( struct/contract apple fruit ( [ type string? ] ) )\n> > ( apple 14 \"golden delicious\" )\n> #\n> > ( apple 5 30 )\n> apple: contract violation\n> expected: string?\n> given: 30\n> in: the 2nd argument of\n> (-> any/c string? symbol? any)\n> contract from: (struct apple)\n> blaming: top-level\n> (assuming the contract is correct)\n> > ( apple #f \"granny smith\" )\n> fruit: contract violation\n> expected: number?\n> given: #f\n> in: the 1st argument of\n> (-> number? symbol? any)\n> contract from: (struct fruit)\n> blaming: top-level\n> (assuming the contract is correct)\n> ```\n\n> ```\nsyntax\n\n(define-struct/contract struct-id ([field contract-expr] ...)\n> struct-option ... )\n( define-struct/contract ( struct-id super-struct-id )\n> ( [ field contract-expr ] ... )\n> struct-option ... )\n```"} {"text": "# 8.5 Structure Type Property Contracts\n(parameter)\t→\t\n(-> struct fish)```\nBound by [define-syntax-parameter](stxparam.html#%28form._%28%28lib._racket%2Fstxparam..rkt%29._define-syntax-parameter%29%29), this contains information about the current contract region, used by the above forms to determine the candidates for blame assignment."} {"text": "#### 8.6.2 Low-level Contract Boundaries\n> ```\nsyntax\n(define-module-boundary-contract id\n> orig-id\n> contract-expr\n> d-m-b-c-kwd-arg ... )\nd-m-b-c-kwd-arg   =   #:name-for-contract name-for-contract-id\n    |   #:name-for-blame blame-id\n    |   #:srcloc srcloc-expr\n    |   #:pos-source pos-source-expr\n    |   #:context-limit limit-expr\n    |   #:lift-to-end? boolean\n    |   #:start-swapped? boolean\n```\nDefines id to be orig-id, but with the contract contract-expr.\n\nThe identifier id is defined as a macro transformer that consults the context of its use to determine the name for negative blame assignment (using the entire module where a reference appears as the negative party).\n\nThe name used in the error messages will be orig-id, unless #:name-for-blame is supplied, in which case the identifier following it is used as the name in the error messages.\n\nThe contract expression is wrapped in a let to give it a name which will be passed on to the name of the wrapped value in certain situations (e.g., if the contract is a function contract). If name-for-contract-id is supplied, the identifier that follows it is used to name the contract; otherwise orig-id is used.\n\nThe source location used in the blame error messages for the location of the place where the contract was put on the value defaults to the source location of the use of define-module-boundary-contract, but can be specified via the #:srcloc argument, in which case it can be any of the things that the third argument to datum → syntax can be.\n\nThe positive party defaults to the module containing the use of define-module-boundary-contract, but can be specified explicitly via the #:pos-source keyword.\n\nIf #:context-limit is supplied, it behaves the same as it does when supplied to contract.\n\nIf lift-to-end? is #t or is not supplied, then the contract expression is placed at the end of the enclosing module (using syntax-local-lift-module-end-declaration). If it is supplied and #f, the contract expression is placed where define-module-boundary-contract is placed.\n\nIf start-swapped? is #t, then the initial blame object is created in the “swapped?” state, and the pos-source is used as a negative source. This is helpful to get the “contract from:” line in contract violations correct in certain situations. If #:start-swapped? is not supplied, it is treated as if it was supplied as #f.\n\nExamples:\n\n> ```racket\n> > ( module server racket/base ( require racket/contract/base ) ( define ( f x ) #f ) ( define-module-boundary-contract g f ( → integer? integer? ) ) ( provide g ) )\n> > ( module client racket/base ( require ' server ) ( define ( clients-fault ) ( g #f ) ) ( define ( servers-fault ) ( g 1 ) ) ( provide servers-fault clients-fault ) )\n> > ( require ' client )\n> > ( clients-fault )\n> g: contract violation\n> expected: integer?\n> given: #f\n> in: the 1st argument of\n> ( → integer? integer?)\n> contract from: 'server\n> blaming: client\n> (assuming the contract is correct)\n> at: eval:2:0\n> > ( servers-fault )\n> g: broke its own contract\n> promised: integer?\n> produced: #f\n> in: the range of\n> ( → integer? integer?)\n> contract from: 'server\n> blaming: (quote server)\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\n\nChanged in version 6.7.0.4 of package base: Added the #:name-for-blame argument. \nChanged in version 6.90.0.29: Added the #:context-limit argument. \nChanged in version 8.13.0.1: Added the #:name-for-contract and #:start-swapped arguments.\n\n>
\n\n

syntax

\n\n
( contract contract-expr to-protect-expr\n> positive-blame-expr negative-blame-expr )
( contract contract-expr to-protect-expr\n> positive-blame-expr negative-blame-expr\n> #:context-limit limit-expr )
( contract contract-expr to-protect-expr\n> positive-blame-expr negative-blame-expr\n> value-name-expr source-location-expr )
\n\nThe primitive mechanism for attaching a contract to a value. The purpose of contract is as a target for the expansion of some higher-level contract specifying form.\n\nThe contract expression adds the contract specified by contract-expr to the value produced by to-protect-expr. The result of a contract expression is the result of the to-protect-expr expression, but with the contract specified by contract-expr enforced on to-protect-expr.\n\nThe values of positive-blame-expr and negative-blame-expr indicate how to assign blame for positive and negative positions of the contract specified by contract-expr. They may be any value, and are formatted as by display for purposes of contract violation error messages.\n\nIf specified, value-name-expr indicates a name for the protected value to be used in error messages. If not supplied, or if value-name-expr produces #f, no name is printed. Otherwise, it is also formatted as by display. More precisely, the value-name-expr ends up in the blame-value field of the blame record, which is used as the first portion of the error message.\n\nExamples:\n\n> ```racket\n> > ( contract integer? #f ' pos ' neg ' timothy #f )\n> timothy: broke its own contract\n> promised: integer?\n> produced: #f\n> in: integer?\n> contract from: pos\n> blaming: pos\n> (assuming the contract is correct)\n> > ( contract integer? #f ' pos ' neg #f #f )\n> broke its own contract\n> promised: integer?\n> produced: #f\n> in: integer?\n> contract from: pos\n> blaming: pos\n> (assuming the contract is correct)\n> ```\n\nIf specified, source-location-expr indicates the source location reported by contract violations. The expression must produce a srcloc structure, syntax object, #f, or a list or vector in the format accepted by the third argument to datum → syntax.\n\nIf #:context-limit is supplied, the following expression must evaluate to either #f or a natural number. If the expression evaluates to an natural number, the number of layers of context information is limited to at most that many. For example, if the number is 0, no context information is recorded and the error messages do not contain the section that starts with in:.\n\n------------------------------------------------------------------------\n\n# 8.7 Building New Contract Combinators\n\n### 8.7 Building New Contract Combinators\n\n| | |\n|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/contract/combinator]()) |  package: base |\n\n> ```\n(make-contract\n   [ #:name name  \n    #:first-order first-order  \n    #:late-neg-projection late-neg-proj  \n    #:collapsible-late-neg-projection collapsible-late-neg-proj  \n    #:val-first-projection val-first-proj  \n    #:projection proj  \n    #:stronger stronger  \n    #:equivalent equivalent  \n    #:list-contract? is-list-contract?)  \n\n  →  contract?\n  name : any/c = 'anonymous-contract\n  first-order : ( →  any/c any/c) = (λ (x) #t)\n   late-neg-proj   :   (or/c #f ( →  blame? ( →  any/c any/c any/c)))\n      =   #f\n\n   collapsible-late-neg-proj   :   (or/c #f ( →  blame? (values ( →  any/c any/c any/c) collapsible-contract?)))\n      =   #f\n\n   val-first-proj   :   (or/c #f ( →  blame? ( →  any/c ( →  any/c any/c))))\n      =   #f\n\n   proj   :   ( →  blame? ( →  any/c any/c))\n      =   ( λ ( b )\n> ( λ ( x )\n> ( if ( first-order x )\n> x\n> ( raise-blame-error\n> b x\n> ' ( expected: \"~a\" given: \"~e\" )\n> name x ) ) ) )\n\n  stronger : (or/c #f ( →  contract? contract? boolean?)) = #f\n  equivalent : (or/c #f ( →  contract? contract? boolean?)) = #f\n  is-list-contract? : boolean? = #f\n\n(make-chaperone-contract  \n   [ #:name name  \n    #:first-order first-order  \n    #:late-neg-projection late-neg-proj  \n    #:collapsible-late-neg-projection collapsible-late-neg-proj  \n    #:val-first-projection val-first-proj  \n    #:projection proj  \n    #:stronger stronger  \n    #:equivalent equivalent  \n    #:list-contract? is-list-contract?)  \n\n  →  chaperone-contract?\n  name : any/c = 'anonymous-chaperone-contract\n  first-order : ( →  any/c any/c) = (λ (x) #t)\n   late-neg-proj   :   (or/c #f ( →  blame? ( →  any/c any/c any/c)))\n      =   #f\n\n   collapsible-late-neg-proj   :   (or/c #f ( →  blame? (values ( →  any/c any/c any/c) collapsible-contract?)))\n      =   #f\n\n   val-first-proj   :   (or/c #f ( →  blame? ( →  any/c ( →  any/c any/c))))\n      =   #f\n\n   proj   :   ( →  blame? ( →  any/c any/c))\n      =   ( λ ( b )\n> ( λ ( x )\n> ( if ( first-order x )\n> x\n> ( raise-blame-error\n> b x\n> ' ( expected: \"~a\" given: \"~e\" )\n> name x ) ) ) )\n\n  stronger : (or/c #f ( →  contract? contract? boolean?)) = #f\n  equivalent : (or/c #f ( →  contract? contract? boolean?)) = #f\n  is-list-contract? : boolean? = #f\n\n(make-flat-contract  \n   [ #:name name  \n    #:first-order first-order  \n    #:late-neg-projection late-neg-proj  \n    #:collapsible-late-neg-projection collapsible-late-neg-proj  \n    #:val-first-projection val-first-proj  \n    #:projection proj  \n    #:stronger stronger  \n    #:equivalent equivalent  \n    #:list-contract? is-list-contract?)  \n\n  →  flat-contract?\n  name : any/c = 'anonymous-flat-contract\n  first-order : ( →  any/c any/c) = (λ (x) #t)\n   late-neg-proj   :   (or/c #f ( →  blame? ( →  any/c any/c any/c)))\n      =   #f\n\n   collapsible-late-neg-proj   :   (or/c #f ( →  blame? (values ( →  any/c any/c any/c) collapsible-contract?)))\n      =   #f\n\n   val-first-proj   :   (or/c #f ( →  blame? ( →  any/c ( →  any/c any/c))))\n      =   #f\n\n   proj   :   ( →  blame? ( →  any/c any/c))\n      =   ( λ ( b )\n> ( λ ( x )\n> ( if ( first-order x )\n> x\n> ( raise-blame-error\n> b x\n> ' ( expected: \"~a\" given: \"~e\" )\n> name x ) ) ) )\n\n  stronger : (or/c #f ( →  contract? contract? boolean?)) = #f\n  equivalent : (or/c #f ( →  contract? contract? boolean?)) = #f\n  is-list-contract? : boolean? = #f```\n\n\nThese functions build simple higher-order contracts, [chaperone contracts](contracts.html#%28tech._chaperone._contract%29), and [flat contracts](contracts.html#%28tech._flat._contract%29), respectively. They all take the same set of three optional arguments: a name, a first-order predicate, and a blame-tracking projection. For [make-flat-contract](#%28def._%28%28lib._racket%2Fcontract%2Fcombinator..rkt%29._make-flat-contract%29%29), see also [flat-contract-with-explanation](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._flat-contract-with-explanation%29%29).\n\nThe name argument is any value to be rendered using [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29) to describe the contract when a violation occurs. The default name for simple higher-order contracts is anonymous-contract, for [chaperone contracts](contracts.html#%28tech._chaperone._contract%29) is anonymous-chaperone-contract, and for [flat contracts](contracts.html#%28tech._flat._contract%29) is anonymous-flat-contract.\n\nThe first-order predicate first-order is used to determine which values the contract applies to. This test is used by [contract-first-order-passes?](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract-first-order-passes~3f%29%29), and indirectly by [or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) and [first-or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._first-or%2Fc%29%29) to determine which higher-order contract to wrap a value with when there are multiple higher-order contracts to choose from. The default value accepts any value, but it must match the behavior of the projection argument (see below for how). The predicate should be influenced by the value of (contract-first-order-okay-to-give-up?) (see it’s documentation for more explanation).\n\nThe late-neg-proj argument defines the behavior of applying the contract via a late neg projection. If it is supplied, this argument accepts a [blame object](#%28tech._blame._object%29) that is missing one party (see also [blame-missing-party?](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._blame-missing-party~3f%29%29)). Then it must return a function that accepts both the value that is getting the contract and the name of the missing blame party, in that order. The result must either be the value (perhaps suitably wrapped with a [chaperone](chaperones.html#%28tech._chaperone%29) or [impersonator](chaperones.html#%28tech._impersonator%29) to enforce the contract), or signal a contract violation using [raise-blame-error](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._raise-blame-error%29%29). The default is #f.\n\nThe collapsible-late-neg-proj argument takes the place of the late-neg-proj argument for contracts that support collapsing. If it is supplied, this argument accepts a [blame object](#%28tech._blame._object%29) that is missing one party. It must return two values. The first value must be a function that accepts both the value that is getting the contract and the name of the missing blame party, in that order. The second value should be a [collapsible](collapsible.html#%28tech._collapsible._contract%29) representation of the contract.\n\nThe projection proj and val-first-proj are older mechanisms for defining the behavior of applying the contract. The proj argument is a curried function of two arguments: the first application accepts a blame object, and the second accepts a value to protect with the contract. The projection must either produce the value, suitably wrapped to enforce any higher-order aspects of the contract, or signal a contract violation using [raise-blame-error](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._raise-blame-error%29%29). The default projection produces an error when the first-order test fails, and produces the value unchanged otherwise. The val-first-proj is like late-neg-proj, except with an extra layer of currying.\n\nAt least one of the late-neg-proj, proj, val-first-proj, or first-order must be non-#f.\n\nThe projection arguments (late-neg-proj, proj, and val-first-proj) must be in sync with the first-order argument. In particular, if the first-order argument returns #f for some value, then the projections must raise a blame error for that value and if the first-order argument returns #t for some value, then the projection must not signal any blame for this value, unless there are higher-order interactions later. In other words, for [flat contracts](contracts.html#%28tech._flat._contract%29), the first-order and projection arguments must check the same predicate. For convenience, the the default projection uses the first-order argument, signalling an error when it returns #f and never signalling one otherwise.\n\nProjections for [chaperone contracts](contracts.html#%28tech._chaperone._contract%29) must produce a value that passes [chaperone-of?](chaperones.html#%28def._%28%28quote._~23~25kernel%29._chaperone-of~3f%29%29) when compared with the original, uncontracted value. Projections for [flat contracts](contracts.html#%28tech._flat._contract%29) must fail precisely when first-order does, and must produce the input value unchanged otherwise. Applying a [flat contract](contracts.html#%28tech._flat._contract%29) may result in either an application of the predicate, or the projection, or both; therefore, the two must be consistent. The existence of a separate projection only serves to provide more specific error messages. Most [flat contracts](contracts.html#%28tech._flat._contract%29) do not need to supply an explicit projection.\n\nThe stronger argument is used to implement [contract-stronger?](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract-stronger~3f%29%29). The first argument is always the contract itself and the second argument is whatever was passed as the second argument to [contract-stronger?](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract-stronger~3f%29%29). If no stronger argument is supplied, then a default that compares its arguments with [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) is used for [flat contracts](contracts.html#%28tech._flat._contract%29) and [chaperone contracts](contracts.html#%28tech._chaperone._contract%29). For [impersonator contracts](contracts.html#%28tech._impersonator._contract%29) constructed with [make-contract](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fprop..rkt%29._make-contract%29%29) that do not supply the stronger argument, [contract-stronger?](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract-stronger~3f%29%29) returns #f.\n\nSimilarly, the equivalent argument is used to implement [contract-equivalent?](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract-equivalent~3f%29%29). If it isn’t supplied or #false is supplied, then [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) is used for chaperone and flat contracts, and ([λ](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~ce~bb%29%29) (x y) #f) is used otherwise.\n\nThe is-list-contract? argument is used by the [list-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._list-contract~3f%29%29) predicate to determine if this is a contract that accepts only [list?](pairs.html#%28def._%28%28quote._~23~25kernel%29._list~3f%29%29) values.\n\nExamples:\n\n> ```racket\n> > ( define int/c ( make-flat-contract #:name ' int/c #:first-order integer? ) )\n> > ( contract int/c 1 ' positive ' negative )\n> 1\n> > ( contract int/c \"not one\" ' positive ' negative )\n> eval:4:0: broke its own contract\n> promised: int/c\n> produced: \"not one\"\n> in: int/c\n> contract from: positive\n> blaming: positive\n> (assuming the contract is correct)\n> > ( int/c 1 )\n> #t\n> > ( int/c \"not one\" )\n> #f\n> > ( define int->int/c ( make-contract #:name ' int->int/c #:first-order ( λ ( x ) ( and ( procedure? x ) ( procedure-arity-includes? x 1 ) ) ) #:projection ( λ ( b ) ( let ( [ domain ( ( contract-projection int/c ) ( blame-swap b ) ) ] [ range ( ( contract-projection int/c ) b ) ] ) ( λ ( f ) ( if ( and ( procedure? f ) ( procedure-arity-includes? f 1 ) ) ( λ ( x ) ( range ( f ( domain x ) ) ) ) ( raise-blame-error b f ' ( expected \"a function of one argument\" given: \"~e\" ) f ) ) ) ) ) ) )\n> > ( contract int->int/c \"not fun\" ' positive ' negative )\n> eval:8:0: broke its own contract;\n> promised a function of one argument\n> produced: \"not fun\"\n> in: int->int/c\n> contract from: positive\n> blaming: positive\n> (assuming the contract is correct)\n> > ( define halve ( contract int->int/c ( λ ( x ) ( / x 2 ) ) ' positive ' negative ) )\n> > ( halve 2 )\n> 1\n> > ( halve 1/2 )\n> halve: contract violation\n> expected: int/c\n> given: 1/2\n> in: int->int/c\n> contract from: positive\n> blaming: negative\n> (assuming the contract is correct)\n> > ( halve 1 )\n> halve: broke its own contract\n> promised: int/c\n> produced: 1/2\n> in: int->int/c\n> contract from: positive\n> blaming: positive\n> (assuming the contract is correct)\n> ```\n\nChanged in version 6.0.1.13 of package base: Added the #:list-contract? argument. \nChanged in version 6.90.0.30: Added the #:equivalent argument. \nChanged in version 7.1.0.10: Added the #:collapsible-late-neg-projection argument.\n\n> ```\n(build-compound-type-name c/s ...) → any\n  c/s : any/c\n```"} {"text": "# 8.5 Structure Type Property Contracts\n(parameter)\t→```\nConverts a regular Racket value into an instance of a contract struct, converting it according to the description of [contracts](contracts.html#%28tech._contract%29).\nIf v is not one of the coercible values, [coerce-contract](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._coerce-contract%29%29) signals an error, using the first argument in the error message.\n> ```\n(parameter)\t→\t\n(-> listof contract?)\n```\n(parameter)\t→```\n\n\nLike [coerce-contract](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._coerce-contract%29%29), but requires the result to be a [chaperone contract](contracts.html#%28tech._chaperone._contract%29), not an arbitrary contract.\n\n> ```\n(parameter)\t→\t\n(-> listof chaperone-contract?)\n```\n(parameter)\t→```\nLike [coerce-contract](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._coerce-contract%29%29), but requires the result to be a [flat contract](contracts.html#%28tech._flat._contract%29), not an arbitrary contract.\n> ```\n(parameter)\t→\t\n(-> listof flat-contract?)\n```\nLike coerce-contracts, but requires the results to be flat contracts, not arbitrary contracts.\n\n> ```\n(coerce-contract/f v)  →  (or/c contract? #f)\n  v : any/c```\n\n\nLike [coerce-contract](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._coerce-contract%29%29), but returns #f if the value cannot be coerced to a contract.\n\n> ```\n(parameter)\t→\t\n(-> skip-projection-wrapper? wrap?)\n```"} {"text": "# 8.5 Structure Type Property Contracts\nThe functions make-chaperone-contract and build-chaperone-contract-property wrap their arguments to ensure that the result of the projections are chaperones of the input. This layer of wrapping can, in some cases, introduce unwanted overhead into contract checking. If this parameter’s value is #t during the dynamic extent of the call to either of those functions, the wrapping (and thus the checks) are skipped.\n>
\n

syntax

\n

(with-contract-continuation-mark blame body ...)

(with-contract-continuation-mark blame+neg-party body ...)
\nInserts a continuation mark that informs the contract profiler (see the contract profiling documentation) that contract checking is happening. For the costs from checking your new combinator to be included, you should wrap any deferred, higher-order checks with this form. First-order checks are recognized automatically and do not require this form.\nIf your combinator’s projections operate on complete blame objects (i.e., no missing blame parties), the blame object should be the first argument to this form. Otherwise (e.g., in the case of late-neg projections), a pair of the blame object and the missing party should be used instead.\nAdded in version 6.4.0.4 of package base.\n>
\n

syntax

"} {"text": "# 8.5 Structure Type Property Contracts\n

(contract-pos/neg-doubling e1 e2)

\nSome contract combinators need to build projections for subcontracts with both regular and blame-swaped versions of the blame that they are given in order to check both access and mutations (e.g., vector/c and vectorof). In the case that such combinators are nested deeply inside each other, there is a potential for an exponential explosion of nested projections being built.\nTo avoid that explosion, wrap each of the calls to the blame-accepting portion of the combinator in contract-pos/neg-doubling. It returns three values. The first is a boolean, indicating how to interpret the other two results. If the boolean is #t, then the other two results are the values of e1 and e2 and we are not too deep in the nesting. If the boolean is #f, then we have passed a threshold and it is not safe to evaluate e1 and e2 yet, as we are in danger of running into the exponential slowdown. In that case, the last two results are thunks that, when invoked, compute the values of e1 and e2.\nAs an example, vectorof uses contract-pos/neg-doubling wrapping its two calls to the blame-accepting part of the projection for its subcontract. When it receives a #f as that first boolean, it does not invoke the thunks right away, but waits until the interposition procedure that it attaches to the chaperoned vector is called. Then it invokes them (and caches the result). This delays the construction of the projections until they are actually needed, avoiding the exponential blowup."} {"text": "# 8.5 Structure Type Property Contracts\nAdded in version 6.90.0.27 of package base."} {"text": "#### 8.7.1 Blame Objects\nThis section describes blame objects and operations on them.\n> ```\n(blame? v) → boolean?\n  v : any/c```\nThis predicate recognizes [blame objects](#%28tech._blame._object%29).\n> ```\n(raise-blame-error b\n    #:missing-party missing-party        \n    v        \n    fmt        \n    v-fmt ...)   →   none/c\n  b : blame?\n  missing-party : #f\n  v : any/c\n   fmt   :   ( or/c string?\n> ( listof ( or/c string?\n> ' given ' given:\n> ' expected ' expected: ) ) )\n  v-fmt : any/c\n```\nSignals a contract violation. The first argument, b, records the current blame information, including positive and negative parties, the name of the contract, the name of the value, and the source location of the contract application. The #:missing-party argument supplies one of the blame parties. It should be non-#f when the b object was created without supplying a negative party. See blame-add-missing-party and the description of the late-neg-proj argument of make-contract.\n\nThe second positional argument, v, is the value that failed to satisfy the contract.\n\nThe remaining arguments are a format string, fmt, and its arguments, v-fmt ..., specifying an error message specific to the precise violation.\n\nIf fmt is a list, then the elements are concatenated together (with spaces added, unless there are already spaces at the ends of the strings), after first replacing symbols with either their string counterparts, or replacing 'given with \"produced\" and 'expected with \"promised\", depending on whether or not the b argument has been swapped or not (see blame-swap).\n\nIf fmt contains the symbols 'given: or 'expected:, they are replaced like 'given and 'expected are, but the replacements are prefixed with the string \"\\\\n  \" to conform to the error message guidelines in Error Message Conventions.\n\n> ```\n(blame-add-context blame\n    context        \n   [ #:important important        \n    #:swap? swap?)   →   blame?\n\n  blame : blame?\n  context : (or/c string? #f)\n  important : (or/c string? #f) = #f\n  swap? : boolean? = #f```\n\n\nAdds some context information to blame error messages that explicates which portion of the contract failed (and that gets rendered by [raise-blame-error](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._raise-blame-error%29%29)).\n\nThe context argument describes one layer of the portion of the contract, typically of the form \"the 1st argument of\" (in the case of a function contract) or \"a conjunct of\" (in the case of an [and/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) contract).\n\nFor example, consider this contract violation:\n\n> ```racket\n> > ( define/contract f ( list/c ( -> integer? integer? ) ) ( list ( λ ( x ) x ) ) )\n> > ( ( car f ) #f )\n> f: contract violation\n> expected: integer?\n> given: #f\n> in: the 1st argument of\n> the 1st element of\n> (list/c (-> integer? integer?))\n> contract from: (definition f)\n> blaming: top-level\n> (assuming the contract is correct)\n> at: eval:2:0\n> ```\n\nIt shows that the portion of the contract being violated is the first occurrence of [integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._integer~3f%29%29), because the [->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) and the [list/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._list%2Fc%29%29) combinators each internally called [blame-add-context](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._blame-add-context%29%29) to add the two lines following “in” in the error message.\n\nThe important argument is used to build the beginning part of the contract violation. The last important argument that gets added to a [blame object](#%28tech._blame._object%29) is used. The [class/c](Object_and_Class_Contracts.html#%28form._%28%28lib._racket%2Fclass..rkt%29._class%2Fc%29%29) contract adds an important argument, as does the [->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) contract (when [->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) knows the name of the function getting the contract).\n\nThe swap? argument has the effect of calling [blame-swap](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._blame-swap%29%29) while adding the layer of context, but without creating an extra [blame object](#%28tech._blame._object%29).\n\nPassing #f as the context string argument is no longer relevant. For backwards compatibility, [blame-add-context](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._blame-add-context%29%29) returns b when context is #f.\n\nChanged in version 6.90.0.29 of package base: The context argument being #f is no longer relevant.\n\n> ```\n(blame-context blame)  →  (listof string?)\n  blame : blame?\n```"} {"text": "# 8.5 Structure Type Property Contracts\nReturns the context information that would be supplied in an error message, if blame is passed to raise-blame-error.\n> ```\n(blame-positive b)  →  any/c\n  b : blame?\n(blame-negative b)  →  any/c\n  b : blame?```\nThese functions produce printable descriptions of the current positive and negative parties of a [blame object](#%28tech._blame._object%29).\n> ```\n(blame-contract b)  →  any/c\n  b : blame?\n```\nThis function produces a description of the contract associated with a blame object (the result of contract-name).\n\n> ```\n(blame-value b)  →  any/c\n  b : blame?```\n\n\nThis function produces the name of the value to which the contract was applied, or #f if no name was provided.\n\n> ```\n(blame-source b)  →  srcloc?\n  b : blame?\n```\nThis function produces the source location associated with a contract. If no source location was provided, all fields of the structure will contain #f.\n> ```\n(blame-swap b)  →  blame?\n  b : blame?\n```\n\n\nThis function swaps the positive and negative parties of a [blame object](#%28tech._blame._object%29). (See also [blame-add-context](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._blame-add-context%29%29).)\n\n> ```\n(blame-original? b)  →  boolean?\n  b : blame?\n\n(blame-swapped? b)  →  boolean?\n  b : blame?\n```"} {"text": "# 8.5 Structure Type Property Contracts\nThese functions report whether the current blame of a given blame object is the same as in the original contract invocation (possibly of a compound contract containing the current one), or swapped, respectively. Each is the negation of the other; both are provided for convenience and clarity.\n> ```\n(blame-replace-negative b neg)  →  blame?\n  b : blame?\n  neg : any/c```\nProduces a [blame?](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._blame~3f%29%29) object just like b except that it uses neg instead of the negative position b has.\n> ```\n(blame-replaced-negative? b)  →  boolean?\n  b : blame?\n```\nReturns #t if b is the result of calling blame-replace-negative (or the result of some other function whose input was the result of blame-replace-negative).\n\n> ```\n(blame-update b pos neg)  →  blame?\n  b : blame?\n  pos : any/c\n  neg : any/c```\n\n\nProduces a [blame?](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._blame~3f%29%29) object just like b except that it adds pos and neg to the positive and negative parties of b respectively.\n\n> ```\n(blame-missing-party? b)  →  boolean?\n  b : blame?\n```\nReturns #t when b does not have both parties.\n> ```\n(blame-add-missing-party b missing-party)\n  →  (and/c blame? (not/c blame-missing-party?))\n  b : (and/c blame? blame-missing-party?)\n  missing-party : any/c"} {"text": "# 8.5 Structure Type Property Contracts\n```\n\n\nProduces a new [blame object](#%28tech._blame._object%29) like b, except that the missing party is replaced with missing-party.\n\n>
\n\n

struct

\n\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:contract:blame](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._exn~3afail~3acontract~3ablame%29%29) [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) (object)
    #:extra-constructor-name [make-exn:fail:contract:blame](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._make-exn~3afail~3acontract~3ablame%29%29))
  object : [blame?](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._blame~3f%29%29)
\n\nThis exception is raised to signal a contract error. The object field contains a [blame object](#%28tech._blame._object%29) associated with a contract violation.\n\n> ```\n(current-blame-format)\t→\t\n(-> blame? any/c string? string?)\n(current-blame-format proc) → void?\n proc\t:\t\n(-> blame? any/c string? string?)\n```\n(c)\t→\t\n(-> / x 2)```"} {"text": "# 8.5 Structure Type Property Contracts\nThese functions build the arguments for [prop:contract](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fprop..rkt%29._prop~3acontract%29%29), [prop:chaperone-contract](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fprop..rkt%29._prop~3achaperone-contract%29%29), and [prop:flat-contract](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fprop..rkt%29._prop~3aflat-contract%29%29), respectively.\nA contract property specifies the behavior of a structure when used as a contract. It is specified in terms of seven properties:\n- get-name which produces a description to [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29) as part of a contract violation and defaults to a function that always produces 'anonymous-contract, 'anonymous-chaperone-contract, or 'anonymous-flat-contract;\n- get-first-order, which produces a first-order predicate to be used by [contract-first-order-passes?](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract-first-order-passes~3f%29%29);\n- late-neg-proj, which produces a blame-tracking projection defining the behavior of the contract (The get-projection and val-first-proj arguments also specify the projection, but using a different signature. They are here for backwards compatibility.);\n- collapsible-late-neg-proj, similar to late-neg-proj which produces a blame-tracking projection defining the behavior of the contract, this function additionally specifies the [collapsible](collapsible.html#%28tech._collapsible._contract%29) behavior of the contract;"} {"text": "# 8.5 Structure Type Property Contracts\n- stronger, a predicate that determines whether this contract (passed in the first argument) is stronger than some other contract (passed in the second argument) and whose default always returns #f;\n- equivalent, a predicate that determines whether this contract (passed in the first argument) is equivalent to some other contract (passed in the second argument); the default for flat and chaperone contracts is [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) and for impersonator contracts returns #f;\n- generate, which returns a thunk that generates random values matching the contract (using [contract-random-generate-fail](Random_generation.html#%28def._%28%28lib._racket%2Fcontract..rkt%29._contract-random-generate-fail%29%29)) to indicate failure) or #f to indicate that random generation for this contract isn’t supported;\n- exercise, which returns a function that exercises values matching the contract (e.g., if it is a function contract, it may call the function) and a list of contracts whose values will be generated by this process;\n- and is-list-contract?, which is used by [flat-contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._flat-contract~3f%29%29) to determine if this contract accepts only [list?](pairs.html#%28def._%28%28quote._~23~25kernel%29._list~3f%29%29)s.\nAt least one of the late-neg-proj, collapsible-late-neg-proj, get-projection, val-first-proj, or get-first-order must be non-#f."} {"text": "# 8.5 Structure Type Property Contracts\nThese accessors are passed as (optional) keyword arguments to [build-contract-property](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fprop..rkt%29._build-contract-property%29%29), and are applied to instances of the appropriate structure type by the contract system. Their results are used analogously to the arguments of [make-contract](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fprop..rkt%29._make-contract%29%29).\nA chaperone contract property specifies the behavior of a structure when used as a chaperone contract. It is specified using [build-chaperone-contract-property](#%28def._%28%28lib._racket%2Fcontract%2Fcombinator..rkt%29._build-chaperone-contract-property%29%29), and accepts exactly the same set of arguments as [build-contract-property](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fprop..rkt%29._build-contract-property%29%29). The only difference is that the projection accessor must return a value that passes [chaperone-of?](chaperones.html#%28def._%28%28quote._~23~25kernel%29._chaperone-of~3f%29%29) when compared with the original, uncontracted value.\nA flat contract property specifies the behavior of a structure when used as a [flat contract](contracts.html#%28tech._flat._contract%29). It is specified using [build-flat-contract-property](#%28def._%28%28lib._racket%2Fcontract%2Fcombinator..rkt%29._build-flat-contract-property%29%29), and accepts similar arguments as [build-contract-property](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fprop..rkt%29._build-contract-property%29%29). The differences are:"} {"text": "# 8.5 Structure Type Property Contracts\n- the projection accessor is expected not to wrap its argument in a higher-order fashion, analogous to the constraint on projections in [make-flat-contract](#%28def._%28%28lib._racket%2Fcontract%2Fcombinator..rkt%29._make-flat-contract%29%29);\n- the #:exercise keyword argument is omitted because it is not relevant for flat contracts.\nChanged in version 6.0.1.13 of package base: Added the #:list-contract? argument. \nChanged in version 6.1.1.4: Allow generate to return [contract-random-generate-fail](Random_generation.html#%28def._%28%28lib._racket%2Fcontract..rkt%29._contract-random-generate-fail%29%29). \nChanged in version 6.90.0.30: Added the #:equivalent argument. \nChanged in version 7.1.0.10: Added the #:collapsible-late-neg-projection argument.\n> ```\n(contract-property? v)  →  boolean?\n  v : any/c\n(chaperone-contract-property? v)  →  boolean?\n  v : any/c\n(flat-contract-property? v)  →  boolean?\n  v : any/c"} {"text": "# 8.5 Structure Type Property Contracts\n```\n(module)\t→\t\n(->)```\n\n\nReturns #t if the contract c1 accepts either fewer or the same set of values that c2 does.\n\n[Chaperone contracts](contracts.html#%28tech._chaperone._contract%29) and [flat contracts](contracts.html#%28tech._flat._contract%29) that are the same (i.e., where c1 is [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) to c2) are considered to always be stronger than each other.\n\nThis function is conservative, so it may return #f when c1 does, in fact, accept fewer values.\n\nExamples:\n\n> ```racket\n> > ( contract-stronger? integer? integer? )\n> #t\n> > ( contract-stronger? ( between/c 25 75 ) ( between/c 0 100 ) )\n> #t\n> > ( contract-stronger? ( between/c 0 100 ) ( between/c 25 75 ) )\n> #f\n> > ( contract-stronger? ( between/c -1 0 0 ) ( between/c 0 10 ) )\n> #f\n> > ( contract-stronger? ( λ ( x ) ( and ( real? x ) ( <= x 0 ) ) ) ( λ ( x ) ( and ( real? x ) ( <= x 100 ) ) ) )> #f\n> ```\n\n> ```\n(contract-equivalent? c1 c2)  →  boolean?\n  c1 : contract?\n  c2 : contract?\n```\nReturns #t if the contract c1 accepts the same set of values that c2 does.\nChaperone contracts and flat contracts that are the same (i.e., where c1 is equal? to c2) are considered to always be equivalent to each other.\nThis function is conservative, so it may return #f when c1 does, in fact, accept the same set of values that c2 does.\nExamples:"} {"text": "# 8.5 Structure Type Property Contracts\n> ```racket\n> > ( contract-equivalent? integer? integer? )\n> #t\n> > ( contract-equivalent? ( non-empty-listof integer? ) ( cons/c integer? ( listof integer? ) ) )\n> #t\n> > ( contract-equivalent? ( λ ( x ) ( and ( real? x ) ( and ( number? x ) ( >= ( sqr x ) 0 ) ) ) ) ( λ ( x ) ( and ( real? x ) ( real? x ) ) ) )\n> #f\n> ```\nAdded in version 6.90.0.30 of package base.\n> ```\n(contract-first-order-passes? contract v) → boolean?\n  contract : contract?\n  v : any/c```\nReturns a boolean indicating whether the first-order tests of contract pass for v.\nIf it returns #f, the contract is guaranteed not to hold for that value; if it returns #t, the contract may or may not hold. If the contract is a first-order contract, a result of #t guarantees that the contract holds.\nSee also contract-first-order-okay-to-give-up? and contract-first-order-try-less-hard.\n> ```\n(contract-first-order c)  →  ( →  any/c boolean?)\n  c : contract?\n```\nProduces the first-order test used by or/c to match values to higher-order contracts.\n\n------------------------------------------------------------------------\n\n# 8.8 Contract Utilities\n\n### 8.8 Contract Utilities\n\n> ```\n(contract? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if its argument is a [contract](contracts.html#%28tech._contract%29) (i.e., constructed with one of the combinators described in this section or a value that can be used as a contract) and #f otherwise.\n\n> ```\n(chaperone-contract? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 8.5 Structure Type Property Contracts\nReturns #t if its argument is a chaperone contract, i.e., one that guarantees that it returns a value which passes chaperone-of? when compared to the original, uncontracted value.\n> ```\n(impersonator-contract? v)  →  boolean?\n  v : any/c```\nReturns #t if its argument is an [impersonator contract](contracts.html#%28tech._impersonator._contract%29), i.e., a [contract](contracts.html#%28tech._contract%29) that is neither a [chaperone contract](contracts.html#%28tech._chaperone._contract%29) nor a [flat contract](contracts.html#%28tech._flat._contract%29).\n> ```\n(flat-contract? v)  →  boolean?\n  v : any/c"} {"text": "# 8.5 Structure Type Property Contracts\n```\nReturns #t when its argument is a contract that can be checked immediately (unlike, say, a function contract).\n\nFor example, flat-contract constructs flat contracts from predicates, and symbols, booleans, numbers, and other ordinary Racket values (that are defined as contracts) are also flat contracts.\n\n> ```\n(list-contract? v)  →  boolean?\n  v : any/c```\n\n\nRecognizes certain [contract?](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract~3f%29%29) values that accept [list?](pairs.html#%28def._%28%28quote._~23~25kernel%29._list~3f%29%29)s.\n\nA list contract is one that insists that its argument is a [list?](pairs.html#%28def._%28%28quote._~23~25kernel%29._list~3f%29%29), meaning that the value cannot be cyclic and must either be the empty list or a pair constructed with [cons](pairs.html#%28def._%28%28quote._~23~25kernel%29._cons%29%29) and another list.\n\nAdded in version 6.0.1.13 of package base.\n\n> ```\n(contract-name c)  →  any/c\n  c : contract?\n```\nProduces the name used to describe the contract in error messages.\n> ```\n(value-contract v)  →  (or/c contract? #f)\n  v : has-contract?"} {"text": "# 8.5 Structure Type Property Contracts\n```\n\n\nReturns the contract attached to v, if recorded. Otherwise it returns #f.\n\nTo support [value-contract](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._value-contract%29%29) and [value-contract](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._value-contract%29%29) in your own contract combinators, use [prop:contracted](Building_New_Contract_Combinators.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._prop~3acontracted%29%29) or [impersonator-prop:contracted](Building_New_Contract_Combinators.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._impersonator-prop~3acontracted%29%29).\n\n> ```\n(has-contract? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a value that has a recorded contract attached to it.\n> ```\n(value-blame v)  →  (or/c blame? #f)\n  v : has-blame?"} {"text": "# 8.5 Structure Type Property Contracts\n```\n\n\nReturns the [blame object](Building_New_Contract_Combinators.html#%28tech._blame._object%29) for the contract attached to v, if recorded. Otherwise it returns #f.\n\nTo support [value-contract](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._value-contract%29%29) and [value-blame](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._value-blame%29%29) in your own contract combinators, use [prop:blame](Building_New_Contract_Combinators.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._prop~3ablame%29%29) or [impersonator-prop:blame](Building_New_Contract_Combinators.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._impersonator-prop~3ablame%29%29).\n\nAdded in version 6.0.1.12 of package base.\n\n> ```\n(has-blame? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a value that has a contract with blame information attached to it.\nAdded in version 6.0.1.12 of package base.\n> ```\n(contract-late-neg-projection c)\n  →  ( →  blame? ( →  any/c (or/c #f any/c) any/c))\n  c : contract?"} {"text": "# 8.5 Structure Type Property Contracts\n```\n\n\nProduces the projection defining a contract’s behavior.\n\nThe first argument, [blame?](Building_New_Contract_Combinators.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._blame~3f%29%29) object encapsulates information about the contract checking, mostly used to create a meaningful error message if a contract violation is detected. The resulting function’s first argument is the value that should have the contract and its second argument is a missing party for the [blame object](Building_New_Contract_Combinators.html#%28tech._blame._object%29), to be passed to [raise-contract-error](Legacy_Contracts.html#%28def._%28%28lib._racket%2Fcontract..rkt%29._raise-contract-error%29%29).\n\nIf possible, use this function instead of [contract-val-first-projection](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract-val-first-projection%29%29) or [contract-projection](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract-projection%29%29).\n\n> ```\n(contract-projection c)  →  ( →  blame? ( →  any/c any/c))\n  c : contract?\n```\nProduces a projection defining a contract’s behavior. This projection is a curried function of two arguments: the first application accepts a blame object, and the second accepts a value to protect with the contract.\nIf possible, use contract-late-neg-projection instead.\n> ```\n(contract-val-first-projection c)\n  →  ( →  blame? ( →  any/c ( →  any/c any/c)))\n  c : contract?```"} {"text": "# 8.5 Structure Type Property Contracts\nProduces a projection defining a contract’s behavior. This projection is similar to the result of [contract-late-neg-projection](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract-late-neg-projection%29%29) except with an extra layer of currying.\nIf possible, use [contract-late-neg-projection](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract-late-neg-projection%29%29) instead.\n> ```\n(make-none/c sexp-name)  →  contract?\n  sexp-name : any/c\n```\n(not-a-contract)\t→\t\n(-> or/c #f #t 0 1)```\n\n\nPrints c to p using the contract’s name.\n\nAdded in version 6.1.1.5 of package base.\n\n> ```\n(rename-contract contract name)  →  contract?\n  contract : contract?\n  name : any/c\n```\nProduces a contract that acts like contract but with the name name.\nThe resulting contract is a flat contract if contract is a flat contract.\nAdded in version 6.3 of package base.\n>
\n

syntax

\n

(contract-first-order-okay-to-give-up?)

\nThis form returns a boolean that controls the result of first-order contact checks. More specifically, if it returns #t, then a first-order check may return #t even when the entire first-order checks have not happened. If it returns #f then the first order checks must continue until a definitive answer is returned.\nThis will only return #t in the dynamic extent of or/c or first-or/c’s checking to determine which branch to use."} {"text": "# 8.5 Structure Type Property Contracts\nAdded in version 6.3.0.9 of package base.\n>
\n

syntax

\n

(contract-first-order-try-less-hard e)

\nEncourages first-order checks that happen in the dynamic-extent of e to be more likely to give up. That is, makes it more likely that contract-first-order-okay-to-give-up? might return #t.\nIf not in the dynamic-extent of or/c’s or first-or/c’s checking to determine the branch, then this form has no effect.\nAdded in version 6.3.0.9 of package base.\n> ```\n(if/c predicate then-contract else-contract) → contract?\n  predicate : ( →  any/c any/c)\n  then-contract : contract?\n  else-contract : contract?```\nProduces a contract that, when applied to a value, first tests the value with predicate; if predicate returns true, the then-contract is applied; otherwise, the else-contract is applied. The resulting contract is a [flat contract](contracts.html#%28tech._flat._contract%29) if both then-contract and else-contract are [flat contracts](contracts.html#%28tech._flat._contract%29).\nFor example, the following contract enforces that if a value is a procedure, it is a thunk; otherwise it can be any (non-procedure) value:"} {"text": "# 8.5 Structure Type Property Contracts\n> ([if/c](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._if%2Fc%29%29) [procedure?](procedures.html#%28def._%28%28quote._~23~25kernel%29._procedure~3f%29%29) ([->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) [any](data-structure-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%29%29)) [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29))\nNote that the following contract is not equivalent:\n> ([or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) ([->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) [any](data-structure-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%29%29)) [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29)) ; wrong!\nThe last contract is the same as [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29) because [or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) tries [flat contracts](contracts.html#%28tech._flat._contract%29) before higher-order contracts.\nAdded in version 6.3 of package base.\n>
\n

value

"} {"text": "# 8.5 Structure Type Property Contracts\n

[failure-result/c](#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._failure-result%2Fc%29%29) : [contract?](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract~3f%29%29)

\nA contract that describes the failure result arguments of procedures such as [hash-ref](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29).\nEquivalent to ([if/c](#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._if%2Fc%29%29) [procedure?](procedures.html#%28def._%28%28quote._~23~25kernel%29._procedure~3f%29%29) ([->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) [any](data-structure-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%29%29)) [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29)).\nAdded in version 6.3 of package base.\n> ```\n(get/build-val-first-projection c)\n  →  ( →  blame? ( →  any/c ( →  any/c any/c)))\n  c : contract?"} {"text": "# 8.5 Structure Type Property Contracts\n```\nReturns the val-first projection for c.\n\nSee make-contract for more details.\n\nAdded in version 6.1.1.5 of package base.\n\n> ```\n(get/build-late-neg-projection c)\n  →  ( →  blame? ( →  any/c any/c any/c))\n  c : contract?```\n\n\nReturns the late-neg projection for c.\n\nIf c does not have a late-neg contract, then this function uses the original projection for it and logs a warning to the 'racket/contract logger.\n\nSee [make-contract](Building_New_Contract_Combinators.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fprop..rkt%29._make-contract%29%29) for more details.\n\nAdded in version 6.2.900.11 of package base.\n\n------------------------------------------------------------------------\n\n# 8.9 racket/contract/base\n\n### 8.9 [racket/contract/base]()\n\n| | |\n|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/contract/base]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe [racket/contract/base]() module provides a subset of the exports of [racket/contract](contracts.html) module. In particular, it contains everything in the\n\n- [Data-structure Contracts](data-structure-contracts.html)\n\n- [Function Contracts](function-contracts.html)\n\n- [Attaching Contracts to Values](attaching-contracts-to-values.html) and\n\n- [Contract Utilities](contract-utilities.html) sections.\n\nUnfortunately, using [racket/contract/base]() does not yield a significantly smaller memory footprint than [racket/contract](contracts.html), but it can still be useful to add contracts to libraries that [racket/contract](contracts.html) uses to implement some of the more sophisticated parts of the contract system.\n\n------------------------------------------------------------------------\n\n# 8.10 Collapsible Contracts\n\n### 8.10 Collapsible Contracts\n\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/contract/collapsible]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nAdded in version 7.1.0.10 of package base.\n\nCollapsible contracts are an optimization in the contract system designed to avoid a particular pathological build up of contract wrappers on higher-order values. The [vectorof](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fvector..rkt%29._vectorof%29%29), [vector/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fvector..rkt%29._vector%2Fc%29%29), and [->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) contract combinators support collapsing for vector contracts and function contracts for functions returning a single value.\n\nIntuitively, a collapsible contract is a tree structure. The [tree nodes](#%28def._%28%28lib._racket%2Fcontract%2Fcollapsible..rkt%29._collapsible-ho%2Fc%29%29) represent higher-order contracts (e.g., [->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29)) and the [tree leaves](#%28def._%28%28lib._racket%2Fcontract%2Fcollapsible..rkt%29._collapsible-leaf%2Fc%29%29) represent sequences of flat contracts. Two trees can collapse into one tree via the [merge](#%28def._%28%28lib._racket%2Fcontract%2Fcollapsible..rkt%29._merge%29%29) procedure, which removes unnecessary flat contracts from the leaves.\n\nFor more information on the motivation and design of collapsible contracts, see \\[[Feltey18](doc-bibliography.html#%28cite._.Feltey18%29)\\]. For the theoretical foundations, see \\[[Greenberg15](doc-bibliography.html#%28cite._.Greenberg15%29)\\].\n\nWarning: the features described in this section are experimental and may not be sufficient to implement new collapsible contracts. Implementing new collapsible contracts requires the use of unsafe chaperones and impersonators which are only supported for vector and procedure values. This documentation exists primarily to allow future maintenance of the racket/contract/collapsible library. End Warning\n\n> ```\n(get/build-collapsible-late-neg-projection c)\n  →  ( →  blame? (values ( →  any/c any/c any/c) collapsible-contract?))\n  c : contract?\n```"} {"text": "# 8.5 Structure Type Property Contracts\nReturns the collapsible-late-neg projection for c.\nIf c does not have a collapsible-late-neg projection, then this function uses the original projection for it and constructs a leaf as its collapsible representation.\n>
\n

value

\n

collapsible-contract-continuation-mark-key

 : continuation-mark-key?
\nKey used by continuation marks that are present during collapsible contract checking. The value of these marks are #t if the current contract is collapsible.\n>
\n

syntax

\n

(with-collapsible-contract-continuation-mark body ...)

\nInserts a continuation mark that informs the contract profiler that the current contract is collapsible.\n>
\n

value

\n

prop:collapsible-contract : struct-type-property?

\nStructures implementing this property are usable as collapsible contracts. The value associated with this property should be constructed by calling build-collapsible-contract-property.\n> ```\n(collapsible-contract? v) → boolean?\n  v : any/c```"} {"text": "# 8.5 Structure Type Property Contracts\nA predicate recognizing structures with the [prop:collapsible-contract](#%28def._%28%28lib._racket%2Fcontract%2Fcollapsible..rkt%29._prop~3acollapsible-contract%29%29) property.\n> ```\n(merge new-cc new-neg old-cc old-neg)  →  collapsible-contract?\n  new-cc : collapsible-contract?\n  new-neg : any/c\n  old-cc : collapsible-contract?\n  old-neg : any/c\n```\nCombine two collapsible contracts into a single collapsible contract. The new-neg and old-neg arguments are expected to be blame parties similar to those passed to a late neg projection.\n\n> ```\n(collapsible-guard cc val neg-party)  →  any/c\n  cc : collapsible-contract?\n  val : any/c\n  neg-party : any/c```\n\n\nSimilar to a [late neg projection](Building_New_Contract_Combinators.html#%28tech._late._neg._projection%29), this function guards the value val with the collapsible contract cc.\n\n> ```\n(collapsible-contract-property? v)  →  boolean?\n  v : any/c\n```\nThis predicate indicates that a value can be used as the property for prop:collapsible-contract.\n> ```\n(build-collapsible-contract-property\n   [ #:try-merge try-merge  \n    #:collapsible-guard collapsible-guard)  \n  →  collapsible-contract-property?\n   try-merge   :   ( or/c #f\n> ( → collapsible-contract?\n> any/c\n> collapsible-contract?\n> any/c\n> ( or/c #f collapsible-contract? ) ) )   =   #f\n   collapsible-guard   :   ( →  collapsible-contract? any/c any/c any/c)\n      =   ( λ ( cc v neg )\n> ( error\n> \"internal error: contract does not support `collapsible-guard`\" cc ) )```"} {"text": "# 8.5 Structure Type Property Contracts\nConstructs a collapsible contract property from a merging function and a guard. The try-merge argument is similar to [merge](#%28def._%28%28lib._racket%2Fcontract%2Fcollapsible..rkt%29._merge%29%29), but may return #f instead of a collapsible contract and may be specialized to a particular collapsible contract. The collapsible-guard argument should be specialized to the particular collapsible contract being implemented.\n>
\n

struct

\n

([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [collapsible-ho/c](#%28def._%28%28lib._racket%2Fcontract%2Fcollapsible..rkt%29._collapsible-ho%2Fc%29%29) (latest-blame missing-party latest-ctc))

  latest-blame : [blame?](Building_New_Contract_Combinators.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._blame~3f%29%29)
  missing-party : [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29)
  latest-ctc : [contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract~3f%29%29)
"} {"text": "# 8.5 Structure Type Property Contracts\nA common parent structure for collapsible contracts for higher-order values. The latest-blame field holds the blame object for the most recent contract attached. Similarly, the missing-party field holds the latest missing party passed to the contract. The latest-contract field stores the most recent contract attached to the value.\n>
\n

struct

\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [collapsible-leaf/c](#%28def._%28%28lib._racket%2Fcontract%2Fcollapsible..rkt%29._collapsible-leaf%2Fc%29%29) (proj-list
    contract-list
    blame-list
    missing-party-list))
  proj-list : ([listof](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._listof%29%29) ([->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29) [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29) [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29)))
  contract-list : ([listof](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._listof%29%29) [contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract~3f%29%29))
  blame-list : ([listof](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._listof%29%29) [blame?](Building_New_Contract_Combinators.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fblame..rkt%29._blame~3f%29%29))
  missing-party-list : ([listof](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._listof%29%29) [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29))
"} {"text": "# 8.5 Structure Type Property Contracts\nA structure representing the leaf nodes of a collapsible contract. The proj-list field holds a list of partially applied [late neg projections](Building_New_Contract_Combinators.html#%28tech._late._neg._projection%29). The contract-list, blame-list, and missing-party-list fields hold a list of contracts, blame objects, and blame missing parties respectively.\n> ```\nvalue\nimpersonator-prop:collapsible : impersonator-property?\n(has-impersonator-prop:collapsible? v)  →  boolean?\n  v : any/c\n(get-impersonator-prop:collapsible v)  →  collapsible-property?\n  v : any/c"} {"text": "# 8.5 Structure Type Property Contracts\n```\nAn impersonator property (and its accessors) that should be attached to chaperoned or impersonated values that are guarded with a collapsible contract.\n\n>
\n\n

struct

\n\n

(struct collapsible-property (c-c neg-party ref))

  c-c : collapsible-contract?
  neg-party : any/c
  ref : (or/c #f impersonator?)
\n\nThe parent struct of properties that should be attached to chaperones or impersonators of values protected with a collapsible contract. The c-c field stores the collapsible contract that is or will in the future be attached to the value. The neg-party field stores the latest missing blame party passed to the contract on the value. The ref field is mutable and stores a reference to the chaperone or impersonator to which this property is attached. This is necessary to determine whether an unknown chaperone has been attached to a value after it has been protected by a collapsible contract.\n\n>
\n\n

struct

\n\n
(struct collapsible-count-property collapsible-property (count
    prev))
  count : natural-number/c
  prev : (or/c collapsible-count-property? any/c)
\n\nThis property is associated with the impersonator-prop:collapsible property before the value completely enters the collapsible mode. These properties keep track of the number of contracts on a value in the count field, and hold a reference to the previous count property in the prev field or the original value without a contract. This allows the contract system to traverse the chain of attached contracts and merge them into a single collapsible contract to protect the original value.\n\n>
\n\n

struct

\n\n
(struct collapsible-wrapper-property collapsible-property
  (checking-wrapper)
  checking-wrapper : impersonator?
\n\nThis property is used when a value is guarded by a collapsible contract. The checking-wrapper field holds a chaperone or impersonator that dispatches to the collapsible contract stored in this property to perform any necessary contract checks. When the value receives another contract and merging happens, the checking wrapper will remain the same even though the specific collapsible contract attached to the value may change.\n\n------------------------------------------------------------------------\n\n# 8.11 Legacy Contracts\n\n### 8.11 Legacy Contracts\n\n> ```\n(make-proj-contract name proj first-order) → contract?\n  name : any/c\n   proj   :   ( or/c ( → any/c\n> any/c\n> ( list/c any/c any/c )\n> contact?\n> ( → any/c any/c ) )\n> ( → any/c\n> any/c\n> ( list/c any/c any/c )\n> contact?\n> boolean?\n> ( → any/c any/c ) ) )\n\n  first-order : ( →  any/c boolean?)```\n\n\nBuilds a contract using an old interface.\n\nModulo errors, it is equivalent to:\n\n> ```racket\n> ( make-contract\n> #:name name\n> #:first-order first-order\n> #:projection\n> ( cond\n> [ ( procedure-arity-includes? proj 5 )\n> ( lambda ( blame )\n> ( proj ( blame-positive blame )\n> ( blame-negative blame )\n> ( list ( blame-source blame ) ( blame-value blame ) )\n> ( blame-contract blame )\n> ( not ( blame-swapped? blame ) ) ) ) ]\n> [ ( procedure-arity-includes? proj 4 )\n> ( lambda ( blame )\n> ( proj ( blame-positive blame )\n> ( blame-negative blame )\n> ( list ( blame-source blame ) ( blame-value blame ) )\n> ( blame-contract blame ) ) ) ] ) )\n> ```\n\n> ```\n(raise-contract-error val\n    src        \n    pos        \n    name        \n    fmt        \n    arg ...)   →   any/c\n\n  val : any/c\n  src : any/c\n  pos : any/c\n  name : any/c\n  fmt : string?\n  arg : any/c\n```"} {"text": "# 8.5 Structure Type Property Contracts\n(parameter)\t→\t\n(-> * (symbol? symbol? (or/c syntax? (list/c any/c any/c)))\n (boolean?)\n (→ any/c any))```\nConstructs an old-style projection from a contract.\nThe resulting function accepts the information that is in a blame struct and returns a projection function that checks the contract.\n------------------------------------------------------------------------"} {"text": "# 8.12 Random generation"} {"text": "### 8.12 Random generation\n> ```\n(contract-random-generate ctc [fuel fail) → any/c\n  ctc : contract?\n  fuel : 5 = exact-nonnegative-integer?\n  fail : (or/c #f ( →  any) ( →  boolean? any)) = #f\n```\n(parameter)\t→```\n\n\nAttempts to get the vals to break their contracts (if any).\n\nUses [value-contract](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._value-contract%29%29) to determine if any of the vals have a contract and, for those that do, uses information about the contract’s shape to poke and prod at the value. For example, if the value is function, it will use the contract to tell it what arguments to supply to the value.\n\nThe argument fuel determines how hard [contract-exercise](#%28def._%28%28lib._racket%2Fcontract..rkt%29._contract-exercise%29%29) tries to break the values. It controls both the number of exercise iterations and the size of the intermediate values generated during the exercises.\n\nThe argument shuffle? controls whether [contract-exercise](#%28def._%28%28lib._racket%2Fcontract..rkt%29._contract-exercise%29%29) randomizes the exercise order or not. If shuffle? is not #f, [contract-exercise](#%28def._%28%28lib._racket%2Fcontract..rkt%29._contract-exercise%29%29) would shuffle the order of the contracts in each exercise iteration.\n\nExamples:\n\n> ```racket\n> > ( define/contract ( returns-false x ) ( -> integer? integer? ) ; does not obey its contract #f )\n> > ( contract-exercise returns-false )\n> returns-false: broke its own contract\n> promised: integer?\n> produced: #f\n> in: the range of\n> (-> integer? integer?)\n> contract from: (function returns-false)\n> blaming: (function returns-false)\n> (assuming the contract is correct)\n> at: eval:2:0\n> > ( define/contract ( calls-its-argument-with-eleven f ) ( -> ( -> integer? integer? ) boolean? ) ; f returns an integer, but ; we're supposed to return a boolean ( f 11 ) )\n> > ( contract-exercise calls-its-argument-with-eleven )\n> calls-its-argument-with-eleven: broke its own contract\n> promised: boolean?\n> produced: 11\n> in: the range of\n> (-> (-> integer? integer?) boolean?)\n> contract from:\n> (function calls-its-argument-with-eleven)\n> blaming: (function calls-its-argument-with-eleven)\n> (assuming the contract is correct)\n> at: eval:4:0\n> ```\n\nChanged in version 7.0.0.18 of package base: Added the shuffle? optional argument.\n\n> ```\n(contract-random-generate/choose c fuel)  →  (or/c #f ( →  c))\n  c : contract?\n  fuel : exact-nonnegative-integer?\n```"} {"text": "# 8.12 Random generation\nThis function is like contract-random-generate, but it is intended to be used with combinators that generate values based on sub-contracts they have. It must be called when contract-random-generate (and contract-exercise) creates the generators. To be more precise, contract-random-generate/choose is available only for the generate and exercise arguments in build-contract-property, build-chaperone-contract-property or build-flat-contract-property and only during the dynamic extent of the call to generate (and exercise). That is, after it receives the c and fuel arguments and before it returns the thunk (or the exerciser).\ncontract-random-generate/choose will never fail, but it might escape back to an enclosing call or to the original call to contract-random-generate.\nIt chooses one of several possible generation strategies, and thus it may not actually use the generator associated with c, but might instead use a stashed value that matches c that it knows about via contract-random-generate-stash.\nAdded in version 6.1.1.5 of package base.\n>
\n

value

\n

contract-random-generate-fail : contract-random-generate-fail?

\nAn atomic value that is used to indicate that a generator failed to generate a value.\nAdded in version 6.1.1.5 of package base.\n> ```\n(contract-random-generate-fail? v) → boolean?\n  v : any/c```"} {"text": "# 8.12 Random generation\nA predicate to recognize [contract-random-generate-fail](#%28def._%28%28lib._racket%2Fcontract..rkt%29._contract-random-generate-fail%29%29).\nAdded in version 6.1.1.5 of package base.\n> ```\n(contract-random-generate-env? v)  →  boolean?\n  v : any/c\n```\n(parameter)\t→```\n\n\nThis should be called with values that the program under test supplies during contract generation. For example, when ([->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) ([->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29) [integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._integer~3f%29%29) [integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._integer~3f%29%29)) [integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._integer~3f%29%29)) is generated, it may call its argument function. That argument function may return an integer and, if so, that integer should be saved by calling [contract-random-generate-stash](#%28def._%28%28lib._racket%2Fcontract..rkt%29._contract-random-generate-stash%29%29), so it can be used by other integer generators.\n\nAdded in version 6.1.1.5 of package base.\n\n> ```\n(contract-random-generate-get-current-environment)\t→\n```\nReturns the environment currently being used for generation. This function can be called only during the dynamic extent of contract generation. It is intended to be grabbed during the construction of a contract generator and then used with contract-random-generate-stash while generation is happening."} {"text": "# 8.12 Random generation\nAdded in version 6.1.1.5 of package base.\n------------------------------------------------------------------------"} {"text": "# 9 Pattern Matching"} {"text": "## 9 Pattern Matching\n> > > \"+\"Pattern Matching in The Racket Guide introduces pattern matching.\nThe match form and related forms support general pattern matching on Racket values. See also Regular Expressions for information on regular-expression matching on strings, bytes, and streams.\n| | |\n|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/match]()) |  package: base |\nThe bindings documented in this section are provided by the [racket/match]() and racket libraries, but not racket/base.\n>
\n

syntax

"} {"text": "# 9 Pattern Matching\n

(match val-expr clause ...)

 
clause = [pat option=> option ... body ...+]
     
option=> = 
  | (=> id)
     
option = #:when cond-expr
  | #:do [do-body ...]
"} {"text": "# 9 Pattern Matching\nFinds the first pat that matches the result of val-expr, and evaluates the corresponding bodys with bindings introduced by pat (if any). Bindings introduced by pat are not available in other parts of pat. The last body in the matching clause is evaluated in tail position with respect to the match expression.\nTo find a match, the clauses are tried in order. If no clause matches, then the exn:misc:match? exception is raised.\nAn optional #:when cond-expr specifies that the pattern should only match if cond-expr produces a true value. cond-expr is in the scope of all of the variables bound in pat. cond-expr must not mutate the object being matched before calling the failure procedure, otherwise the behavior of matching is unpredictable. See also failure-cont, which is a lower-level mechanism achieving the same ends.\nExamples:\n> ```racket\n> > ( define ( m x ) ( match x [ ( list a b c ) #:when ( = 6 ( + a b c ) ) ' sum-is-six ] [ ( list a b c ) ' sum-is-not-six ] ) )\n> > ( m ' ( 1 2 3 ) )\n> 'sum-is-six\n> > ( m ' ( 2 3 4 ) )\n> 'sum-is-not-six\n> ```\nAn optional #:do \\[do-body ...\\] executes do-body forms. In particular, the forms may introduce definitions that are visible in the remaining options and the main clause body. Both #:when and #:do options may appear multiple times\nExamples:"} {"text": "# 9 Pattern Matching\n> ```racket\n> > ( define ( m x ) ( match x [ ( list a b c ) #:do [ ( define sum ( + a b c ) ) ] #:when ( > sum 6 ) ( format \"the sum, which is ~a, is greater than 6\" sum ) ] [ ( list a b c ) ' sum-is-not-greater-than-six ] ) )\n> > ( m ' ( 1 2 3 ) )\n> 'sum-is-not-greater-than-six\n> > ( m ' ( 2 3 4 ) )\n> \"the sum, which is 9, is greater than 6\"\n> ```\nAn optional (=> id), which must appear immediately after pat, is bound to a failure procedure of zero arguments. id is visible in all clause options and the clause body. If this procedure is invoked, it escapes back to the pattern matching expression, and resumes the matching process as if the pattern had failed to match. The bodys must not mutate the object being matched before calling the failure procedure, otherwise the behavior of matching is unpredictable.\nExamples:\n> ```racket\n> > ( define ( m x ) ( match x [ ( list a b c ) ( => exit ) ( f x exit ) ] [ ( list a b c ) ' sum-is-not-six ] ) )\n> > ( define ( f x exit ) ( if ( = 6 ( apply + x ) ) ' sum-is-six ( exit ) ) )\n> > ( m ' ( 1 2 3 ) )\n> 'sum-is-six\n> > ( m ' ( 2 3 4 ) )\n> 'sum-is-not-six\n> ```\nThe grammar of pat is as follows, where non-italicized identifiers are recognized symbolically (i.e., not by binding)."} {"text": "# 9 Pattern Matching\n| | | | | | | |\n|---------|-----|-----|-----|-----------------------------------------|-----|----------------------------------------------------------------------------------------------------------------------------------|\n| pat |   | ::= |   | id |   | match anything, bind identifier |\n|   |   |  \\| |   | (var id) |   | match anything, bind identifier |\n|   |   |  \\| |   | \\_ |   | match anything |\n|   |   |  \\| |   | literal |   | match literal |\n|   |   |  \\| |   | (quote datum) |   | match equal? value |\n|   |   |  \\| |   | (list lvp ...) |   | match sequence of lvps |\n|   |   |  \\| |   | (list-rest lvp ... pat) |   | match lvps consed onto a pat |\n|   |   |  \\| |   | (list\\* lvp ... pat) |   | match lvps consed onto a pat |\n|   |   |  \\| |   | (list-no-order pat ...) |   | match pats in any order |\n|   |   |  \\| |   | (list-no-order pat ... lvp) |   | match pats in any order |\n|   |   |  \\| |   | (vector lvp ...) |   | match vector of pats |\n|   |   |  \\| |   | (hash expr pat ... ... ht-opt) |   | match hash table |\n|   |   |  \\| |   | (hash\\* \\[expr pat kv-opt\\] ... ht-opt) |   | match hash table |\n|   |   |  \\| |   | (hash-table (pat pat) ...) |   | match hash table - deprecated |\n|   |   |  \\| |   | (hash-table (pat pat) ...+ ooo) |   | match hash table - deprecated |\n|   |   |  \\| |   | (cons pat pat) |   | match pair of pats |\n|   |   |  \\| |   | (mcons pat pat) |   | match mutable pair of pats |\n|   |   |  \\| |   | (box pat) |   | match boxed pat |\n|   |   |  \\| |   | (struct-id pat ...) |   | match struct-id instance |\n|   |   |  \\| |   | (struct struct-id (pat ...)) |   | match struct-id instance |\n|   |   |  \\| |   | (regexp rx-expr) |   | match string |\n|   |   |  \\| |   | (regexp rx-expr pat) |   | match string, result with pat |\n|   |   |  \\| |   | (pregexp px-expr) |   | match string |\n|   |   |  \\| |   | (pregexp px-expr pat) |   | match string, result with pat |\n|   |   |  \\| |   | (and pat ...) |   | match when all pats match |\n|   |   |  \\| |   | (or pat ...) |   | match when any pat match |\n|   |   |  \\| |   | (not pat ...) |   | match when no pat matches |\n|   |   |  \\| |   | (app expr pats ...) |   | match (expr value) output values to pats |\n|   |   |  \\| |   | (? expr pat ...) |   | match if (expr value) and pats |\n|   |   |  \\| |   | (quasiquote qp) |   | match a quasipattern |\n|   |   |  \\| |   | derived-pattern |   | match using extension |\n| literal |   | ::= |   | #t |   | match true |\n|   |   |  \\| |   | #f |   | match false |\n|   |   |  \\| |   | string |   | match equal? string |\n|   |   |  \\| |   | bytes |   | match equal? byte string |\n|   |   |  \\| |   | number |   | match equal? number |\n|   |   |  \\| |   | char |   | match equal? character |\n|   |   |  \\| |   | keyword |   | match equal? keyword |\n|   |   |  \\| |   | regexp |   | match equal? regexp literal |\n|   |   |  \\| |   | pregexp |   | match equal? pregexp literal |\n| lvp |   | ::= |   | pat ooo |   | greedily match pat instances |\n|   |   |  \\| |   | pat |   | match pat |\n| qp |   | ::= |   | literal |   | match literal |\n|   |   |  \\| |   | id |   | match symbol |\n|   |   |  \\| |   | (qp ...) |   | match sequences of qps |\n|   |   |  \\| |   | (qp ... . qp) |   | match qps ending qp |\n|   |   |  \\| |   | (qp ooo . qp) |   | match qps beginning with repeated qp |\n|   |   |  \\| |   | #(qp ...) |   | match vector of qps |\n|   |   |  \\| |   | #&qp |   | match boxed qp |\n|   |   |  \\| |   | #s(prefab-key qp ...) |   | match prefab struct with qp fields |\n|   |   |  \\| |   | ,pat |   | match pat |\n|   |   |  \\| |   | ,@(list lvp ...) |   | match lvps, spliced |\n|   |   |  \\| |   | ,@(list-rest lvp ... pat) |   | match lvps plus pat, spliced |\n|   |   |  \\| |   | ,@'qp |   | match list-matching qp, spliced |\n| ooo |   | ::= |   | ... |   | zero or more; ... is literal |\n|   |   |  \\| |   | \\_\\_\\_ |   | zero or more |\n|   |   |  \\| |   | ..k |   | k or more |\n|   |   |  \\| |   | \\_\\_k |   | k or more |\n| kv-opt |   | ::= |   | |   | key must exist |\n|   |   |  \\| |   | #:default def-expr |   | key may not exist; match def-expr with the value pattern |\n| ht-opt |   | ::= |   | |   | default mode |\n|   |   |  \\| |   | #:closed |   | closed to extension mode |\n|   |   |  \\| |   | #:open |   | open to extension mode |\n|   |   |  \\| |   | #:rest pat |   | residue mode |"} {"text": "# 9 Pattern Matching\nIn more detail, patterns match as follows:\n- \nid (excluding the reserved names \\_, ..., \\_\\_\\_, ..k, and \\_\\_k for non-negative integers k)\n> > > Unlike in cond and case, else is not a keyword in match. Use the \\_ pattern for the “else” clause.\nor (var id) — matches anything, and binds id to the matching values. If an id is used multiple times within a pattern, the corresponding matches must be the same according to (match-equality-test), except that instances of an id in different or and not sub-patterns are independent. The binding for id is not available in other parts of the same pattern.\nExamples:\n> ```racket\n> > ( match ' ( 1 2 3 ) [ ( list a b a ) ( list a b ) ] [ ( list a b c ) ( list c b a ) ] )\n> '(3 2 1)\n> > ( match ' ( 1 ( x y z ) 1 ) [ ( list a b a ) ( list a b ) ] [ ( list a b c ) ( list c b a ) ] )\n> '(1 (x y z))\n> > ( match #f [ else ( cond [ #f ' not-evaluated ] [ else ' also-not-evaluated ] ) ] )\n> ```\n- \\_ — matches anything, without binding any identifiers.\nExample:\n> ```racket\n> > ( match ' ( 1 2 3 ) [ ( list _ _ a ) a ] )\n> 3\n> ```\n- #t, #f, string, bytes, number, char, or (quote datum) — matches an equal? constant.\nExample:\n> ```racket\n> > ( match \"yes\" [ \"no\" #f ] [ \"yes\" #t ] )\n> #t\n> ```\n- (list lvp ...) — matches a list of elements. In the case of (list pat ...), the pattern matches a list with as many elements as pats, and each element must match the corresponding pat. In the more general case, each lvp corresponds to a “spliced” list of greedy matches."} {"text": "# 9 Pattern Matching\nFor spliced lists, ... and \\_\\_\\_ are aliases for zero or more matches. The ..k and \\_\\_k forms are also aliases, specifying k or more matches. Pattern variables that precede these splicing operators are bound to lists of matching forms.\nExamples:\n> ```racket\n> > ( match ' ( 1 2 3 ) [ ( list a b c ) ( list c b a ) ] )\n> '(3 2 1)\n> > ( match ' ( 1 2 3 ) [ ( list 1 a ... ) a ] )\n> '(2 3)\n> > ( match ' ( 1 2 3 ) [ ( list 1 a ..3 ) a ] [ _ ' else ] )\n> 'else\n> > ( match ' ( 1 2 3 4 ) [ ( list 1 a ..3 ) a ] [ _ ' else ] )\n> '(2 3 4)\n> > ( match ' ( 1 2 3 4 5 ) [ ( list 1 a ..3 5 ) a ] [ _ ' else ] )\n> '(2 3 4)\n> > ( match ' ( 1 ( 2 ) ( 2 ) ( 2 ) 5 ) [ ( list 1 ( list a ) ..3 5 ) a ] [ _ ' else ] )\n> '(2 2 2)\n> ```\n- (list-rest lvp ... pat) or (list\\* lvp ... pat) — similar to a list pattern, but the final pat matches the “rest” of the list after the last lvp. In fact, the matched value can be a non-list chain of pairs (i.e., an “improper list”) if pat matches non-list values.\nExamples:\n> ```racket\n> > ( match ' ( 1 2 3 . 4 ) [ ( list-rest a b c d ) d ] )\n> 4\n> > ( match ' ( 1 2 3 . 4 ) [ ( list-rest a ... d ) ( list a d ) ] )\n> '((1 2 3) 4)\n> ```\n- (list-no-order pat ...) — similar to a list pattern, but the elements to match each pat can appear in the list in any order.\nExample:\n> ```racket\n> > ( match ' ( 1 2 3 ) [ ( list-no-order 3 2 x ) x ] )\n> 1\n> ```"} {"text": "# 9 Pattern Matching\n> > > Unlike other patterns, list-no-order doesn’t allow duplicate identifiers between subpatterns. For example the patterns (list-no-order x 1 x) and (list-no-order x 1 x ...) both produce syntax errors.\n- (list-no-order pat ... lvp) — generalizes list-no-order to allow a pattern that matches multiple list elements that are interspersed in any order with matches for the other patterns.\nExample:\n> ```racket\n> > ( match ' ( 1 2 3 4 5 6 ) [ ( list-no-order 6 2 y ... ) y ] )\n> '(1 3 4 5)\n> ```\n- (vector lvp ...) — like a list pattern, but matching a vector.\nExample:\n> ```racket\n> > ( match # ( 1 ( 2 ) ( 2 ) ( 2 ) 5 ) [ ( vector 1 ( list a ) ..3 5 ) a ] )\n> '(2 2 2)\n> ```\n- (hash expr pat ... ... ht-opt) — matches against a hash table where expr matches a key and pat matches a corresponding value.\nExamples:\n> ```racket\n> > ( match ( hash \"aa\" 1 \"b\" 2 ) [ ( hash \"b\" b ( string-append \"a\" \"a\" ) a ) ( list b a ) ] )\n> '(2 1)\n> > ( match ( hash \"aa\" 1 \"b\" 2 ) [ ( hash \"b\" _ \"c\" _ ) ' matched ] [ _ ' not-matched ] )\n> 'not-matched\n> ```\nThe key matchings use the key comparator of the matching hash table.\nExamples:\n> ```racket\n> > ( let ( [ k ( string-append \"a\" \"b\" ) ] ) ( match ( hasheq \"ab\" 1 ) [ ( hash k v ) ' matched ] [ _ ' not-matched ] ) )\n> 'not-matched\n> > ( let ( [ k ( string-append \"a\" \"b\" ) ] ) ( match ( hasheq k 1 ) [ ( hash k v ) ' matched ] [ _ ' not-matched ] ) )\n> 'matched\n> ```\nThe behavior of residue key-value entries in the hash table value depends on ht-opt."} {"text": "# 9 Pattern Matching\nWhen ht-opt is not provided or when it is #:closed, all of the keys in the hash table value must be matched. I.e., the matching is closed to extension.\nExample:\n> ```racket\n> > ( match ( hash \"a\" 1 \"b\" 2 ) [ ( hash \"b\" _ ) ' matched ] [ _ ' not-matched ] )\n> 'not-matched\n> ```\nWhen ht-opt is #:open, there can be keys in the hash table value that are not specified in the pattern. I.e., the matching is open to extension.\nExample:\n> ```racket\n> > ( match ( hash \"a\" 1 \"b\" 2 ) [ ( hash \"b\" _ #:open ) ' matched ] [ _ ' not-matched ] )\n> 'matched\n> ```\nWhen ht-opt is #:rest pat, pat is further matched against the residue hash table. If the matching hash table is immutable, this residue matching is efficient. Otherwise, the matching hash table will be copied, which could be expensive.\nExample:\n> ```racket\n> > ( match ( hash \"a\" 1 \"b\" 2 ) [ ( hash \"b\" _ #:rest ( hash \"a\" a ) ) a ] [ _ #f ] )\n> 1\n> ```\nMany key exprs could evaluate to the same value.\nExample:\n> ```racket\n> > ( match ( hash \"a\" 1 \"b\" 2 ) [ ( hash \"b\" _ \"b\" 2 \"a\" _ ) ' matched ] [ _ ' not-matched ] )\n> 'matched\n> ```\n- (hash\\* \\[expr pat kv-opt\\] ... ht-opt) — similar to hash, but with the following differences:\n- The key-value pattern must be grouped syntactically.\n- If ht-opt is not specified, it behaves like #:open (as opposed to #:closed).\n- If kv-opt is specified with #:default def-expr, and the key does not exist in the hash table value, then the default value from def-expr will be matched against the value pattern, instead of immediately failing to match.\nExamples:"} {"text": "# 9 Pattern Matching\n> ```racket\n> > ( match ( hash \"a\" 1 \"b\" 2 ) [ ( hash* [ \"b\" b ] [ \"a\" a ] ) ( list b a ) ] )\n> '(2 1)\n> > ( match ( hash \"a\" 1 \"b\" 2 ) [ ( hash* [ \"b\" b ] ) ' matched ] [ _ ' not-matched ] )\n> 'matched\n> > ( match ( hash \"a\" 1 \"b\" 2 ) [ ( hash* [ \"a\" a #:default 42 ] [ \"c\" c #:default 100 ] ) ( list a c ) ] [ _ #f ] )\n> '(1 100)\n> ```\n- (hash-table (pat pat) ...) — This pattern is deprecated because it can be incorrect. However, many programs rely on the incorrect behavior, so we still provide this pattern for backward compatibility reasons.\nSimilar to list-no-order, but matching against hash table’s key–value pairs.\nExample:\n> ```racket\n> > ( match #hash ( ( \"a\" . 1 ) ( \"b\" . 2 ) ) [ ( hash-table ( \"b\" b ) ( \"a\" a ) ) ( list b a ) ] )\n> '(2 1)\n> ```\n- (hash-table (pat pat) ...+ ooo) — This pattern is deprecated because it can be incorrect. However, many programs rely on the incorrect behavior, so we still provide this pattern for backward compatibility reasons.\nGeneralizes hash-table to support a final repeating pattern.\nExample:\n> ```racket\n> > ( match #hash ( ( \"a\" . 1 ) ( \"b\" . 2 ) ) [ ( hash-table ( key val ) ... ) key ] )\n> '(\"b\" \"a\")\n> ```\n- (cons pat1 pat2) — matches a pair value.\nExample:\n> ```racket\n> > ( match ( cons 1 2 ) [ ( cons a b ) ( + a b ) ] )\n> 3\n> ```\n- (mcons pat1 pat2) — matches a mutable pair value.\nExample:\n> ```racket\n> > ( match ( mcons 1 2 ) [ ( cons a b ) ' immutable ] [ ( mcons a b ) ' mutable ] )\n> 'mutable\n> ```\n- (box pat) — matches a boxed value.\nExample:\n> ```racket\n> > ( match #& 1 [ ( box a ) a ] )\n> 1\n> ```"} {"text": "# 9 Pattern Matching\n- (struct-id pat ...) or (struct struct-id (pat ...)) — matches an instance of a structure type named struct-id, where each field in the instance matches the corresponding pat. See also struct*.\nUsually, struct-id is defined with struct. More generally, struct-id must be bound to expansion-time information for a structure type (see Structure Type Transformer Binding), where the information includes at least a predicate binding and field accessor bindings corresponding to the number of field pats. In particular, a module import or a unit import with a signature containing a struct declaration can provide the structure type information.\nExamples:\n> ```racket\n> ( struct tree ( val left right ) )\n> > ( match ( tree 0 ( tree 1 #f #f ) #f ) [ ( tree a ( tree b _ _ ) _ ) ( list a b ) ] )\n> '(0 1)\n> ```\n- (struct struct-id _) — matches any instance of struct-id, without regard to contents of the fields of the instance.\n- (regexp rx-expr) — matches a string that matches the regexp pattern produced by rx-expr, where rx-expr can be either a regexp, a pregexp, a byte-regexp, a byte-pregexp, a string, or a byte string. A string and byte string value is converted to a pattern using regexp and byte-regexp respectively. See Regular Expressions for more information about regexps.\nExamples:"} {"text": "# 9 Pattern Matching\n> ```racket\n> > ( match \"apple\" [ ( regexp #rx\"p+\" ) ' yes ] [ _ ' no ] )\n> 'yes\n> > ( match \"banana\" [ ( regexp #px\"(na){2}\" ) ' yes ] [ _ ' no ] )\n> 'yes\n> > ( match \"banana\" [ ( regexp \"(na){2}\" ) ' yes ] [ _ ' no ] )\n> 'no\n> > ( match #\"apple\" [ ( regexp #rx#\"p+\" ) ' yes ] [ _ ' no ] )\n> 'yes\n> > ( match #\"banana\" [ ( regexp #px#\"(na){2}\" ) ' yes ] [ _ ' no ] )\n> 'yes\n> > ( match #\"banana\" [ ( regexp #\"(na){2}\" ) ' yes ] [ _ ' no ] )\n> 'no\n> ```\n- (regexp rx-expr pat) — extends the regexp form to further constrain the match where the result of regexp-match is matched against pat.\nExamples:\n> ```racket\n> > ( match \"apple\" [ ( regexp #rx\"p+(.)\" ( list _ \"l\" ) ) ' yes ] [ _ ' no ] )\n> 'yes\n> > ( match \"append\" [ ( regexp #rx\"p+(.)\" ( list _ \"l\" ) ) ' yes ] [ _ ' no ] )\n> 'no\n> ```\n- (pregexp rx-expr) or (pregexp rx-expr pat) — like the regexp patterns, but rx-expr must be either a pregexp, a byte-pregexp, a string, or a byte string. A string and byte string value is converted to a pattern using pregexp and byte-pregexp respectively.\n- (and pat ...) — matches if all of the pats match. This pattern is often used as (and id pat) to bind id to the entire value that matches pat. The pats are matched in the order that they appear.\nExample:\n> ```racket\n> > ( match ' ( 1 ( 2 3 ) 4 ) [ ( list _ ( and a ( list _ ... ) ) _ ) a ] )\n> '(2 3)\n> ```\n- (or pat ...) — matches if any of the pats match. Each pat must bind the same set of identifiers.\nExample:\n> ```racket\n> > ( match ' ( 1 2 ) [ ( or ( list a 1 ) ( list a 2 ) ) a ] )\n> 1\n> ```"} {"text": "# 9 Pattern Matching\n- (not pat ...) — matches when none of the pats match, and binds no identifiers.\nExamples:\n> ```racket\n> > ( match ' ( 1 2 3 ) [ ( list ( not 4 ) ... ) ' yes ] [ _ ' no ] )\n> 'yes\n> > ( match ' ( 1 4 3 ) [ ( list ( not 4 ) ... ) ' yes ] [ _ ' no ] )\n> 'no\n> ```\n- (app expr pats ...) — applies expr to the value to be matched; each result of the application is matched against one of the pats, respectively.\nExamples:\n> ```racket\n> > ( match ' ( 1 2 ) [ ( app length 2 ) ' yes ] )\n> 'yes\n> > ( match \"3.14\" [ ( app string → number ( ? number? pi ) ) ` ( I got , pi ) ] )\n> '(I got 3.14)\n> > ( match ' ( 1 2 ) [ ( app ( lambda ( v ) ( split-at v 1 ) ) ' ( 1 ) ' ( 2 ) ) ' yes ] )\n> 'yes\n> > ( match ' ( 1 2 3 ) [ ( app ( λ ( ls ) ( apply values ls ) ) x y ( ? odd? z ) ) ( list ' yes x y z ) ] )\n> '(yes 1 2 3)\n> ```\n- (? expr pat ...) — applies expr to the value to be matched, and checks whether the result is a true value; the additional pats must also match; i.e., ? combines a predicate application and an and pattern. However, ?, unlike and, guarantees that expr is matched before any of the pats.\n> > > The expr procedure may be called more than once on identical input (although this happens only rarely), and the order in which calls to expr are made should not be relied upon.\nExample:\n> ```racket\n> > ( match ' ( 1 3 5 ) [ ( list ( ? odd? ) ... ) ' yes ] )\n> 'yes\n> ```\n- (quasiquote qp) — introduces a quasipattern, in which identifiers match symbols. Like the quasiquote expression form, unquote and unquote-splicing escape back to normal patterns.\nExample:"} {"text": "# 9 Pattern Matching\n> ```racket\n> > ( match ' ( 1 2 3 ) [ ` ( 1 , a , ( ? odd? b ) ) ( list a b ) ] )\n> '(2 3)\n> ```\n- derived-pattern — matches a pattern defined by a macro extension via define-match-expander.\nNote that the matching process may destructure the input multiple times, and may evaluate expressions embedded in patterns such as (app expr pat) in arbitrary order, or multiple times. Therefore, such expressions must be safe to call multiple times, or in an order other than they appear in the original program.\nChanged in version 8.9.0.5 of package base: Added a support for #:do. \nChanged in version 8.11.1.10: Added the hash and hash\\* patterns."} {"text": "### 9.1 Additional Matching Forms\n>
\n

syntax

\n

(match* (val-expr ...+) clause* ...)

 
clause* = [(pat ...+) option=> option ... body ...+]
\nMatches a sequence of values against each clause in order, matching only when all patterns in a clause match. Each clause must have the same number of patterns as the number of val-exprs.\nExamples:\n> ```racket\n> > ( match* ( 1 2 3 ) [ ( _ ( ? number? ) x ) ( add1 x ) ] )\n> 4\n> > ( match* ( 15 17 ) [ ( ( ? number? a ) ( ? number? b ) ) #:when ( = ( + a 2 ) b ) ' diff-by-two ] )\n> 'diff-by-two\n> ```\n>
\n

syntax

\n

(match/values expr clause* clause* ...)

\nIf expr evaluates to n values, then match all n values against the patterns in clause\\* .... Each clause must contain exactly n patterns. At least one clause is required to determine how many values to expect from expr.\nExample:"} {"text": "### 9.1 Additional Matching Forms\n> ```racket\n> > ( match/values ( values 1 2 3 ) [ ( a ( ? number? b ) ( ? odd? c ) ) ( + a b c ) ] )\n> 6\n> ```\n> ```\nsyntax\n(define/match (head args)\n> match*-clause ... )\nhead   =   id\n    |   (head args)\nargs   =   arg ...\n    |   arg ... . rest-id\narg   =   arg-id\n    |   [arg-id default-expr]\n    |   keyword arg-id\n    |   keyword [arg-id default-expr]\nmatch*-clause   =   [(pat ...+) option=> option ... body ...+]```\nBinds id to a procedure that is defined by pattern matching clauses using [match*](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%2A%29%29). Each clause takes a sequence of patterns that correspond to the arguments in the function header. The arguments are ordered as they appear in the function header for matching purposes.\nExamples:\n> ```racket\n> ( define/match ( fact n ) [ ( 0 ) 1 ] [ ( n ) ( * n ( fact ( sub1 n ) ) ) ] )\n> > ( fact 5 )\n> 120\n> ```\nThe function header may also contain optional or keyword arguments, may have curried arguments, and may also contain a rest argument.\nExamples:\n> ```racket\n> ( define/match ( ( f x ) #:y [ y ' ( 1 2 3 ) ] ) [ ( ( regexp #rx\"p+\" ) ` ( , a 2 3 ) ) a ] [ ( _ _ ) #f ] )\n> > ( ( f \"ape\" ) #:y ' ( 5 2 3 ) )\n> 5\n> > ( ( f \"dog\" ) )\n> #f\n> ( define/match ( g x y . rst ) [ ( 0 0 ' ( ) ) #t ] [ ( 5 5 ' ( 5 5 ) ) #t ] [ ( _ _ _ ) #f ] )\n> > ( g 0 0 )\n> #t\n> > ( g 5 5 5 5 )\n> #t\n> > ( g 1 2 )\n> #f\n> ```"} {"text": "### 9.1 Additional Matching Forms\n>
\n

syntax

\n

([match-lambda](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-lambda%29%29) clause ...)

\n

syntax

\n

([match-λ](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-~ce~bb%29%29) clause ...)

\nEquivalent to ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) (id) ([match](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%29%29) id clause [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29))).\nChanged in version 8.13.0.5 of package base: Added [match-λ](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-~ce~bb%29%29).\n>
\n

syntax

"} {"text": "### 9.1 Additional Matching Forms\n

([match-lambda*](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-lambda%2A%29%29) clause ...)

\n

syntax

\n

([match-λ*](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-~ce~bb%2A%29%29) clause ...)

\nEquivalent to ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) lst ([match](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%29%29) lst clause [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29))).\nChanged in version 8.13.0.5 of package base: Added [match-λ*](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-~ce~bb%2A%29%29).\n>
\n

syntax

\n

([match-lambda**](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-lambda%2A%2A%29%29) clause* ...)

\n

syntax

"} {"text": "### 9.1 Additional Matching Forms\n

([match-λ**](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-~ce~bb%2A%2A%29%29) clause* ...)

\nEquivalent to ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) (args [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) ([match*](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%2A%29%29) (args [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) clause\\* [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29))), where the number of args [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) is computed from the number of patterns appearing in each of the clause\\*.\nChanged in version 8.13.0.5 of package base: Added [match-λ**](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-~ce~bb%2A%2A%29%29).\n>
\n

syntax

\n

([match-let](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-let%29%29) ([pat expr] ...) body ...+)

"} {"text": "### 9.1 Additional Matching Forms\nGeneralizes [let](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%29%29) to support pattern bindings. Each expr is matched against its corresponding pat (the match must succeed), and the bindings that pat introduces are visible in the bodys.\nExample:\n> ```racket\n> > ( match-let ( [ ( list a b ) ' ( 1 2 ) ] [ ( vector x ... ) # ( 1 2 3 4 ) ] ) ( list b a x ) )\n> '(2 1 (1 2 3 4))\n> ```\n>
\n

syntax

\n

([match-let*](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-let%2A%29%29) ([pat expr] ...) body ...+)

\nLike [match-let](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-let%29%29), but generalizes [let*](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%2A%29%29), so that the bindings of each pat are available in each subsequent expr.\nExample:\n> ```racket\n> > ( match-let* ( [ ( list a b ) ' ( # ( 1 2 3 4 ) 2 ) ] [ ( vector x ... ) a ] ) x )\n> '(1 2 3 4)\n> ```\n>
\n

syntax

\n

([match-let-values](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-let-values%29%29) ([(pat ...) expr] ...) body ...+)

"} {"text": "### 9.1 Additional Matching Forms\nLike [match-let](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-let%29%29), but generalizes [let-values](let.html#%28form._%28%28quote._~23~25kernel%29._let-values%29%29).\n>
\n

syntax

\n

([match-let*-values](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-let%2A-values%29%29) ([(pat ...) expr] ...) body ...+)

\nLike [match-let*](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-let%2A%29%29), but generalizes [let*-values](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%2A-values%29%29).\n>
\n

syntax

\n

([match-letrec](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-letrec%29%29) ([pat expr] ...) body ...+)

\nLike [match-let](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-let%29%29), but generalizes [letrec](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._letrec%29%29).\n>
\n

syntax

\n

([match-letrec-values](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-letrec-values%29%29) ([(pat ...) expr] ...) body ...+)

"} {"text": "### 9.1 Additional Matching Forms\nLike [match-let](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-let%29%29), but generalizes [letrec-values](let.html#%28form._%28%28quote._~23~25kernel%29._letrec-values%29%29).\nAdded in version 6.1.1.8 of package base.\n>
\n

syntax

\n

([match-define](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-define%29%29) pat expr)

\nDefines the names bound by pat to the values produced by matching against the result of expr.\nExamples:\n> ```racket\n> > ( match-define ( list a b ) ' ( 1 2 ) )\n> > b\n> 2\n> ```\n>
\n

syntax

\n

([match-define-values](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-define-values%29%29) (pat pats ...) expr)

\nLike [match-define](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-define%29%29) but for when expr produces multiple values. Like match/values, it requires at least one pattern to determine the number of values to expect.\nExamples:\n> ```racket\n> > ( match-define-values ( a b ) ( values 1 2 ) )\n> > b\n> 2\n> ```\n> ```\n(exn:misc:match? v)  →  boolean?\n  v : any/c"} {"text": "### 9.1 Additional Matching Forms\n```\n(failure-cont)\t→\t\n(-> define-match-expander syntax-list (lambda (stx) (syntax-case stx () [ (_ elts ...) #' (? syntax-list? (app syntax → list (list elts ...))) ])))```\n\n\nPredicates for values which implement the appropriate match expander properties.\n\n> ```\n(syntax-local-match-introduce stx)  →  syntax?\n  stx : syntax?\n```\n(match-equality-test)\t→\t\n(-> any/c any/c . → . any)\n(match-equality-test comp-proc) → void?\n comp-proc\t:\t\n(-> any/c any/c . → . any)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the comparison procedure used to check whether multiple uses of an identifier match the “same” value. The default is [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29).\n>
\n

syntax

\n

([match/derived](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%2Fderived%29%29) val-expr original-datum clause ...)

\n

syntax

\n

([match*/derived](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%2A%2Fderived%29%29) (val-expr ...) original-datum clause* ...)

"} {"text": "### 9.1 Additional Matching Forms\nLike [match](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%29%29) and [match*](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%2A%29%29) respectively, but includes a sub-expression to be used as the source for all syntax errors within the form. For example, [match-lambda](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-lambda%29%29) expands to [match/derived](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%2Fderived%29%29) so that errors in the body of the form are reported in terms of [match-lambda](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match-lambda%29%29) instead of [match](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%29%29)."} {"text": "### 9.3 Library Extensions\n>
\n

syntax

\n

([==](#%28form._%28%28lib._racket%2Fmatch..rkt%29._~3d~3d%29%29) val comparator)

([==](#%28form._%28%28lib._racket%2Fmatch..rkt%29._~3d~3d%29%29) val)
\nA [match expander](#%28tech._match._expander%29) which checks if the matched value is the same as val when compared by comparator. If comparator is not provided, it defaults to [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29).\nExamples:\n> ```racket\n> > ( match ( list 1 2 3 ) [ ( == ( list 1 2 3 ) ) ' yes ] [ _ ' no ] )\n> 'yes\n> > ( match ( list 1 2 3 ) [ ( == ( list 1 2 3 ) eq? ) ' yes ] [ _ ' no ] )\n> 'no\n> > ( match ( list 1 2 3 ) [ ( list 1 2 ( == 3 = ) ) ' yes ] [ _ ' no ] )\n> 'yes\n> ```\n>
\n

syntax

\n

([struct*](#%28form._%28%28lib._racket%2Fmatch..rkt%29._struct%2A%29%29) struct-id ([field pat] ...))

\nA [match](#%28form._%28%28lib._racket%2Fmatch..rkt%29._match%29%29) pattern form that matches an instance of a structure type named struct-id, where the field field in the instance matches the corresponding pat. The fields do not include those from super types.\nAny field of struct-id may be omitted, and such fields can occur in any order.\nExamples:"} {"text": "### 9.3 Library Extensions\n> ```racket\n> ( struct tree ( val left right ) ) ( struct tree* tree ( val ) )\n> > ( match ( tree 0 ( tree 1 #f #f ) #f ) [ ( struct* tree ( [ val a ] [ left ( struct* tree ( [ right #f ] [ val b ] ) ) ] ) ) ( list a b ) ] )\n> '(0 1)\n> > ( match ( tree* 0 #f #f 42 ) [ ( and ( struct* tree* ( [ val a ] ) ) ( struct* tree ( [ val b ] ) ) ) ( list a b ) ] )\n> '(42 0)\n> ```\n------------------------------------------------------------------------"} {"text": "# 10 Control Flow"} {"text": "## 10 Control Flow\n| |\n|-------------------------------------------------------------------------------------------------------------------------------------|\n|     [10.1 Multiple Values](values.html) |\n|     [10.2 Exceptions](exns.html) |\n|       [10.2.1 Error Message Conventions](exns.html#%28part._err-msg-conventions%29) |\n|       [10.2.2 Raising Exceptions](exns.html#%28part._errorproc%29) |\n|       [10.2.3 Handling Exceptions](exns.html#%28part._.Handling_.Exceptions%29) |\n|       [10.2.4 Configuring Default Handling](exns.html#%28part._.Configuring_.Default_.Handling%29) |\n|       [10.2.5 Built-in Exception Types](exns.html#%28part._.Built-in_.Exception_.Types%29) |\n|       [10.2.6 Additional Exception Functions](exns.html#%28part._.Additional_.Exception_.Functions%29) |\n|       [10.2.7 Realms and Error Message Adjusters](exns.html#%28part._err-realm%29) |\n|     [10.3 Delayed Evaluation](Delayed_Evaluation.html) |\n|       [10.3.1 Additional Promise Kinds](Delayed_Evaluation.html#%28part._.Additional_.Promise_.Kinds%29) |\n|     [10.4 Continuations](cont.html) |\n|       [10.4.1 Additional Control Operators](cont.html#%28part._.Additional_.Control_.Operators%29) |\n|     [10.5 Continuation Marks](contmarks.html) |\n|     [10.6 Breaks](breakhandler.html) |\n|     [10.7 Exiting](Exiting.html) |\n|     [10.8 Unreachable Expressions](unreachable.html) |\n|       [10.8.1 Customized Unreachable Reporting](unreachable.html#%28part._with-unreachable%29) |"} {"text": "# 10 Control Flow\n------------------------------------------------------------------------"} {"text": "# 10.1 Multiple Values"} {"text": "### 10.1 Multiple Values\nSee [Multiple Return Values](eval-model.html#%28part._values-model%29) for general information about multiple result values. In addition to [call-with-values](#%28def._%28%28quote._~23~25kernel%29._call-with-values%29%29) (described in this section), the [let-values](let.html#%28form._%28%28quote._~23~25kernel%29._let-values%29%29), [let*-values](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%2A-values%29%29), [letrec-values](let.html#%28form._%28%28quote._~23~25kernel%29._letrec-values%29%29), and [define-values](define.html#%28form._%28%28quote._~23~25kernel%29._define-values%29%29) forms (among others) create continuations that receive multiple values.\n> ```\n(values v ...) → any\n  v : any/c"} {"text": "# 10.1 Multiple Values\n```\nReturns the given vs. That is, values returns its provided arguments.\n\nExamples:\n\n> ```racket\n> > ( values 1 )\n> 1\n> > ( values 1 2 3 )\n> 1 2 3\n> > ( values )\n> ```\n\n> ```\n(call-with-values generator receiver)  →  any\n  generator : ( →  any)\n  receiver : procedure?```\n\n\nCalls generator, and passes the values that generator produces as arguments to receiver. Thus, [call-with-values](#%28def._%28%28quote._~23~25kernel%29._call-with-values%29%29) creates a continuation that accepts any number of values that receiver can accept. The receiver procedure is called in tail position with respect to the [call-with-values](#%28def._%28%28quote._~23~25kernel%29._call-with-values%29%29) call.\n\nExamples:\n\n> ```racket\n> > ( call-with-values ( lambda ( ) ( values 1 2 ) ) + )\n> 3\n> > ( call-with-values ( lambda ( ) 1 ) ( lambda ( x y ) ( + x y ) ) )\n> arity mismatch;\n> the expected number of arguments does not match the given\n> number\n> expected: 2\n> given: 1\n> ```\n\n------------------------------------------------------------------------\n\n# 10.2 Exceptions\n\n### 10.2 Exceptions\n\n> > > \"+\"[Exceptions](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=exns.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces exceptions.\n\nSee [Exceptions](eval-model.html#%28part._exn-model%29) for information on the Racket exception model. It is based on a proposal by Friedman, Haynes, and Dybvig \\[[Friedman95](doc-bibliography.html#%28cite._.Friedman95%29)\\].\n\nWhenever a primitive error occurs in Racket, an exception is raised. The value that is passed to the current [exception handler](eval-model.html#%28tech._exception._handler%29) for a primitive error is always an instance of the [exn](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn%29%29) structure type. Every [exn](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn%29%29) structure value has a message field that is a string, the primitive error message. The default exception handler recognizes exception values with the [exn?](#%28def._%28%28quote._~23~25kernel%29._exn~3f%29%29) predicate and passes the error message to the current [error display handler](#%28tech._error._display._handler%29) (see [error-display-handler](#%28def._%28%28quote._~23~25kernel%29._error-display-handler%29%29)).\n\nPrimitive procedures that accept a procedure argument with a particular required arity (e.g., [call-with-input-file](file-ports.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._call-with-input-file%29%29), [call/cc](cont.html#%28def._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._call%2Fcc%29%29)) check the argument’s arity immediately, raising [exn:fail:contract](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) if the arity is incorrect.\n\n#### 10.2.1 Error Message Conventions\n\nRacket’s error message convention is to produce error messages with the following shape:\n\n> ```racket\n> ‹ srcloc › : ‹ name › : ‹ message › ;\n> ‹ continued-message › ...\n> ‹ field › : ‹ detail ›\n> ...\n> ```\n\nThe message starts with an optional source location, ‹srcloc›, which is followed by a colon and space when present. The message continues with an optional ‹name› that usually identifies the complaining function, syntactic form, or other entity, but may also refer to an entity being complained about; the ‹name› is also followed by a colon and space when present.\n\nThe ‹message› should be relatively short, and it should be largely independent of specific values that triggered the error. More detailed explanation that requires multiple lines should continue with each line indented by a single space, in which case ‹message› should end in a semi-colon (but the semi-colon should be omitted if ‹continued-message› is not present). Message text should be lowercase—using semi-colons to separate sentences if needed, although long explanations may be better deferred to extra fields.\n\nSpecific values that triggered the error or other helpful information should appear in separate ‹field› lines, each of which is indented by two spaces. If a ‹detail› is especially long or takes multiple lines, it should start on its own line after the ‹field› label, and each of its lines should be indented by three spaces. Field names should be all lowercase.\n\nA ‹field› name should end with ... if the field provides relatively detailed information that might be distracting in common cases but useful in others. For example, when a contract failure is reported for a particular argument of a function, other arguments to the function might be shown in an “other arguments...” field. The intent is that fields whose names end in ... might be hidden by default in an environment such as DrRacket.\n\nMake ‹field› names as short as possible, relying on ‹message› or ‹continued message› text to clarify the meaning for a field. For example, prefer “given” to “given turtle” as a field name, where ‹message› is something like “given turtle is too sleepy” to clarify that “given” refers to a turtle.\n\n#### 10.2.2 Raising Exceptions\n\n> ```\n(raise v [barrier?) → any\n  v : any/c\n  barrier? : any/c = #t\n```"} {"text": "# 10.1 Multiple Values\n(parameter)\t→\t\n(-> error message-str v ...)```\nRaises the exception [exn:fail](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29), which contains an error string. The different forms produce the error string in different ways:\n- ([error](#%28def._%28%28quote._~23~25kernel%29._error%29%29) message-sym) creates a message string by concatenating \"error: \" with the string form of message-sym. Use this form sparingly.\n- ([error](#%28def._%28%28quote._~23~25kernel%29._error%29%29) message-str v [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) creates a message string by concatenating message-str with string versions of the vs (as produced by the current error value conversion handler; see [error-value->string-handler](#%28def._%28%28quote._~23~25kernel%29._error-value-~3estring-handler%29%29)). A space is inserted before each v. Use this form sparingly, because it does not conform well to Racket’s [error message conventions](#%28tech._error._message._convention%29); consider [raise-arguments-error](#%28def._%28%28quote._~23~25kernel%29._raise-arguments-error%29%29), instead.\n- ([error](#%28def._%28%28quote._~23~25kernel%29._error%29%29) who-sym format-str v [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) creates a message string equivalent to the string created by"} {"text": "# 10.1 Multiple Values\n > ([format](Writing.html#%28def._%28%28quote._~23~25kernel%29._format%29%29) ([string-append](strings.html#%28def._%28%28quote._~23~25kernel%29._string-append%29%29) \"\\~s: \" format-str) who-sym v [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29))\n When possible, use functions such as [raise-argument-error](#%28def._%28%28quote._~23~25kernel%29._raise-argument-error%29%29), instead, which construct messages that follow Racket’s [error message conventions](#%28tech._error._message._convention%29).\nIn all cases, the constructed message string is passed to [make-exn:fail](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail%29%29), and the resulting exception is raised.\nExamples:\n> ```racket\n> > ( error ' failed )\n> error: failed\n> > ( error \"failed\" 23 ' pizza ( list 1 2 3 ) )\n> failed 23 'pizza '(1 2 3)\n> > ( error ' method-a \"failed because ~a\" \"no argument supplied\" )\n> method-a: failed because no argument supplied\n> ```\n> ```\n(parameter)\t→\t\n(-> raise-user-error message-str v ...)"} {"text": "# 10.1 Multiple Values\n```\n(parameter)\t→\t\n(-> raise-argument-error name\n expected\n bad-pos\n v ...)```\n\n\nCreates an [exn:fail:contract](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) value and [raise](#%28def._%28%28quote._~23~25kernel%29._raise%29%29)s it as an exception. The name argument is used as the source procedure’s name in the error message. The expected argument is used as a description of the expected contract (i.e., as a string, but the string is intended to contain a contract expression).\n\nIn the first form, v is the value received by the procedure that does not have the expected type.\n\nIn the second form, the bad argument is indicated by an index bad-pos (counting from 0), and all of the original arguments v are provided (in order). The resulting error message names the bad argument and also lists the other arguments. If bad-pos is not less than the number of vs, the [exn:fail:contract](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nThe error message generated by [raise-argument-error](#%28def._%28%28quote._~23~25kernel%29._raise-argument-error%29%29) is adjusted via [error-contract->adjusted-string](#%28def._%28%28quote._~23~25kernel%29._error-contract-~3eadjusted-string%29%29) and then [error-message->adjusted-string](#%28def._%28%28quote._~23~25kernel%29._error-message-~3eadjusted-string%29%29) using the default 'racket realm.\n\nExamples:\n\n> ```racket\n> > ( define ( feed-machine bits ) ( unless ( integer? bits ) ( raise-argument-error ' feed-machine \"integer?\" bits ) ) \"fed the machine\" )\n> > ( feed-machine ' turkey )\n> feed-machine: contract violation\n> expected: integer?\n> given: 'turkey\n> > ( define ( feed-cow animal ) ( unless ( eq? animal ' cow ) ( raise-argument-error ' feed-cow \"'cow\" animal ) ) \"fed the cow\" )\n> > ( feed-cow ' turkey )\n> feed-cow: contract violation\n> expected: 'cow\n> given: 'turkey\n> > ( define ( feed-animals cow sheep goose cat ) ( unless ( eq? goose ' goose ) ( raise-argument-error ' feed-animals \"'goose\" 2 cow sheep goose cat ) ) \"fed the animals\" )\n> > ( feed-animals ' cow ' sheep ' dog ' cat )\n> feed-animals: contract violation\n> expected: 'goose\n> given: 'dog\n> argument position: 3rd\n> other arguments...:\n> 'cow\n> 'sheep\n> 'cat\n> ```\n\n> ```\n(parameter)\t→\t\n(-> raise-argument-error* name\n realm\n expected\n bad-pos\n v ...)\n```"} {"text": "# 10.1 Multiple Values\n(parameter)\t→\t\n(-> raise-result-error name\n expected\n bad-pos\n v ...)```\nLike [raise-argument-error](#%28def._%28%28quote._~23~25kernel%29._raise-argument-error%29%29), but the error message describe v as a “result” instead of an “argument.”\n> ```\n(parameter)\t→\t\n(-> raise-result-error* name\n realm\n expected\n bad-pos\n v ...)\n```\n(parameter)\t→```\n\n\nCreates an [exn:fail:contract](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) value and [raise](#%28def._%28%28quote._~23~25kernel%29._raise%29%29)s it as an exception. The name is used as the source procedure’s name in the error message. The message is the error message; if message contains newline characters, each extra line should be suitably indented (with one extra space at the start of each line), but it should not end with a newline character. Each field must have a corresponding v, and the two are rendered on their own line in the error message; each v is formatted using the error value conversion handler (see [error-value->string-handler](#%28def._%28%28quote._~23~25kernel%29._error-value-~3estring-handler%29%29)), unless v is a [unquoted-printing string](#%28tech._unquoted._printing._string%29), in which case the string content is [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29)ed without using the error value conversion handler. When a string produced by the error value conversion handler or in an unquoted-printing string contains a newline but does not start with a newline, then the string is started on its own line with extra spaces added before each line to indent the string content.\n\nThe error message generated by [raise-arguments-error](#%28def._%28%28quote._~23~25kernel%29._raise-arguments-error%29%29) is adjusted via [error-message->adjusted-string](#%28def._%28%28quote._~23~25kernel%29._error-message-~3eadjusted-string%29%29) using the default 'racket realm.\n\nExamples:\n\n> ```racket\n> > ( raise-arguments-error ' eat \"fish is smaller than its given meal\" \"fish\" 12 \"meal\" 13 )\n> eat: fish is smaller than its given meal\n> fish: 12\n> meal: 13\n> > ( raise-arguments-error ' eat \"not edible\" \"candidate\" ( unquoted-printing-string \"a banana made\\nof wax\" ) )\n> eat: not edible\n> candidate:\n> a banana made\n> of wax\n> ```\n\nChanged in version 8.15.0.2 of package base: Added indentation for v strings that contain newlines.\n\n> ```\n(parameter)\t→\n```"} {"text": "# 10.1 Multiple Values\n(parameter)\t→\t\n(-> or/c #f exact-integer?)```\nCreates an [exn:fail:contract](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) value and [raise](#%28def._%28%28quote._~23~25kernel%29._raise%29%29)s it as an exception to report an out-of-range error. The type-description string describes the value for which the index is meant to select an element, and index-prefix is a prefix for the word “index.” The index argument is the rejected index. The in-value argument is the value for which the index was meant. The lower-bound and upper-bound arguments specify the valid range of indices, inclusive; if upper-bound is below lower-bound, the value is characterized as “empty.” If alt-lower-bound is not #f, and if index is between alt-lower-bound and upper-bound, then the error is report as index being less than the “starting” index lower-bound.\nSince upper-bound is inclusive, a typical value is one less than the size of a collection—for example, ([sub1](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._sub1%29%29) ([vector-length](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector-length%29%29) vec)), ([sub1](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._sub1%29%29) ([length](pairs.html#%28def._%28%28quote._~23~25kernel%29._length%29%29) lst)), and so on."} {"text": "# 10.1 Multiple Values\nThe error message generated by [raise-range-error](#%28def._%28%28quote._~23~25kernel%29._raise-range-error%29%29) is adjusted via [error-message->adjusted-string](#%28def._%28%28quote._~23~25kernel%29._error-message-~3eadjusted-string%29%29) using the default 'racket realm.\nExamples:\n> ```racket\n> > ( raise-range-error ' vector-ref \"vector\" \"starting \" 5 # ( 1 2 3 4 ) 0 3 )\n> vector-ref: starting index is out of range\n> starting index: 5\n> valid range: [0, 3]\n> vector: '#(1 2 3 4)\n> > ( raise-range-error ' vector-ref \"vector\" \"ending \" 5 # ( 1 2 3 4 ) 0 3 )\n> vector-ref: ending index is out of range\n> ending index: 5\n> valid range: [0, 3]\n> vector: '#(1 2 3 4)\n> > ( raise-range-error ' vector-ref \"vector\" \"\" 3 # ( ) 0 -1 )\n> vector-ref: index is out of range for empty vector\n> index: 3\n> > ( raise-range-error ' vector-ref \"vector\" \"ending \" 1 # ( 1 2 3 4 ) 2 3 0 )\n> vector-ref: ending index is smaller than starting index\n> ending index: 1\n> starting index: 2\n> valid range: [0, 3]\n> vector: '#(1 2 3 4)\n> ```\n> ```\n(parameter)\t→\t\n(-> or/c #f exact-integer?)"} {"text": "# 10.1 Multiple Values\n```\n(parameter)\t→\t\n(-> raise-type-error name expected bad-pos v ...)```\n\n\nLike [raise-argument-error](#%28def._%28%28quote._~23~25kernel%29._raise-argument-error%29%29), but with Racket’s old formatting conventions, and where expected is used as a “type” description instead of a contract expression. Use [raise-argument-error](#%28def._%28%28quote._~23~25kernel%29._raise-argument-error%29%29) or [raise-result-error](#%28def._%28%28quote._~23~25kernel%29._raise-result-error%29%29), instead.\n\nThe error message generated by [raise-type-error](#%28def._%28%28quote._~23~25kernel%29._raise-type-error%29%29) is adjusted via [error-message->adjusted-string](#%28def._%28%28quote._~23~25kernel%29._error-message-~3eadjusted-string%29%29) using the default 'racket realm.\n\n> ```\n(parameter)\t→\n```\n(parameter)\t→\t\n(-> parameter)```\nCreates an [exn:fail:contract:arity](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3aarity%29%29) value and [raise](#%28def._%28%28quote._~23~25kernel%29._raise%29%29)s it as an exception. The name is used for the source procedure’s name in the error message."} {"text": "# 10.1 Multiple Values\nThe arity-v value must be a possible result from [procedure-arity](procedures.html#%28def._%28%28quote._~23~25kernel%29._procedure-arity%29%29), except that it does not have to be normalized (see [procedure-arity?](procedures.html#%28def._%28%28quote._~23~25kernel%29._procedure-arity~3f%29%29) for the details of normalized arities); [raise-arity-error](#%28def._%28%28quote._~23~25kernel%29._raise-arity-error%29%29) will normalize the arity and use the normalized form in the error message. If name is a procedure, its actual arity is ignored.\nThe arg-v arguments are the actual supplied arguments, which are shown in the error message (using the error value conversion handler; see [error-value->string-handler](#%28def._%28%28quote._~23~25kernel%29._error-value-~3estring-handler%29%29)); also, the number of supplied arg-vs is explicitly mentioned in the message.\nThe error message generated by [raise-arity-error](#%28def._%28%28quote._~23~25kernel%29._raise-arity-error%29%29) is adjusted via [error-message->adjusted-string](#%28def._%28%28quote._~23~25kernel%29._error-message-~3eadjusted-string%29%29) using the default 'racket realm.\nExample:\n> ```racket\n> > ( raise-arity-error ' unite ( arity-at-least 13 ) \"Virginia\" \"Maryland\" )\n> unite: arity mismatch;\n> the expected number of arguments does not match the given\n> number\n> expected: at least 13\n> given: 2\n> arguments...:\n> \"Virginia\"\n> \"Maryland\"\n> ```\n> ```\n(parameter)\t→\t\n(-> or/c symbol? procedure?)"} {"text": "# 10.1 Multiple Values\n```\n(parameter)\t→\t\n(-> or/c symbol? procedure?)```\n\n\nThe same as [raise-arity-error](#%28def._%28%28quote._~23~25kernel%29._raise-arity-error%29%29), but using the arity representation described with [procedure-arity-mask](procedures.html#%28def._%28%28quote._~23~25kernel%29._procedure-arity-mask%29%29).\n\nAdded in version 7.0.0.11 of package base.\n\n> ```\n(parameter)\t→\t\n(-> or/c symbol? procedure?)\n```\n(parameter)\t→\t\n(-> or/c symbol? #f)```\nLike [raise-arity-error](#%28def._%28%28quote._~23~25kernel%29._raise-arity-error%29%29), but reports a “result” mismatch instead of an “argument” mismatch. The name argument can be #f to omit an initial source for the error. The detail-str argument, if non-#f, should be a string that starts with a newline, since it is added near the end of the generated error message.\nThe error message generated by [raise-result-arity-error](#%28def._%28%28quote._~23~25kernel%29._raise-result-arity-error%29%29) is adjusted via [error-message->adjusted-string](#%28def._%28%28quote._~23~25kernel%29._error-message-~3eadjusted-string%29%29) using the default 'racket realm.\nExample:\n> ```racket\n> > ( raise-result-arity-error ' let-values 2 \"\\n in: example\" ' a 2.0 \"three\" )\n> let-values: result arity mismatch;\n> expected number of values not received\n> expected: 2\n> received: 3\n> in: example\n> arguments...:\n> 'a\n> 2.0\n> \"three\"\n> ```\nAdded in version 6.90.0.26 of package base.\n> ```\n(parameter)\t→\t\n(-> or/c symbol? #f)"} {"text": "# 10.1 Multiple Values\n```\n(parameter)\t→\t\n(-> or/c symbol? #f)```\n\n\nCreates an [exn:fail:syntax?](#%28def._%28%28quote._~23~25kernel%29._exn~3afail~3asyntax~3f%29%29) value and [raise](#%28def._%28%28quote._~23~25kernel%29._raise%29%29)s it as an exception. Macros use this procedure to report syntax errors.\n\nThe name argument is usually #f when expr is provided; it is described in more detail below. The message is used as the main body of the error message; if message contains newline characters, each new line should be suitably indented (with one space at the start), and it should not end with a newline character.\n\nThe optional expr argument is the erroneous source syntax object or S-expression (but the expression #f cannot be represented by itself; it must be wrapped as a [syntax object](syntax-model.html#%28tech._syntax._object%29)). The optional sub-expr argument is a syntax object or S-expression (again, #f cannot represent itself) within expr that more precisely locates the error. Both may appear in the generated error-message text if [error-print-source-location](#%28def._%28%28quote._~23~25kernel%29._error-print-source-location%29%29) is #t. Source location information in the error-message text is similarly extracted from sub-expr or expr when at least one is a syntax object and [error-print-source-location](#%28def._%28%28quote._~23~25kernel%29._error-print-source-location%29%29) is #t.\n\nIf sub-expr is provided and not #f, it is used (in syntax form) for the exprs field of the generated exception record, else the expr is used if provided and not #f. In either case, the syntax object is [cons](pairs.html#%28def._%28%28quote._~23~25kernel%29._cons%29%29)ed onto extra-sources to produce the exprs field, or extra-sources is used directly for exprs if neither expr nor sub-expr is provided and not #f. The extra-sources argument is also used directly for exprs in the unusual case that the sub-expr or expr that would be included in exprs cannot be converted to a syntax object (because it contains a cycle).\n\nThe form name used in the generated error message is determined through a combination of the name, expr, and sub-expr arguments:\n\n- When name is #f, and when expr is either an identifier or a syntax pair containing an identifier as its first element, then the form name from the error message is the identifier’s symbol.\n\n- When name is #f and when expr is not an identifier or a syntax pair containing an identifier as its first element, then the form name in the error message is \"?\".\n\n- When name is a symbol, then the symbol is used as the form name in the generated error message.\n\nThe message-suffix string is appended to the end of the error message. If not \"\", it should normally start with a newline and two spaces to add extra fields to the message (see [Error Message Conventions](#%28part._err-msg-conventions%29)).\n\nIf specified, exn should be a constructor or function that has the same signature as the [exn:fail:syntax](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3asyntax%29%29) constructor.\n\nExamples:\n\n> ```racket\n> > ( raise-syntax-error #f \"bad syntax\" ' ( bad syntax ) )\n> ?: bad syntax\n> in: (bad syntax)\n> > ( raise-syntax-error #f \"unbound identifier\" ' unbound-id #:exn exn:fail:syntax:unbound )\n> ?: unbound identifier\n> in: unbound-id\n> ```\n\nChanged in version 6.90.0.18 of package base: Added the message-suffix optional argument. \nChanged in version 8.4.0.6: Added the exn optional argument.\n\n> ```\n(unquoted-printing-string? v)  →  boolean?\n  v : any/c\n\n(unquoted-printing-string s)  →  unquoted-printing-string?\n  s : string?\n\n(unquoted-printing-string-value ups)  →  string?\n  ups : unquoted-printing-string?\n```"} {"text": "# 10.1 Multiple Values\nAn unquoted-printing string wraps a string and prints, writes, and displays the same way that the string displays. An unquoted-printing string is especially useful with raise-arguments-error to serve as a field “value” that causes literal text to be printed as the field content.\nThe unquoted-printing-string? procedure returns #t if v is a unquoted-printing string, #f otherwise. The unquoted-printing-string creates a unquoted-printing string value that encapsulates the string s, and unquoted-printing-string-value returns the string within a unquoted-printing string.\nAdded in version 6.10.0.2 of package base."} {"text": "#### 10.2.3 Handling Exceptions\n> ```\n(call-with-exception-handler f thunk)  →  any\n  f : (any/c . → . any)\n  thunk : ( →  any)```\nInstalls f as the [exception handler](eval-model.html#%28tech._exception._handler%29) for the [dynamic extent](eval-model.html#%28tech._dynamic._extent%29) of the call to thunk. If an exception is raised during the evaluation of thunk (in an extension of the current continuation that does not have its own exception handler), then f is applied to the [raise](#%28def._%28%28quote._~23~25kernel%29._raise%29%29)d value in the continuation of the [raise](#%28def._%28%28quote._~23~25kernel%29._raise%29%29) call (but the continuation is normally extended with a [continuation barrier](eval-model.html#%28tech._continuation._barrier%29); see [Prompts, Delimited Continuations, and Barriers](eval-model.html#%28part._prompt-model%29) and [raise](#%28def._%28%28quote._~23~25kernel%29._raise%29%29))."} {"text": "# 10.1 Multiple Values\nAny procedure that takes one argument can be an exception handler. Normally, an exception handler escapes from the context of the [raise](#%28def._%28%28quote._~23~25kernel%29._raise%29%29) call via [abort-current-continuation](cont.html#%28def._%28%28quote._~23~25kernel%29._abort-current-continuation%29%29) or some other escape mechanism. To propagate an exception to the “previous” exception handler—that is, the exception handler associated with the rest of the continuation after the point where the called exception handler was associated with the continuation—an exception handler can simply return a result instead of escaping, in which case the [raise](#%28def._%28%28quote._~23~25kernel%29._raise%29%29) call propagates the value to the previous exception handler (still in the dynamic extent of the call to [raise](#%28def._%28%28quote._~23~25kernel%29._raise%29%29), and under the same barrier, if any). If an exception handler returns a result and no previous handler is available, the [uncaught-exception handler](#%28tech._uncaught._exception._handler%29) is used."} {"text": "# 10.1 Multiple Values\nA call to an exception handler is [parameterize-break](breakhandler.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize-break%29%29)ed to disable breaks, and it is wrapped with [call-with-exception-handler](#%28def._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._call-with-exception-handler%29%29) to install an exception handler that reports both the original and newly raised exceptions via the [error display handler](#%28tech._error._display._handler%29) and then escapes via the [error escape handler](#%28tech._error._escape._handler%29).\n> ```\n(uncaught-exception-handler)\t→\t\n(-> any/c . → . any)\n(uncaught-exception-handler f) → void?\n f\t:\t\n(-> any/c . → . any)"} {"text": "# 10.1 Multiple Values\n```\n(parameter)\t→```\n\n\nEvaluates each pred-expr and handler-expr in the order that they are specified, and then evaluates the bodys with a new exception handler during its dynamic extent.\n\nThe new exception handler processes an exception only if one of the pred-expr procedures returns a true value when applied to the exception, otherwise the exception handler is invoked from the continuation of the [with-handlers](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._with-handlers%29%29) expression (by raising the exception again). If an exception is handled by one of the handler-expr procedures, the result of the entire [with-handlers](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._with-handlers%29%29) expression is the return value of the handler.\n\nWhen an exception is raised during the evaluation of bodys, each predicate procedure pred-expr is applied to the exception value; if a predicate returns a true value, the corresponding handler-expr procedure is invoked with the exception as an argument. The predicates are tried in the order that they are specified.\n\nBefore any predicate or handler procedure is invoked, the continuation of the entire [with-handlers](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._with-handlers%29%29) expression is restored, but also [parameterize-break](breakhandler.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize-break%29%29)ed to disable breaks. Thus, breaks are disabled by default during the predicate and handler procedures (see [Breaks](breakhandler.html)), and the exception handler is the one from the continuation of the [with-handlers](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._with-handlers%29%29) expression.\n\nThe [exn:fail?](#%28def._%28%28quote._~23~25kernel%29._exn~3afail~3f%29%29) procedure is useful as a handler predicate to catch all error exceptions. Avoid using ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) (x) #t) as a predicate, because the [exn:break](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak%29%29) exception typically should not be caught (unless it will be re-raised to cooperatively break). Beware, also, of catching and discarding exceptions, because discarding an error message can make debugging unnecessarily difficult; instead of discarding an error message, consider logging it via [log-error](logging.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._log-error%29%29) or a logging form created by [define-logger](logging.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._define-logger%29%29).\n\nExamples:\n\n> ```racket\n> > ( with-handlers ( [ exn:fail:syntax? ( λ ( e ) ( displayln \"got a syntax error\" ) ) ] ) ( raise-syntax-error #f \"a syntax error\" ) )\n> got a syntax error\n> > ( with-handlers ( [ exn:fail:syntax? ( λ ( e ) ( displayln \"got a syntax error\" ) ) ] [ exn:fail? ( λ ( e ) ( displayln \"fallback clause\" ) ) ] ) ( raise-syntax-error #f \"a syntax error\" ) )\n> got a syntax error\n> ```\n\n> ```\nsyntax\n\n(with-handlers* ([pred-expr handler-expr] ...)\n> body ...+ )\n```"} {"text": "# 10.1 Multiple Values\n(error-escape-handler)\t→\t\n(-> any)\n(error-escape-handler proc) → void?\n proc\t:\t\n(-> any)```\nA parameter for the error escape handler, which takes no arguments and escapes from the dynamic context of an exception. The default error escape handler escapes using ([abort-current-continuation](cont.html#%28def._%28%28quote._~23~25kernel%29._abort-current-continuation%29%29) ([default-continuation-prompt-tag](cont.html#%28def._%28%28quote._~23~25kernel%29._default-continuation-prompt-tag%29%29)) [void](void.html#%28def._%28%28quote._~23~25kernel%29._void%29%29)).\nThe error escape handler is normally called directly by an exception handler, in a [parameterization](eval-model.html#%28tech._parameterization%29) that sets the [error display handler](#%28tech._error._display._handler%29) and [error escape handler](#%28tech._error._escape._handler%29) to the default handlers, and it is normally [parameterize-break](breakhandler.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize-break%29%29)ed to disable breaks. To escape from a run-time error in a different context, use [raise](#%28def._%28%28quote._~23~25kernel%29._raise%29%29) or [error](#%28def._%28%28quote._~23~25kernel%29._error%29%29)."} {"text": "# 10.1 Multiple Values\nDue to a [continuation barrier](eval-model.html#%28tech._continuation._barrier%29) around exception-handling calls, an error escape handler cannot invoke a full continuation that was created prior to the exception, but it can abort to a prompt (see [call-with-continuation-prompt](cont.html#%28def._%28%28quote._~23~25kernel%29._call-with-continuation-prompt%29%29)) or invoke an escape continuation (see [call-with-escape-continuation](cont.html#%28def._%28%28quote._~23~25kernel%29._call-with-escape-continuation%29%29)).\n> ```\n(error-display-handler)\t→\t\n(-> string? any/c . → . any)\n(error-display-handler proc) → void?\n proc\t:\t\n(-> string? any/c . → . any)\n```\n(error-print-width)\t→\t\n(-> error-print-width)\n(error-print-width width) → void?\n width\t:\t\n(-> error-print-width)```\n\n\nA parameter whose value is used as the maximum number of characters used to print a Racket value that is embedded in a primitive error message.\n\n> ```\n(error-print-context-length)\t→\t\n(-> error-print-context-length cnt)\n(error-print-context-length cnt) → void?\n cnt\t:\t\n(-> error-print-context-length cnt)\n```\n(error-print-source-location)\t→\t\n(-> error-print-source-location include?)```"} {"text": "# 10.1 Multiple Values\nA [parameter](eval-model.html#%28tech._parameter%29) that controls whether read and syntax error messages include source information, such as the source line and column or the expression. This parameter also controls the error message when a module-defined variable is accessed before its definition is executed; the parameter determines whether the message includes a module name. Only the message field of an [exn:fail:read](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aread%29%29), [exn:fail:syntax](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3asyntax%29%29), or [exn:fail:contract:variable](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3avariable%29%29) structure is affected by the parameter. The default is #t.\n> ```\n(parameter)\t→\t\n(-> any/c exact-nonnegative-integer?\n . → .\n string?)"} {"text": "# 10.1 Multiple Values\n```\n(parameter)\t→\t\n(-> see print-unreadable)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the error syntax conversion handler, which is used to print a syntax form that is embedded in an error message, such as from [raise-syntax-error](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._raise-syntax-error%29%29) when [error-print-source-location](#%28def._%28%28quote._~23~25kernel%29._error-print-source-location%29%29) is #t.\n\nThe arguments to the handler are analogous to the arguments for a [error value conversion handler](#%28tech._error._value._conversion._handler%29) as configured with [error-value->string-handler](#%28def._%28%28quote._~23~25kernel%29._error-value-~3estring-handler%29%29), except that #f can be provided instead of an integer for the length, meaning that the printed form should not be truncated. The first argument is normally a [syntax object](syntax-model.html#%28tech._syntax._object%29), but in the same way that [raise-syntax-error](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._raise-syntax-error%29%29) accepts other S-expressions, the error syntax conversion handler must also handle representations that are not syntax objects.\n\nAdded in version 8.2.0.8 of package base.\n\n> ```\n(parameter)\t→\t\n(-> syntax? . → . (or/c symbol? #f))\n```\n(parameter)\t→\t\n(-> any/c exact-nonnegative-integer?\n . → .\n string?)```"} {"text": "# 10.1 Multiple Values\nSimilar to [error-value->string-handler](#%28def._%28%28quote._~23~25kernel%29._error-value-~3estring-handler%29%29), but intended for a module path. The default [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29)s the module path to a string.\nAdded in version 8.16.0.3 of package base."} {"text": "#### 10.2.5 Built-in Exception Types\n>
\n

struct

\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn%29%29) (message continuation-marks)
    #:extra-constructor-name [make-exn](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn%29%29)
    #:transparent)
  message : [string?](strings.html#%28def._%28%28quote._~23~25kernel%29._string~3f%29%29)
  continuation-marks : [continuation-mark-set?](contmarks.html#%28def._%28%28quote._~23~25kernel%29._continuation-mark-set~3f%29%29)
\nThe base [structure type](structures.html#%28tech._structure._type%29) for exceptions. The message field contains an error message, and the [continuation-marks](contmarks.html#%28def._%28%28quote._~23~25kernel%29._continuation-marks%29%29) field contains the value produced by ([current-continuation-marks](contmarks.html#%28def._%28%28quote._~23~25kernel%29._current-continuation-marks%29%29)) immediately before the exception was raised.\nExceptions raised by Racket form a hierarchy under [exn](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn%29%29):"} {"text": "# 10.1 Multiple Values\n> ```racket\n> exn\n> exn:fail\n> exn:fail:contract\n> exn:fail:contract:arity\n> exn:fail:contract:divide-by-zero\n> exn:fail:contract:non-fixnum-result\n> exn:fail:contract:continuation\n> exn:fail:contract:variable\n> exn:fail:syntax\n> exn:fail:syntax:unbound\n> exn:fail:syntax:missing-module\n> exn:fail:read\n> exn:fail:read:eof\n> exn:fail:read:non-char\n> exn:fail:filesystem\n> exn:fail:filesystem:exists\n> exn:fail:filesystem:version\n> exn:fail:filesystem:errno\n> exn:fail:filesystem:missing-module\n> exn:fail:network\n> exn:fail:network:errno\n> exn:fail:out-of-memory\n> exn:fail:unsupported\n> exn:fail:user\n> exn:break\n> exn:break:hang-up\n> exn:break:terminate\n> ```\n>
\n

struct

\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) [exn](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn%29%29) ()
    #:extra-constructor-name [make-exn:fail](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail%29%29)
    #:transparent)
\nRaised for exceptions that represent errors, as opposed to [exn:break](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak%29%29)."} {"text": "# 10.1 Multiple Values\n>
\n

struct

\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:contract](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) [exn:fail](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) ()
    #:extra-constructor-name [make-exn:fail:contract](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3acontract%29%29)
    #:transparent)
\nRaised for errors from the inappropriate run-time use of a function or syntactic form.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:contract:arity](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3aarity%29%29) [exn:fail:contract](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) ()
    #:extra-constructor-name [make-exn:fail:contract:arity](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3acontract~3aarity%29%29)
    #:transparent)
\nRaised when a procedure is applied to the wrong number of arguments.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:contract:divide-by-zero](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3adivide-by-zero%29%29) [exn:fail:contract](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) ()
    #:extra-constructor-name
    [make-exn:fail:contract:divide-by-zero](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3acontract~3adivide-by-zero%29%29)
    #:transparent)
\nRaised for division by exact zero.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:contract:non-fixnum-result](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3anon-fixnum-result%29%29) [exn:fail:contract](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) ()
    #:extra-constructor-name
    [make-exn:fail:contract:non-fixnum-result](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3acontract~3anon-fixnum-result%29%29)
    #:transparent)
\nRaised by functions like [fx+](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fx%2B%29%29) when the result would not be a fixnum.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:contract:continuation](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3acontinuation%29%29) [exn:fail:contract](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) ()
    #:extra-constructor-name [make-exn:fail:contract:continuation](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3acontract~3acontinuation%29%29)
    #:transparent)
\nRaised when a continuation is applied where the jump would cross a continuation barrier.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:contract:variable](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3avariable%29%29) [exn:fail:contract](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) (id)
    #:extra-constructor-name [make-exn:fail:contract:variable](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3acontract~3avariable%29%29)
    #:transparent)
  id : [symbol?](symbols.html#%28def._%28%28quote._~23~25kernel%29._symbol~3f%29%29)
\nRaised for a reference to a not-yet-defined [top-level variable](eval-model.html#%28tech._top._level._variable%29) or [module-level variable](eval-model.html#%28tech._module._level._variable%29).\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:syntax](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3asyntax%29%29) [exn:fail](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) (exprs)
    #:extra-constructor-name [make-exn:fail:syntax](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3asyntax%29%29)
    #:transparent)
  exprs : ([listof](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._listof%29%29) [syntax?](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax~3f%29%29))
\nRaised for a syntax error that is not a [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) error. The exprs indicate the relevant source expressions, least-specific to most-specific.\nThis structure type implements the [prop:exn:srclocs](#%28def._%28%28quote._~23~25kernel%29._prop~3aexn~3asrclocs%29%29) property.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:syntax:unbound](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3asyntax~3aunbound%29%29) [exn:fail:syntax](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3asyntax%29%29) ()
    #:extra-constructor-name [make-exn:fail:syntax:unbound](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3asyntax~3aunbound%29%29)
    #:transparent)
\nRaised by [#%top](__top.html#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) or [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) for an unbound identifier within a module.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:syntax:missing-module](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3asyntax~3amissing-module%29%29) [exn:fail:syntax](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3asyntax%29%29) (path)
    #:extra-constructor-name [make-exn:fail:syntax:missing-module](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3asyntax~3amissing-module%29%29)
    #:transparent)
  path : [module-path?](Module_Names_and_Loading.html#%28def._%28%28quote._~23~25kernel%29._module-path~3f%29%29)
\nRaised by the default [module name resolver](Module_Names_and_Loading.html#%28tech._module._name._resolver%29) or default [load handler](eval.html#%28tech._load._handler%29) to report a module path—a reported in the path field—whose implementation file cannot be found."} {"text": "# 10.1 Multiple Values\nThe default [module name resolver](Module_Names_and_Loading.html#%28tech._module._name._resolver%29) raises this exception only when it is given a syntax object as its second argument, and the default [load handler](eval.html#%28tech._load._handler%29) raises this exception only when the value of [current-module-path-for-load](Module_Names_and_Loading.html#%28def._%28%28quote._~23~25kernel%29._current-module-path-for-load%29%29) is a syntax object (in which case both the exprs field and the path field are determined by the syntax object).\nThis structure type implements the [prop:exn:missing-module](#%28def._%28%28quote._~23~25kernel%29._prop~3aexn~3amissing-module%29%29) property.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:read](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aread%29%29) [exn:fail](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) (srclocs)
    #:extra-constructor-name [make-exn:fail:read](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3aread%29%29)
    #:transparent)
  srclocs : ([listof](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._listof%29%29) [srcloc?](#%28def._%28%28quote._~23~25kernel%29._srcloc~3f%29%29))
\nRaised for a [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) error. The srclocs indicate the relevant source expressions.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:read:eof](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aread~3aeof%29%29) [exn:fail:read](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aread%29%29) ()
    #:extra-constructor-name [make-exn:fail:read:eof](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3aread~3aeof%29%29)
    #:transparent)
\nRaised for a [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) error, specifically when the error is due to an unexpected end-of-file.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:read:non-char](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aread~3anon-char%29%29) [exn:fail:read](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aread%29%29) ()
    #:extra-constructor-name [make-exn:fail:read:non-char](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3aread~3anon-char%29%29)
    #:transparent)
\nRaised for a [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) error, specifically when the error is due to an unexpected non-character (i.e., “special”) element in the input stream.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:filesystem](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) [exn:fail](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) ()
    #:extra-constructor-name [make-exn:fail:filesystem](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3afilesystem%29%29)
    #:transparent)
\nRaised for an error related to the filesystem (such as a file not found).\n>
\n

struct

\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:filesystem:exists](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem~3aexists%29%29) [exn:fail:filesystem](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) ()
    #:extra-constructor-name [make-exn:fail:filesystem:exists](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3afilesystem~3aexists%29%29)
    #:transparent)
"} {"text": "# 10.1 Multiple Values\nRaised for an error when attempting to create a file that exists already.\n>
\n

struct

\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:filesystem:version](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem~3aversion%29%29) [exn:fail:filesystem](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) ()
    #:extra-constructor-name [make-exn:fail:filesystem:version](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3afilesystem~3aversion%29%29)
    #:transparent)
\nRaised for a version-mismatch error when loading an extension.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:filesystem:errno](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem~3aerrno%29%29) [exn:fail:filesystem](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) (errno)
    #:extra-constructor-name [make-exn:fail:filesystem:errno](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3afilesystem~3aerrno%29%29)
    #:transparent)
  errno : ([cons/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._cons%2Fc%29%29) [exact-integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-integer~3f%29%29) ([or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) 'posix 'windows 'gai))
"} {"text": "# 10.1 Multiple Values\nRaised for a filesystem error for which a system error code is available. The symbol part of an errno field indicates the category of the error code: 'posix indicates a C/Posix errno value, 'windows indicates a Windows system error code (under Windows, only), and 'gai indicates a getaddrinfo error code (which shows up only in [exn:fail:network:errno](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3anetwork~3aerrno%29%29) exceptions for operations that resolve hostnames, but is allowed in [exn:fail:filesystem:errno](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem~3aerrno%29%29) instances for consistency).\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:filesystem:missing-module](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem~3amissing-module%29%29) [exn:fail:filesystem](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29)
  (path)
    #:extra-constructor-name
    [make-exn:fail:filesystem:missing-module](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3afilesystem~3amissing-module%29%29)
    #:transparent)
  path : [module-path?](Module_Names_and_Loading.html#%28def._%28%28quote._~23~25kernel%29._module-path~3f%29%29)
\nRaised by the default [module name resolver](Module_Names_and_Loading.html#%28tech._module._name._resolver%29) or default [load handler](eval.html#%28tech._load._handler%29) to report a module path—a reported in the path field—whose implementation file cannot be found."} {"text": "# 10.1 Multiple Values\nThe default [module name resolver](Module_Names_and_Loading.html#%28tech._module._name._resolver%29) raises this exception only when it is not given a syntax object as its second argument, and the default [load handler](eval.html#%28tech._load._handler%29) raises this exception only when the value of [current-module-path-for-load](Module_Names_and_Loading.html#%28def._%28%28quote._~23~25kernel%29._current-module-path-for-load%29%29) is not a syntax object.\nThis structure type implements the [prop:exn:missing-module](#%28def._%28%28quote._~23~25kernel%29._prop~3aexn~3amissing-module%29%29) property.\n>
\n

struct

\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:network](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3anetwork%29%29) [exn:fail](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) ()
    #:extra-constructor-name [make-exn:fail:network](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3anetwork%29%29)
    #:transparent)
\nRaised for TCP and UDP errors.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:network:errno](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3anetwork~3aerrno%29%29) [exn:fail:network](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3anetwork%29%29) (errno)
    #:extra-constructor-name [make-exn:fail:network:errno](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3anetwork~3aerrno%29%29)
    #:transparent)
  errno : ([cons/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._cons%2Fc%29%29) [exact-integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-integer~3f%29%29) ([or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) 'posix 'windows 'gai))
\nRaised for a TCP or UDP error for which a system error code is available, where the errno field is as for [exn:fail:filesystem:errno](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem~3aerrno%29%29).\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:out-of-memory](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aout-of-memory%29%29) [exn:fail](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) ()
    #:extra-constructor-name [make-exn:fail:out-of-memory](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3aout-of-memory%29%29)
    #:transparent)
\nRaised for an error due to insufficient memory, in cases where sufficient memory is at least available for raising the exception.\n>
\n

struct

\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:unsupported](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aunsupported%29%29) [exn:fail](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) ()
    #:extra-constructor-name [make-exn:fail:unsupported](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3aunsupported%29%29)
    #:transparent)
"} {"text": "# 10.1 Multiple Values\nRaised for an error due to an unsupported feature on the current platform or configuration.\n>
\n

struct

\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:fail:user](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3auser%29%29) [exn:fail](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) ()
    #:extra-constructor-name [make-exn:fail:user](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3afail~3auser%29%29)
    #:transparent)
\nRaised for errors that are intended to be seen by end users. In particular, the default error printer does not show the program context when printing the error message.\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:break](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak%29%29) [exn](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn%29%29) (continuation)
    #:extra-constructor-name [make-exn:break](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3abreak%29%29)
    #:transparent)
  continuation : [continuation?](cont.html#%28def._%28%28quote._~23~25kernel%29._continuation~3f%29%29)
\nRaised asynchronously (when enabled) in response to a break request. The continuation field can be used to resume the interrupted computation in the [uncaught-exception handler](#%28tech._uncaught._exception._handler%29) or [call-with-exception-handler](#%28def._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._call-with-exception-handler%29%29) (but not [with-handlers](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._with-handlers%29%29) because it escapes from the exception context before evaluating any predicates or handlers).\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:break:hang-up](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak~3ahang-up%29%29) [exn:break](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak%29%29) ()
    #:extra-constructor-name [make-exn:break:hang-up](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3abreak~3ahang-up%29%29)
    #:transparent)
\nRaised asynchronously for hang-up breaks. The default [uncaught-exception handler](#%28tech._uncaught._exception._handler%29) reacts to this exception type by calling the [exit handler](Exiting.html#%28tech._exit._handler%29).\n>
\n

struct

"} {"text": "# 10.1 Multiple Values\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [exn:break:terminate](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak~3aterminate%29%29) [exn:break](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak%29%29) ()
    #:extra-constructor-name [make-exn:break:terminate](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-exn~3abreak~3aterminate%29%29)
    #:transparent)
\nRaised asynchronously for termination-request breaks. The default [uncaught-exception handler](#%28tech._uncaught._exception._handler%29) reacts to this exception type by calling the [exit handler](Exiting.html#%28tech._exit._handler%29).\n>
\n

value

\n

[prop:exn:srclocs](#%28def._%28%28quote._~23~25kernel%29._prop~3aexn~3asrclocs%29%29) : [struct-type-property?](structprops.html#%28def._%28%28quote._~23~25kernel%29._struct-type-property~3f%29%29)

\nA property that identifies structure types that provide a list of [srcloc](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29) values. The property is normally attached to structure types used to represent exception information."} {"text": "# 10.1 Multiple Values\nThe property value must be a procedure that accepts a single value—the structure type instance from which to extract source locations—and returns a list of [srcloc](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29)s. Some [error display handlers](#%28tech._error._display._handler%29) use only the first returned location.\nAs an example,\n> ```racket\n> #lang racket\n> ;; We create a structure that supports the\n> ;; prop:exn:srcloc protocol. It carries\n> ;; with it the location of the syntax that\n> ;; is guilty.\n> ( struct exn:fail:he-who-shall-not-be-named exn:fail\n> ( a-srcloc )\n> #:property prop:exn:srclocs\n> ( lambda ( a-struct )\n> ( match a-struct\n> [ ( exn:fail:he-who-shall-not-be-named msg marks a-srcloc )\n> ( list a-srcloc ) ] ) ) )\n> ;; We can play with this by creating a form that\n> ;; looks at identifiers, and only flags specific ones.\n> ( define-syntax ( skeeterize stx )\n> ( syntax-case stx ( )\n> [ ( _ expr )\n> ( cond\n> [ ( and ( identifier? #' expr )\n> ( eq? ( syntax-e #' expr ) ' voldemort ) )\n> ( quasisyntax/loc stx\n> ( raise ( exn:fail:he-who-shall-not-be-named\n> \"oh dear don't say his name\"\n> ( current-continuation-marks )\n> ( srcloc ' #, ( syntax-source #' expr )\n> ' #, ( syntax-line #' expr )\n> ' #, ( syntax-column #' expr )\n> ' #, ( syntax-position #' expr )\n> ' #, ( syntax-span #' expr ) ) ) ) ) ]\n> [ else\n> ;; Otherwise, leave the expression alone.\n> #' expr ] ) ] ) )\n> ( define ( f x )\n> ( * ( skeeterize x ) x ) )\n> ( define ( g voldemort )\n> ( * ( skeeterize voldemort ) voldemort ) )\n> ;; Examples:\n> ( f 7 )\n> ( g 7 )\n> ;; The error should highlight the use\n> ;; of voldemort in g.\n> ```"} {"text": "# 10.1 Multiple Values\n> ```\n(exn:srclocs? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v has the prop:exn:srclocs property, #f otherwise.\n\n> ```\n(exn:srclocs-accessor v)\n  →  (exn:srclocs? . → . (listof srcloc))\n  v : exn:srclocs?```\n\n\nReturns the [srcloc](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29)-getting procedure associated with v.\n\n>
\n\n

struct

\n\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [srcloc](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29) (source line column position span)
    #:extra-constructor-name [make-srcloc](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-srcloc%29%29)
    #:transparent)
  source : [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29)
  line : ([or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) [exact-positive-integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-positive-integer~3f%29%29) #f)
  column : ([or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) [exact-nonnegative-integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-nonnegative-integer~3f%29%29) #f)
  position : ([or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) [exact-positive-integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-positive-integer~3f%29%29) #f)
  span : ([or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) [exact-nonnegative-integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-nonnegative-integer~3f%29%29) #f)
\n\nA source location is most frequently represented by a [srcloc](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29) structure. More generally, a source location has the same information as a [srcloc](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29) structure, but potentially represented or accessed differently. For example, source-location information is accessed from a [syntax object](syntax-model.html#%28tech._syntax._object%29) with functions like [syntax-source](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-source%29%29) and [syntax-line](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-line%29%29), while [datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29) accepts a source location as a list, vector, or another syntax object. For ports, a combination of [object-name](inspectors.html#%28def._%28%28quote._~23~25kernel%29._object-name%29%29) and [port-next-location](linecol.html#%28def._%28%28quote._~23~25kernel%29._port-next-location%29%29) provides location information, especially in a port for which counting has been enabled through [port-count-lines!](linecol.html#%28def._%28%28quote._~23~25kernel%29._port-count-lines%21%29%29).\n\nThe fields of a [srcloc](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29) instance are as follows:\n\n- source — An arbitrary value identifying the source, often a path (see [Paths](pathutils.html)).\n\n- line — The line number (counts from 1) or #f (unknown).\n\n- column — The column number (counts from 0) or #f (unknown).\n\n- position — The starting position (counts from 1) or #f (unknown).\n\n- span — The number of covered positions (counts from 0) or #f (unknown).\n\nSee [Printing Compiled Code](printing.html#%28part._print-compiled%29) for information about the treatment of [srcloc](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29) values that are embedded in compiled code.\n\n> ```\n(srcloc → string srcloc)  →  (or/c string? #f)\n  srcloc : srcloc?\n```"} {"text": "# 10.1 Multiple Values\n(parameter)\t→```\nReturns #t if v has the [prop:exn:missing-module](#%28def._%28%28quote._~23~25kernel%29._prop~3aexn~3amissing-module%29%29) property, #f otherwise.\n> ```\n(exn:missing-module-accessor v)\n  →  (exn:missing-module? . → . module-path?)\n  v : exn:srclocs?\n```\nReturns the module path-getting procedure associated with v.\n\n#### 10.2.6 Additional Exception Functions\n\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require racket/exn) |  package: base |\n\nThe bindings documented in this section are provided by the racket/exn library, not racket/base or racket.\n\nAdded in version 6.3 of package base.\n\n> ```\n(exn → string exn) → string?\n  exn : (or/c exn? any/c)```\n\n\nFormats exn as a string. If exn is an [exn?](#%28def._%28%28quote._~23~25kernel%29._exn~3f%29%29), collects and returns the output from the current ([error-display-handler](#%28def._%28%28quote._~23~25kernel%29._error-display-handler%29%29)); otherwise, simply converts exn to a string using ([format](Writing.html#%28def._%28%28quote._~23~25kernel%29._format%29%29) \"\\~s\\\\n\" exn).\n\n#### 10.2.7 Realms and Error Message Adjusters\n\nA realm identifies a convention for naming functions and specifying contracts for function arguments and results. Realms are intended to help improve layering and interoperability among languages that are implemented on top of Racket.\n\nRealms primarily enable a language to recognize and rewrite error messages that are generated by lower layers of an implementation. For example, a language’s implementation of “arrays” might use Racket vectors directly, but when an object-type or primitive bounds check fails for a vector, the generated error message mentions “vector” and possibly a contract like [vector?](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector~3f%29%29) and a function name like [vector-ref](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector-ref%29%29). Since these error messages are identified as being from the 'racket/primitive realm, a language implementation can look for 'racket/primitive to detect and rewrite error messages with minimal danger of mangling error messages from other parts of an application (possibly implemented in the new language) that happen to use the word “vector.”\n\nEach procedure and each module also has a realm. A procedure’s realm is relevant, for example, when it is applied to the wrong number of arguments; in that case, the arity-error message itself is from the 'racket/primitive realm, but the error message also should include the name of the procedure, which can be from some different realm. Along similar lines, [continuation-mark-set->context](contmarks.html#%28def._%28%28quote._~23~25kernel%29._continuation-mark-set-~3econtext%29%29) can report the realm associated with (the procedure for) each frame in a continuation, which might be useful to identify boundary crossings.\n\nThe construction of an error message must cooperate explicitly with error-message adjusting. The most basic may to cooperate is through functions like [error-message->adjusted-string](#%28def._%28%28quote._~23~25kernel%29._error-message-~3eadjusted-string%29%29) and [error-contract->adjusted-string](#%28def._%28%28quote._~23~25kernel%29._error-contract-~3eadjusted-string%29%29), which run error-message adjusters via the [current-error-message-adjuster](#%28def._%28%28quote._~23~25kernel%29._current-error-message-adjuster%29%29) parameter and other adjusters associated with the current continuation using [error-message-adjuster-key](#%28def._%28%28quote._~23~25kernel%29._error-message-adjuster-key%29%29) as a [continuation-mark](eval-model.html#%28tech._continuation._mark%29) key. Functions like [raise-argument-error](#%28def._%28%28quote._~23~25kernel%29._raise-argument-error%29%29) and [raise-arity-error](#%28def._%28%28quote._~23~25kernel%29._raise-arity-error%29%29) use [error-message->adjusted-string](#%28def._%28%28quote._~23~25kernel%29._error-message-~3eadjusted-string%29%29) and [error-contract->adjusted-string](#%28def._%28%28quote._~23~25kernel%29._error-contract-~3eadjusted-string%29%29) with the default realm, 'racket. Functions like [raise-argument-error*](#%28def._%28%28quote._~23~25kernel%29._raise-argument-error%2A%29%29) and [raise-arity-error*](#%28def._%28%28quote._~23~25kernel%29._raise-arity-error%2A%29%29) accept an explicit realm argument.\n\nNot all error functions automatically cooperate with error-message adjusting. For example, the raise-reader-error and [raise-syntax-error](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._raise-syntax-error%29%29) functions do not call adjusters, because they report errors that are intimately tied to syntax (and, along those lines, errors of a more static nature).\n\n> ```\n(parameter)\t→\t\n(-> or/c symbol? #f)\n```"} {"text": "# 10.1 Multiple Values\n(parameter)\t→```\nAnalogous to [error-message->adjusted-string](#%28def._%28%28quote._~23~25kernel%29._error-message-~3eadjusted-string%29%29), but for just the contract part of an error message. The result string is typically incorporated into a larger error message that may then be adjusted further.\nAdjustment of contract string uses the 'contract protocol as described for [current-error-message-adjuster](#%28def._%28%28quote._~23~25kernel%29._current-error-message-adjuster%29%29).\nAdded in version 8.4.0.2 of package base.\n> ```\n(current-error-message-adjuster)\t→\t\n(-> symbol? . → . (or/c procedure? #f))\n(current-error-message-adjuster proc) → void?\n proc\t:\t\n(-> symbol? . → . (or/c procedure? #f))"} {"text": "# 10.1 Multiple Values\n```\n(parameter)\t→\t\n(-> require [racket/promise]())```\n\n\nReturns #t if v is a promise, #f otherwise.\n\n>
\n\n

syntax

\n\n

([delay](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%29%29) body ...+)

\n\nCreates a promise that, when [force](#%28def._%28%28lib._racket%2Fpromise..rkt%29._force%29%29)d, evaluates the bodys to produce its value. The result is then cached, so further uses of [force](#%28def._%28%28lib._racket%2Fpromise..rkt%29._force%29%29) produce the cached value immediately. This includes multiple values and exceptions.\n\n>
\n\n

syntax

\n\n

([lazy](#%28form._%28%28lib._racket%2Fpromise..rkt%29._lazy%29%29) body ...+)

\n\nLike [delay](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%29%29), if the last body produces a promise when forced, then this promise is [force](#%28def._%28%28lib._racket%2Fpromise..rkt%29._force%29%29)d, too, to obtain a value. In other words, this form creates a composable promise, where the computation of its body is “attached” to the computation of the following promise, and a single [force](#%28def._%28%28lib._racket%2Fpromise..rkt%29._force%29%29) iterates through the whole chain, tail-calling each step.\n\nNote that the last body of this form must produce a single value, but the value can itself be a [delay](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%29%29) promise that returns multiple values.\n\nThe [lazy](#%28form._%28%28lib._racket%2Fpromise..rkt%29._lazy%29%29) form is useful for implementing lazy libraries and languages, where tail calls can be wrapped in a promise.\n\n> ```\n(force v)  →  any\n  v : any/c\n```"} {"text": "# 10.1 Multiple Values\nIf v is a promise, then the promise is forced to obtain a value. If the promise has not been forced before, then the result is recorded in the promise so that future forces on the promise produce the same value (or values). If forcing the promise raises an exception, then the exception is similarly recorded so that forcing the promise will raise the same exception every time.\nIf v is forced again before the original call to force returns, then the exn:fail exception is raised.\nIf v is not a promise, then it is returned as the result.\n> ```\n(promise-forced? promise)  →  boolean?\n  promise : promise?```\nReturns #t if promise has been forced.\n> ```\n(promise-running? promise)  →  boolean?\n  promise : promise?"} {"text": "# 10.1 Multiple Values\n```\nReturns #t if promise is currently being forced. (Note that a promise can be either running or forced but not both.)\n\n#### 10.3.1 Additional Promise Kinds\n\n>
\n\n

syntax

\n\n

(delay/name body ...+)

\n\nCreates a “call-by-name” promise that is similar to delay-promises, except that the resulting value is not cached. This kind of promise is essentially a thunk that is wrapped in a way that force recognizes.\n\nIf a delay/name promise forces itself, no exception is raised, the promise is never considered “running” or “forced” in the sense of promise-running? and promise-forced?.\n\n> ```\n(promise/name? promise) → boolean?\n  promise : any/c```\n\n\nReturns #t if promise is a promise created with [delay/name](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%2Fname%29%29).\n\nAdded in version 6.3 of package base.\n\n>
\n\n

syntax

\n\n

([delay/strict](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%2Fstrict%29%29) body ...+)

\n\nCreates a “strict” promise: it is evaluated immediately, and the result is wrapped in a promise value. Note that the body can evaluate to multiple values, and forcing the resulting promise will return these values.\n\n>
\n\n

syntax

\n\n

([delay/sync](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%2Fsync%29%29) body ...+)

\n\nProduces a promise where an attempt to [force](#%28def._%28%28lib._racket%2Fpromise..rkt%29._force%29%29) the promise by a thread other than one currently running the promise causes the [force](#%28def._%28%28lib._racket%2Fpromise..rkt%29._force%29%29) to block until a result is available. This kind of promise is also a [synchronizable event](sync.html#%28tech._synchronizable._event%29) for use with [sync](sync.html#%28def._%28%28quote._~23~25kernel%29._sync%29%29); [sync](sync.html#%28def._%28%28quote._~23~25kernel%29._sync%29%29)ing on the promise does not [force](#%28def._%28%28lib._racket%2Fpromise..rkt%29._force%29%29) it, but merely waits until a value is forced by another thread. The [synchronization result](sync.html#%28tech._synchronization._result%29) is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13).\n\nIf a promise created by [delay/sync](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%2Fsync%29%29) is forced on a thread that is already running the promise, an exception is raised in the same way as for promises created with [delay](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%29%29).\n\n>
\n\n

syntax

\n\n

([delay/thread](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%2Fthread%29%29) body/option ...+)

 
body/option = body
  | #:group thread-group-expr
\n\nLike [delay/sync](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%2Fsync%29%29), but begins the computation immediately on a newly created thread. The thread is created under the [thread group](threadgroups.html#%28tech._thread._group%29) specified by thread-group-expr, which defaults to ([make-thread-group](threadgroups.html#%28def._%28%28quote._~23~25kernel%29._make-thread-group%29%29)). A #:group specification can appear at most once.\n\nExceptions raised by the bodys are caught as usual and raised only when the promise is [force](#%28def._%28%28lib._racket%2Fpromise..rkt%29._force%29%29)d. Unlike [delay/sync](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%2Fsync%29%29), if the thread running body terminates without producing a result or exception, [force](#%28def._%28%28lib._racket%2Fpromise..rkt%29._force%29%29) of the promise raises an exception (instead of blocking).\n\n>
\n\n

syntax

\n\n

([delay/idle](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%2Fidle%29%29) body/option ...+)

 
body/option = body
  | #:wait-for wait-evt-expr
  | #:work-while while-evt-expr
  | #:tick tick-secs-expr
  | #:use use-ratio-expr
\n\nLike [delay/thread](#%28form._%28%28lib._racket%2Fpromise..rkt%29._delay%2Fthread%29%29), but with the following differences:\n\n- the computation does not start until the event produced by wait-evt-expr is ready, where the default is ([system-idle-evt](sync.html#%28def._%28%28quote._~23~25kernel%29._system-idle-evt%29%29));\n\n- the computation thread gets to work only when the process is otherwise idle as determined by while-evt-expr, which also defaults to ([system-idle-evt](sync.html#%28def._%28%28quote._~23~25kernel%29._system-idle-evt%29%29));\n\n- the thread is allowed to run only periodically: out of every tick-secs-expr (defaults to 0.2) seconds, the thread is allowed to run use-ratio-expr (defaults to 0.12) of the time proportionally; i.e., the thread runs for ([*](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._%2A%29%29) tick-secs-expr use-ratio-expr) seconds.\n\nIf the promise is forced before the computation is done, it runs the rest of the computation immediately without waiting on events or periodically restricting evaluation.\n\nA #:wait-for, #:work-while, #:tick, or #:use specification can appear at most once.\n\n> ```\nsyntax\n\n(for/list/concurrent maybe-group (for-clause ...)\n> body-or-break ... body )\n \nmaybe-group   =  \n    |   #:group thread-group-expr\n\n \n   thread-group-expr   :   thread-group?\n```"} {"text": "# 10.1 Multiple Values\nIterates like for/list, but the bodies (following any #:break or #:final clauses) are wrapped in delay/thread. Each promise is forced before the result list is returned.\nThreads are created under thread-group-expr, which defaults to (make-thread-group). An optional #:group clause may be provided, in which case the threads will be created under that thread group.\nThis form does not support returning multiple values.\nExample:\n> ```racket\n> > ( time ( for/list/concurrent ( [ i ( in-range 5 ) ] ) ( define duration ( / 1.0 ( random 50 100 ) ) ) ( sleep duration ) ( printf \"thread ~a slept for ~a milliseconds~n\" i ( truncate ( * duration 1000 ) ) ) i ) )\n> thread 4 slept for 11.0 milliseconds thread 0 slept for 11.0 milliseconds thread 1 slept for 14.0 milliseconds thread 3 slept for 16.0 milliseconds thread 2 slept for 17.0 milliseconds cpu time: 97 real time: 18 gc time: 9\n> '(0 1 2 3 4)\n> ```\nAdded in version 8.6.0.4 of package base.\n> ```\nsyntax\n(for*/list/concurrent maybe-group (for-clause ...)\n> body-or-break ... body )```\nLike [for/list/concurrent](#%28form._%28%28lib._racket%2Fpromise..rkt%29._for%2Flist%2Fconcurrent%29%29), but with the implicit nesting of [for*/list](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%2Flist%29%29).\nAdded in version 8.6.0.4 of package base.\n------------------------------------------------------------------------"} {"text": "# 10.4 Continuations"} {"text": "### 10.4 Continuations\n> > > \"+\"[Continuations](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=conts.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces continuations.\nSee [Sub-expression Evaluation and Continuations](eval-model.html#%28part._cont-model%29) and [Prompts, Delimited Continuations, and Barriers](eval-model.html#%28part._prompt-model%29) for general information about continuations. Racket’s support for prompts and composable continuations \\[[Flatt07](doc-bibliography.html#%28cite._.Flatt07%29)\\] closely resembles Sitaram’s % and fcontrol operator \\[[Sitaram93](doc-bibliography.html#%28cite._.Sitaram93%29)\\].\nRacket installs a [continuation barrier](eval-model.html#%28tech._continuation._barrier%29) around evaluation in the following contexts, preventing full-continuation jumps into the evaluation context protected by the barrier:\n- applying an exception handler, an error escape handler, or an error display handler (see [Exceptions](exns.html));\n- applying a macro transformer (see [Syntax Transformers](stxtrans.html)), evaluating a compile-time expression, or applying a module name resolver (see [Resolving Module Names](Module_Names_and_Loading.html#%28part._modnameresolver%29));"} {"text": "# 10.4 Continuations\n- applying a custom-port procedure (see [Custom Ports](customport.html)), an event guard procedure (see [Events](sync.html)), or a parameter guard procedure (see [Parameters](parameters.html));\n- applying a security-guard procedure (see [Security Guards](securityguards.html));\n- applying a will procedure (see [Wills and Executors](willexecutor.html)); or\n- evaluating or loading code from the stand-alone Racket command line (see [Running Racket or GRacket](running-sa.html)).\nIn addition, extensions of Racket may install barriers in additional contexts. Finally, [call-with-continuation-barrier](#%28def._%28%28quote._~23~25kernel%29._call-with-continuation-barrier%29%29) applies a thunk barrier between the application and the current continuation.\n> ```\n(call-with-continuation-prompt proc\n   [ prompt-tag        \n    handler]        \n    arg ...)   →   any\n  proc : procedure?\n   prompt-tag   :   continuation-prompt-tag?\n      =   (default-continuation-prompt-tag)\n  handler : (or/c procedure? #f) = #f\n  arg : any/c"} {"text": "# 10.4 Continuations\n```\n(parameter)\t→```\n\n\nResets the current continuation to that of the nearest prompt tagged by prompt-tag in the current continuation; if no such prompt exists, the [exn:fail:contract:continuation](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3acontinuation%29%29) exception is raised. The vs are delivered as arguments to the target prompt’s handler procedure.\n\nThe protocol for vs supplied to an abort is specific to the prompt-tag. When [abort-current-continuation](#%28def._%28%28quote._~23~25kernel%29._abort-current-continuation%29%29) is used with ([default-continuation-prompt-tag](#%28def._%28%28quote._~23~25kernel%29._default-continuation-prompt-tag%29%29)), generally, a single thunk should be supplied that is suitable for use with the default prompt handler. Similarly, when [call-with-continuation-prompt](#%28def._%28%28quote._~23~25kernel%29._call-with-continuation-prompt%29%29) is used with ([default-continuation-prompt-tag](#%28def._%28%28quote._~23~25kernel%29._default-continuation-prompt-tag%29%29)), the associated handler should generally accept a single thunk argument.\n\nEach [thread](eval-model.html#%28tech._thread%29)’s continuation starts with a prompt for ([default-continuation-prompt-tag](#%28def._%28%28quote._~23~25kernel%29._default-continuation-prompt-tag%29%29)) that uses the default handler, which accepts a single thunk to apply (with the prompt intact).\n\n> ```\n(make-continuation-prompt-tag)\t→\t\n(-> make-continuation-prompt-tag name)\n(make-continuation-prompt-tag name) → continuation-prompt-tag?\n name\t:\t\n(-> make-continuation-prompt-tag name)\n```"} {"text": "# 10.4 Continuations\nCreates a prompt tag that is not equal? to the result of any other value (including prior or future results from make-continuation-prompt-tag). The optional name argument, if supplied, specifies the name of the prompt tag for printing or object-name.\nChanged in version 7.9.0.13 of package base: The name argument gives the name of the prompt tag.\n> ```\n(default-continuation-prompt-tag)  →  continuation-prompt-tag?```\nReturns a constant prompt tag for which a prompt is installed at the start of every thread’s continuation; the handler for each thread’s initial prompt accepts any number of values and returns. The result of [default-continuation-prompt-tag](#%28def._%28%28quote._~23~25kernel%29._default-continuation-prompt-tag%29%29) is the default tag for any procedure that accepts a prompt tag.\n> ```\n(default-continuation-prompt-tag)\t→\t\n(-> continuation? . → . any)\n```\n(default-continuation-prompt-tag)\t→\t\n(-> continuation? . → . any)```\n\n\nThe [call/cc](#%28def._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._call%2Fcc%29%29) binding is an alias for [call-with-current-continuation](#%28def._%28%28quote._~23~25kernel%29._call-with-current-continuation%29%29).\n\n> ```\n(call-with-composable-continuation proc\n   [ prompt-tag)   →   any\n\n  proc : (continuation? . → . any)\n   prompt-tag   :   continuation-prompt-tag?\n      =   (default-continuation-prompt-tag)\n```\n(parameter)\t→\t\n(-> continuation? . → . any)```"} {"text": "# 10.4 Continuations\nLike [call-with-current-continuation](#%28def._%28%28quote._~23~25kernel%29._call-with-current-continuation%29%29), but proc is not called in tail position, and the continuation procedure supplied to proc can only be called during the dynamic extent of the [call-with-escape-continuation](#%28def._%28%28quote._~23~25kernel%29._call-with-escape-continuation%29%29) call.\nA continuation obtained from [call-with-escape-continuation](#%28def._%28%28quote._~23~25kernel%29._call-with-escape-continuation%29%29) is actually a kind of prompt. Escape continuations are provided mainly for backwards compatibility, since they pre-date general prompts in Racket. In the [BC](implementations.html#%28tech._bc%29) implementation of Racket, [call-with-escape-continuation](#%28def._%28%28quote._~23~25kernel%29._call-with-escape-continuation%29%29) is implemented more efficiently than [call-with-current-continuation](#%28def._%28%28quote._~23~25kernel%29._call-with-current-continuation%29%29), so [call-with-escape-continuation](#%28def._%28%28quote._~23~25kernel%29._call-with-escape-continuation%29%29) can sometimes replace [call-with-current-continuation](#%28def._%28%28quote._~23~25kernel%29._call-with-current-continuation%29%29) to improve performance in those older Racket variants.\n> ```\n(call/ec proc)  →  any\n  proc : (continuation? . → . any)"} {"text": "# 10.4 Continuations\n```\nThe call/ec binding is an alias for call-with-escape-continuation.\n\n> ```\n(call-in-continuation k proc)  →  any\n  k : continuation?\n  proc : ( →  any)```\n\n\nSimilar to applying the continuation k, but instead of delivering values to the continuation, proc is called with k as the continuation of the call (so the result of proc is returned to the continuation). If k is a composable continuation, the continuation of the call to proc is the current continuation extended with k.\n\nExamples:\n\n> ```racket\n> > ( + 1 ( call/cc ( lambda ( k ) ( call-in-continuation k ( lambda ( ) 4 ) ) ) ) )\n> 5\n> > ( + 1 ( call/cc ( lambda ( k ) ( let ( [ n 0 ] ) ( dynamic-wind void ( lambda ( ) ; n accessed after post thunk ( call-in-continuation k ( lambda ( ) n ) ) ) ( lambda ( ) ( set! n 4 ) ) ) ) ) ) )\n> 5\n> > ( + 1 ( with-continuation-mark ' n 4 ( call/cc ( lambda ( k ) ( with-continuation-mark ' n 0 ( call-in-continuation k ( lambda ( ) ; ' n mark accessed in continuation ( continuation-mark-set-first #f ' n ) ) ) ) ) ) ) )\n> 5\n> ```\n\nAdded in version 7.6.0.17 of package base.\n\n>
\n\n

syntax

\n\n

([let/cc](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._let%2Fcc%29%29) k body ...+)

\n\nEquivalent to ([call/cc](#%28def._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._call%2Fcc%29%29) ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) (k) body [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29))).\n\n>
\n\n

syntax

\n\n

([let/ec](#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%2Fec%29%29) k body ...+)

\n\nEquivalent to ([call/ec](#%28def._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._call%2Fec%29%29) ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) (k) body [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29))).\n\n> ```\n(call-with-continuation-barrier thunk)  →  any\n  thunk : ( →  any)\n```"} {"text": "# 10.4 Continuations\nApplies thunk with a continuation barrier between the application and the current continuation. The results of thunk are the results of the call-with-continuation-barrier call.\n> ```\n(continuation-prompt-available? prompt-tag\n   [ cont)   →   any\n  prompt-tag : continuation-prompt-tag?\n  cont : continuation? = (call/cc values)```\nReturns #t if cont, which must be a continuation, includes a prompt tagged by prompt-tag, #f otherwise.\n> ```\n(continuation? v)  →  boolean?\n  v : any/c\n```\n(parameter)\t→```\n\n\nReturns #t if v is a continuation prompt tag as produced by [default-continuation-prompt-tag](#%28def._%28%28quote._~23~25kernel%29._default-continuation-prompt-tag%29%29) or [make-continuation-prompt-tag](#%28def._%28%28quote._~23~25kernel%29._make-continuation-prompt-tag%29%29).\n\n> ```\n(dynamic-wind   pre-thunk        \n    value-thunk        \n    post-thunk)   →   any\n\n  pre-thunk : ( →  any)\n  value-thunk : ( →  any)\n  post-thunk : ( →  any)\n```\n(default-continuation-prompt-tag)\t→\t\n(-> default-continuation-prompt-tag)```\nThe [call/prompt](#%28def._%28%28lib._racket%2Fcontrol..rkt%29._call%2Fprompt%29%29) binding is an alias for [call-with-continuation-prompt](#%28def._%28%28quote._~23~25kernel%29._call-with-continuation-prompt%29%29).\n> ```\n(abort/cc prompt-tag v ...) → any\n  prompt-tag : any/c\n  v : any/c"} {"text": "# 10.4 Continuations\n```\n(default-continuation-prompt-tag)\t→\t\n(-> continuation? . → . any)```\n\n\nThe [call/comp](#%28def._%28%28lib._racket%2Fcontrol..rkt%29._call%2Fcomp%29%29) binding is an alias for [call-with-composable-continuation](#%28def._%28%28quote._~23~25kernel%29._call-with-composable-continuation%29%29).\n\n> ```\n(abort v ...) → any\n  v : any/c\n```\n(default-continuation-prompt-tag)\t→\t\n(-> default-continuation-prompt-tag)```\nSitaram’s operators \\[[Sitaram93](doc-bibliography.html#%28cite._.Sitaram93%29)\\].\nThe essential reduction rules are:\n> ```racket\n> ( % val proc ) => val\n> ( % E [ ( fcontrol val ) ] proc ) => ( proc val ( lambda ( x ) E [ x ] ) )\n> ; where E has no %\n> ```\nWhen handler-expr is omitted, [%](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._~25%29%29) is the same as [prompt](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt%29%29). If prompt-tag is provided, [%](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._~25%29%29) uses specific prompt tags like [prompt-at](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt-at%29%29).\nExamples:\n> ```racket\n> > ( % ( + 2 ( fcontrol 5 ) ) ( lambda ( v k ) ( k v ) ) )\n> 7\n> > ( % ( + 2 ( fcontrol 5 ) ) ( lambda ( v k ) v ) )\n> 5\n> ```\n>
\n

syntax

"} {"text": "# 10.4 Continuations\n

([prompt](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt%29%29) expr ...+)

\n

syntax

\n

([control](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._control%29%29) id expr ...+)

\nAmong the earliest operators for higher-order control \\[[Felleisen88a](doc-bibliography.html#%28cite._.Felleisen88a%29), [Felleisen88](doc-bibliography.html#%28cite._.Felleisen88%29), [Sitaram90](doc-bibliography.html#%28cite._.Sitaram90%29)\\].\nThe essential reduction rules are:\n> ```racket\n> ( prompt val ) => val\n> ( prompt E [ ( control k expr ) ] ) => ( prompt ( ( lambda ( k ) expr )\n> ( lambda ( v ) E [ v ] ) ) )\n> ; where E has no prompt\n> ```\nExamples:\n> ```racket\n> > ( prompt ( + 2 ( control k ( k 5 ) ) ) )\n> 7\n> > ( prompt ( + 2 ( control k 5 ) ) )\n> 5\n> > ( prompt ( + 2 ( control k ( + 1 ( control k1 ( k1 6 ) ) ) ) ) )\n> 7\n> > ( prompt ( + 2 ( control k ( + 1 ( control k1 ( k 6 ) ) ) ) ) )\n> 8\n> > ( prompt ( + 2 ( control k ( control k1 ( control k2 ( k2 6 ) ) ) ) ) )\n> 6\n> ```\n>
\n

syntax

"} {"text": "# 10.4 Continuations\n

([prompt-at](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt-at%29%29) prompt-tag-expr expr ...+)

\n

syntax

\n

([control-at](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._control-at%29%29) prompt-tag-expr id expr ...+)

\nLike [prompt](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt%29%29) and [control](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._control%29%29), but using specific prompt tags:\n> ```racket\n> ( prompt-at tag val ) => val\n> ( prompt-at tag E [ ( control-at tag k expr ) ] ) => ( prompt-at tag\n> ( ( lambda ( k ) expr )\n> ( lambda ( v ) E [ v ] ) ) )\n> ; where E has no prompt-at for tag\n> ```\n>
\n

syntax

\n

([reset](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._reset%29%29) expr ...+)

\n

syntax

\n

([shift](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._shift%29%29) id expr ...+)

"} {"text": "# 10.4 Continuations\nDanvy and Filinski’s operators \\[[Danvy90](doc-bibliography.html#%28cite._.Danvy90%29)\\].\nThe essential reduction rules are:\n> ```racket\n> ( reset val ) => val\n> ( reset E [ ( shift k expr ) ] ) => ( reset ( ( lambda ( k ) expr )\n> ( lambda ( v ) ( reset E [ v ] ) ) ) )\n> ; where E has no reset\n> ```\nThe [reset](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._reset%29%29) and [prompt](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt%29%29) forms are interchangeable.\n>
\n

syntax

\n

([reset-at](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._reset-at%29%29) prompt-tag-expr expr ...+)

\n

syntax

\n

([shift-at](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._shift-at%29%29) prompt-tag-expr identifier expr ...+)

\nLike [reset](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._reset%29%29) and [shift](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._shift%29%29), but using the specified prompt tags."} {"text": "# 10.4 Continuations\n>
\n

syntax

\n

([prompt0](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt0%29%29) expr ...+)

\n

syntax

\n

([reset0](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._reset0%29%29) expr ...+)

\n

syntax

\n

([control0](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._control0%29%29) id expr ...+)

\n

syntax

\n

([shift0](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._shift0%29%29) id expr ...+)

\nGeneralizations of [prompt](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt%29%29), etc. \\[[Shan04](doc-bibliography.html#%28cite._.Shan04%29)\\].\nThe essential reduction rules are:"} {"text": "# 10.4 Continuations\n> ```racket\n> ( prompt0 val ) => val\n> ( prompt0 E [ ( control0 k expr ) ] ) => ( ( lambda ( k ) expr )\n> ( lambda ( v ) E [ v ] ) )\n> ( reset0 val ) => val\n> ( reset0 E [ ( shift0 k expr ) ] ) => ( ( lambda ( k ) expr )\n> ( lambda ( v ) ( reset0 E [ v ] ) ) )\n> ```\nThe [reset0](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._reset0%29%29) and [prompt0](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt0%29%29) forms are interchangeable. Furthermore, the following reductions apply:\n> ```racket\n> ( prompt E [ ( control0 k expr ) ] ) => ( prompt ( ( lambda ( k ) expr )\n> ( lambda ( v ) E [ v ] ) ) )\n> ( reset E [ ( shift0 k expr ) ] ) => ( reset ( ( lambda ( k ) expr )\n> ( lambda ( v ) ( reset0 E [ v ] ) ) ) )\n> ( prompt0 E [ ( control k expr ) ] ) => ( prompt0 ( ( lambda ( k ) expr )\n> ( lambda ( v ) E [ v ] ) ) )\n> ( reset0 E [ ( shift k expr ) ] ) => ( reset0 ( ( lambda ( k ) expr )\n> ( lambda ( v ) ( reset E [ v ] ) ) ) )\n> ```\nThat is, both the [prompt](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt%29%29)/[reset](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._reset%29%29) and [control](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._control%29%29)/[shift](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._shift%29%29) sites must agree for 0-like behavior, otherwise the non-0 behavior applies.\n>
\n

syntax

"} {"text": "# 10.4 Continuations\n

([prompt0-at](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt0-at%29%29) prompt-tag-expr expr ...+)

\n

syntax

\n

([reset0-at](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._reset0-at%29%29) prompt-tag-expr expr ...+)

\n

syntax

\n

([control0-at](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._control0-at%29%29) prompt-tag-expr id expr ...+)

\n

syntax

\n

([shift0-at](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._shift0-at%29%29) prompt-tag-expr id expr ...+)

\nVariants of [prompt0](#%28form._%28%28lib._racket%2Fcontrol..rkt%29._prompt0%29%29), etc., that accept a prompt tag.\n> ```\n(spawn proc)  →  any\n  proc : ((any/c . → . any) . → . any)"} {"text": "# 10.4 Continuations\n```\nThe operators of Hieb and Dybvig \\[Hieb90\\].\n\nThe essential reduction rules are:\n\n> ```racket\n> ( spawn proc )\n> => ( prompt/spawn tag\n> ( proc ( lambda ( proc ) ( abort/spawn tag proc ) ) ) )\n> ; where tag is a freshly generated prompt tag\n> ( prompt/spawn tag val )\n> => val\n> ( prompt/spawn tag E [ ( abort/spawn tag proc ) ] )\n> => ( proc ( lambda ( x ) ( prompt/spawn tag E [ x ] ) ) )\n> ; where E has no prompt/spawn for tag\n> ```\n\n> ```\n(splitter proc) → any\n   proc   :   ( ( ( → any ) . → . any )\n> ( ( continuation? . → . any ) . → . any )\n> . → . any )```\n\n\nThe operator of Queinnec and Serpette \\[[Queinnec91](doc-bibliography.html#%28cite._.Queinnec91%29)\\].\n\nThe essential reduction rules are:\n\n> ```racket\n> ( splitter proc )\n> => ( prompt/splitter tag\n> ( proc ( lambda ( thunk ) ( abort/splitter tag thunk ) )\n> ( lambda ( proc ) ( control0/splitter tag k ( proc k ) ) ) ) )\n> ; where tag is a freshly generated prompt tag\n> ( prompt/splitter tag val )\n> => val\n> ( prompt/splitter tag E [ ( abort/splitter tag thunk ) ] )\n> => ( thunk )\n> ; where E has no prompt/splitter for tag\n> ( prompt/splitter tag E [ ( control0/splitter tag k expr ) ] )\n> => ( ( lambda ( k ) expr )\n> ( lambda ( x ) E [ x ] ) )\n> ; where E has no prompt/splitter for tag\n> ```\n\n> ```\n(new-prompt)\t→\t\n(-> new-prompt name)\n(new-prompt name) → continuation-prompt-tag?\n name\t:\t\n(-> new-prompt name)\n```\n(current-continuation-marks)\t→\t\n(-> or/c continuation? thread? #f)```"} {"text": "# 10.4 Continuations\nReturns an opaque value containing the set of continuation marks for all keys in the continuation cont (or the current continuation of cont if it is a thread) up to the prompt tagged by prompt-tag. If cont is #f, the resulting set of continuation marks is empty. If cont is an escape continuation (see [Prompts, Delimited Continuations, and Barriers](eval-model.html#%28part._prompt-model%29)), then the current continuation must extend cont, or the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. If cont was not captured with respect to prompt-tag and does not include a prompt for prompt-tag, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. If cont is a dead thread, the result is an empty set of continuation marks.\n> ```\n(default-continuation-prompt-tag)\t→\t\n(-> default-continuation-prompt-tag)"} {"text": "# 10.4 Continuations\n```\n(default-continuation-prompt-tag)\t→\t\n(-> or/c continuation-mark-set? #f)```\n\n\nReturns a newly-created list containing the marks for key-v in mark-set, which is a set of marks returned by [current-continuation-marks](#%28def._%28%28quote._~23~25kernel%29._current-continuation-marks%29%29) or #f as a shorthand for ([current-continuation-marks](#%28def._%28%28quote._~23~25kernel%29._current-continuation-marks%29%29) prompt-tag). The result list is truncated at the first point, if any, where continuation frames were originally separated by a prompt tagged with prompt-tag. Producing the result takes time proportional to the size of the continuation reflected by mark-set.\n\nChanged in version 8.0.0.1 of package base: Changed to allow mark-set as #f.\n\n> ```\n(continuation-mark-set → list* mark-set\n    key-list        \n   [ none-v        \n    prompt-tag)   →   (listof vector?)\n\n  mark-set : (or/c continuation-mark-set? #f)\n  key-list : (listof any/c)\n  none-v : any/c = #f\n   prompt-tag   :   continuation-prompt-tag?\n      =   (default-continuation-prompt-tag)\n```\n(default-continuation-prompt-tag)\t→\t\n(-> (values (or/c vector? #f) procedure?))```"} {"text": "# 10.4 Continuations\nLike [continuation-mark-set->list*](#%28def._%28%28quote._~23~25kernel%29._continuation-mark-set-~3elist%2A%29%29), but instead of returning a list of values, returns a functional iterator in the form of a procedure that returns one element of the would-be list and a new iterator function for the rest of the would-be list. An iterator procedure returns #f instead of a vector when no more elements are available; in that case, the returned iterator procedure is like the called one, producing no further values. The time required for each step is proportional to the length of key-list times the size of the segment of the continuation reflected by mark-set between frames that have keys in key-list.\nAdded in version 7.5.0.7 of package base. \nChanged in version 8.0.0.1: Changed to allow mark-set as #f.\n> ```\n(continuation-mark-set-first mark-set\n    key-v        \n   [ none-v        \n    prompt-tag)   →   any\n  mark-set : (or/c continuation-mark-set? #f)\n  key-v : any/c\n  none-v : any/c = #f\n   prompt-tag   :   continuation-prompt-tag?\n      =   (default-continuation-prompt-tag)"} {"text": "# 10.4 Continuations\n```\n(amortized)\t→\t\n(-> or mark-set (current-continuation-marks prompt-tag))```\n\n\nCalls proc with the value associated with key-v in the first frame of the current continuation (i.e., a value that would be replaced if the call to [call-with-immediate-continuation-mark](#%28def._%28%28quote._~23~25kernel%29._call-with-immediate-continuation-mark%29%29) were replaced with a [with-continuation-mark](wcm.html#%28form._%28%28quote._~23~25kernel%29._with-continuation-mark%29%29) form using key-v as the key expression). If no such value exists in the first frame, default-v is passed to proc. The proc is called in tail position with respect to the [call-with-immediate-continuation-mark](#%28def._%28%28quote._~23~25kernel%29._call-with-immediate-continuation-mark%29%29) call.\n\nThis function could be implemented with a combination of [with-continuation-mark](wcm.html#%28form._%28%28quote._~23~25kernel%29._with-continuation-mark%29%29), [current-continuation-marks](#%28def._%28%28quote._~23~25kernel%29._current-continuation-marks%29%29), and [continuation-mark-set->list*](#%28def._%28%28quote._~23~25kernel%29._continuation-mark-set-~3elist%2A%29%29), as shown below, but [call-with-immediate-continuation-mark](#%28def._%28%28quote._~23~25kernel%29._call-with-immediate-continuation-mark%29%29) is implemented more efficiently; it inspects only the first frame of the current continuation.\n\n> ```racket\n> ; Equivalent, but inefficient:\n> ( define ( call-with-immediate-continuation-mark key-v proc [ default-v #f ] )\n> ( define private-key ( gensym ) )\n> ( with-continuation-mark\n> private-key #t\n> ( let ( [ vecs ( continuation-mark-set->list* ( current-continuation-marks )\n> ( list key-v private-key )\n> default-v ) ] )\n> ( proc ( vector-ref ( car vecs ) 0 ) ) ) ) )\n> ```\n\n> ```\n(make-continuation-mark-key)\t→\t\n(-> make-continuation-mark-key sym)\n(make-continuation-mark-key sym) → continuation-mark-key?\n sym\t:\t\n(-> make-continuation-mark-key sym)\n```"} {"text": "# 10.4 Continuations\nCreates a continuation mark key that is not equal? to the result of any other value (including prior and future results from make-continuation-mark-key). The continuation mark key can be used as the key argument for with-continuation-mark or accessor procedures like continuation-mark-set-first. The mark key can be chaperoned or impersonated, unlike other values that are used as the mark key.\nThe optional sym argument, if provided, is used when printing the continuation mark.\n> ```\n(continuation-mark-key? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a mark key created by [make-continuation-mark-key](#%28def._%28%28quote._~23~25kernel%29._make-continuation-mark-key%29%29), #f otherwise.\n> ```\n(continuation-mark-set? v)  →  boolean?\n  v : any/c"} {"text": "# 10.4 Continuations\n```\n(parameter)\t→```\n\n\nReturns a list representing an approximate “stack trace” for mark-set’s continuation. The list contains pairs if realms? is #f, where the [car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) of each pair contains either #f or a symbol for a procedure name, and the [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) of each pair contains either #f or a [srcloc](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29) value for the procedure’s source location (see [Counting Positions, Lines, and Columns](linecol.html)); the [car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) and [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) are never both #f. If realms? is true, the list contains 3-element vectors, where the first two elements are like the values for a pair, and the third element is a realm symbol.\n\nConceptually, the stack-trace list is the result of [continuation-mark-set->list](#%28def._%28%28quote._~23~25kernel%29._continuation-mark-set-~3elist%29%29) with mark-set and Racket’s private key for procedure-call marks. The implementation may be different, however, and the results may merely approximate the correct answer. Thus, while the result may contain useful hints to humans about the context of an expression, it is not reliable enough for programmatic use.\n\nA stack trace is extracted from an exception and displayed by the default error display handler (see [error-display-handler](exns.html#%28def._%28%28quote._~23~25kernel%29._error-display-handler%29%29)) for exceptions other than [exn:fail:user](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3auser%29%29) (see [raise-user-error](exns.html#%28def._%28%28quote._~23~25kernel%29._raise-user-error%29%29) in [Raising Exceptions](exns.html#%28part._errorproc%29)).\n\nExamples:\n\n> ```racket\n> > ( define ( extract-current-continuation-marks key ) ( continuation-mark-set->list ( current-continuation-marks ) key ) )\n> > ( with-continuation-mark ' key ' mark ( extract-current-continuation-marks ' key ) )\n> '(mark)\n> > ( with-continuation-mark ' key1 ' mark1 ( with-continuation-mark ' key2 ' mark2 ( list ( extract-current-continuation-marks ' key1 ) ( extract-current-continuation-marks ' key2 ) ) ) )\n> '((mark1) (mark2))\n> > ( with-continuation-mark ' key ' mark1 ( with-continuation-mark ' key ' mark2 ; replaces previous mark ( extract-current-continuation-marks ' key ) ) )\n> '(mark2)\n> > ( with-continuation-mark ' key ' mark1 ( list ; continuation extended to evaluate the argument ( with-continuation-mark ' key ' mark2 ( extract-current-continuation-marks ' key ) ) ) )\n> '((mark2 mark1))\n> > ( let loop ( [ n 1000 ] ) ( if ( zero? n ) ( extract-current-continuation-marks ' key ) ( with-continuation-mark ' key n ( loop ( sub1 n ) ) ) ) )\n> '(1)\n> ```\n\nChanged in version 8.4.0.2 of package base: Added the realms? argument.\n\n------------------------------------------------------------------------\n\n# 10.6 Breaks\n\n### 10.6 Breaks\n\nA break is an asynchronous exception, usually triggered through an external source controlled by the user, or through the [break-thread](threads.html#%28def._%28%28quote._~23~25kernel%29._break-thread%29%29) procedure. For example, the user may type Ctl-C in a terminal to trigger a break. On some platforms, the Racket process may receive SIGINT, SIGHUP, or SIGTERM; the latter two correspond to hang-up and terminate breaks as reflected by [exn:break:hang-up](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak~3ahang-up%29%29) and [exn:break:terminate](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak~3aterminate%29%29), respectively. Multiple breaks may be collapsed into a single exception, and multiple breaks of different kinds may be collapsed to a single “strongest” break, where a terminate break is stronger than a hang-up break which is stronger than an interrupt break.\n\nA break exception can only occur in a thread while breaks are enabled. When a break is detected and enabled, the [exn:break](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak%29%29) (or [exn:break:hang-up](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak~3ahang-up%29%29) or [exn:break:terminate](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak~3aterminate%29%29)) exception is raised in the thread sometime afterward; if breaking is disabled when [break-thread](threads.html#%28def._%28%28quote._~23~25kernel%29._break-thread%29%29) is called, the break is suspended until breaking is again enabled for the thread. While a thread has a suspended break, additional breaks are ignored.\n\nBreaks are enabled through the [break-enabled](#%28def._%28%28quote._~23~25kernel%29._break-enabled%29%29) parameter-like procedure and through the [parameterize-break](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize-break%29%29) form, which is analogous to [parameterize](parameters.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize%29%29). The [break-enabled](#%28def._%28%28quote._~23~25kernel%29._break-enabled%29%29) procedure does not represent a parameter to be used with [parameterize](parameters.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize%29%29), because changing the break-enabled state of a thread requires an explicit check for breaks, and this check is incompatible with the tail evaluation of a [parameterize](parameters.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize%29%29) expression’s body.\n\nCertain procedures, such as [semaphore-wait/enable-break](semaphore.html#%28def._%28%28quote._~23~25kernel%29._semaphore-wait%2Fenable-break%29%29), enable breaks temporarily while performing a blocking action. If breaks are enabled for a thread, and if a break is triggered for the thread but not yet delivered as an [exn:break](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak%29%29) exception, then the break is guaranteed to be delivered before breaks can be disabled in the thread. The timing of [exn:break](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak%29%29) exceptions is not guaranteed in any other way.\n\nBefore calling a [with-handlers](exns.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._with-handlers%29%29) predicate or handler, an exception handler, an error display handler, an error escape handler, an error value conversion handler, or a pre-thunk or post-thunk for a [dynamic-wind](cont.html#%28def._%28%28quote._~23~25kernel%29._dynamic-wind%29%29), the call is [parameterize-break](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize-break%29%29)ed to disable breaks. Furthermore, breaks are disabled during the transitions among handlers related to exceptions, during the transitions between pre-thunks and post-thunks for [dynamic-wind](cont.html#%28def._%28%28quote._~23~25kernel%29._dynamic-wind%29%29), and during other transitions for a continuation jump. For example, if breaks are disabled when a continuation is invoked, and if breaks are also disabled in the target continuation, then breaks will remain disabled from the time of the invocation until the target continuation executes unless a relevant [dynamic-wind](cont.html#%28def._%28%28quote._~23~25kernel%29._dynamic-wind%29%29) pre-thunk or post-thunk explicitly enables breaks.\n\nIf a break is triggered for a thread that is blocked on a nested thread (see [call-in-nested-thread](threads.html#%28def._%28%28quote._~23~25kernel%29._call-in-nested-thread%29%29)), and if breaks are enabled in the blocked thread, the break is implicitly handled by transferring it to the nested thread.\n\nWhen breaks are enabled, they can occur at any point within execution, which makes certain implementation tasks subtle. For example, assuming breaks are enabled when the following code is executed,\n\n> ```racket\n> ( with-handlers ( [ exn:break? ( lambda ( x ) ( void ) ) ] )\n> ( semaphore-wait s ) )\n> ```\n\nthen it is not the case that a [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13) result means the semaphore was decremented or a break was received, exclusively. It is possible that both occur: the break may occur after the semaphore is successfully decremented but before a [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13) result is returned by [semaphore-wait](semaphore.html#%28def._%28%28quote._~23~25kernel%29._semaphore-wait%29%29). A break exception will never damage a semaphore, or any other built-in construct, but many built-in procedures (including [semaphore-wait](semaphore.html#%28def._%28%28quote._~23~25kernel%29._semaphore-wait%29%29)) contain internal sub-expressions that can be interrupted by a break.\n\nIn general, it is impossible using only [semaphore-wait](semaphore.html#%28def._%28%28quote._~23~25kernel%29._semaphore-wait%29%29) to implement the guarantee that either the semaphore is decremented or an exception is raised, but not both. Racket therefore supplies [semaphore-wait/enable-break](semaphore.html#%28def._%28%28quote._~23~25kernel%29._semaphore-wait%2Fenable-break%29%29) (see [Semaphores](semaphore.html)), which does permit the implementation of such an exclusive guarantee:\n\n> ```racket\n> ( parameterize-break #f\n> ( with-handlers ( [ exn:break? ( lambda ( x ) ( void ) ) ] )\n> ( semaphore-wait/enable-break s ) ) )\n> ```\n\nIn the above expression, a break can occur at any point until breaks are disabled, in which case a break exception is propagated to the enclosing exception handler. Otherwise, the break can only occur within [semaphore-wait/enable-break](semaphore.html#%28def._%28%28quote._~23~25kernel%29._semaphore-wait%2Fenable-break%29%29), which guarantees that if a break exception is raised, the semaphore will not have been decremented.\n\nTo allow similar implementation patterns over blocking port operations, Racket provides [read-bytes-avail!/enable-break](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-bytes-avail%21%2Fenable-break%29%29), [write-bytes-avail/enable-break](Byte_and_String_Output.html#%28def._%28%28quote._~23~25kernel%29._write-bytes-avail%2Fenable-break%29%29), and other procedures.\n\n> ```\n(break-enabled)\t→\t\n(-> break-enabled on?)\n```"} {"text": "# 10.4 Continuations\n(current-break-parameterization)\t→```\nAnalogous to ([current-parameterization](parameters.html#%28def._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._current-parameterization%29%29)) (see [Parameters](parameters.html)); it returns a break parameterization (effectively, a thread cell) that holds the current continuation’s break-enable state.\n> ```\n(call-with-break-parameterization   break-param        \n    thunk)   →   any\n  break-param : break-parameterization?\n  thunk : ( →  any)\n```\n(parameter)\t→```\n\n\nReturns #t if v is a break parameterization as produced by [current-break-parameterization](#%28def._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._current-break-parameterization%29%29), #f otherwise.\n\nAdded in version 6.1.1.8 of package base.\n\n------------------------------------------------------------------------\n\n# 10.7 Exiting\n\n### 10.7 Exiting\n\n> ```\n(exit [v) → any\n  v : any/c = #t\n```\n(exit-handler)\t→\t\n(-> any/c . → . any)\n(exit-handler proc) → void?\n proc\t:\t\n(-> any/c . → . any)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the current exit handler. The [exit handler](#%28tech._exit._handler%29) is called by [exit](#%28def._%28%28quote._~23~25kernel%29._exit%29%29)."} {"text": "# 10.4 Continuations\nThe default [exit handler](#%28tech._exit._handler%29) in the Racket executable takes any argument, calls [plumber-flush-all](plumbers.html#%28def._%28%28quote._~23~25kernel%29._plumber-flush-all%29%29) on the original plumber, and shuts down the OS-level Racket process. The argument is used as the OS-level exit code if it is an exact integer between 1 and 255 (which normally means “failure”); otherwise, the exit code is 0, (which normally means “success”).\n> ```\n(executable-yield-handler)\t→\t\n(-> byte? . → . any)\n(executable-yield-handler proc) → void?\n proc\t:\t\n(-> byte? . → . any)"} {"text": "# 10.4 Continuations\n```\n(assert-unreachable)\t→```\n\n\nReports an assertion failure by raising [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29), which is useful as a safe counterpart to [unsafe-assert-unreachable](unsafe.html#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-assert-unreachable%29%29).\n\nAdded in version 8.0.0.11 of package base.\n\n#### 10.8.1 Customized Unreachable Reporting\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/unreachable](#%28mod-path._racket%2Funreachable%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/unreachable](#%28mod-path._racket%2Funreachable%29) library, not [racket/base](index.html) or [racket](index.html).\n\nAdded in version 8.0.0.11 of package base.\n\n> ```\nsyntax\n\n(with-assert-unreachable\n> body ...+ )\n```"} {"text": "# 10.4 Continuations\n(assert-unreachable)\t→\t\n(-> any)```\nCalls thunk with no arguments in a new thread of control. The [thread](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._thread%29%29) procedure returns immediately with a thread descriptor value. When the invocation of thunk returns, the thread created to invoke thunk terminates.\nThe resulting thread is a [coroutine thread](eval-model.html#%28tech._coroutine._thread%29) if pool is #f. If pool is 'own, then a new [parallel thread pool](#%28tech._parallel._thread._pool%29) is created, the thread is added to the pool, and the pool is closed (in the sense of [parallel-thread-pool-close](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._parallel-thread-pool-close%29%29)) to additional threads. If pool is a parallel thread pool, then the new thread is created in that pool, meaning that it shares processor resources with other threads in the same pool. See [Parallel Threads](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=parallelism.html%23%2528part._parallel-threads%2529&version=8.18.0.13) for information about parallel threads and performance. Parallel threads do not run in parallel on the [BC](implementations.html#%28tech._bc%29) variant of Racket or when Racket is built without support for parallelism. For more information, see the description of [parallel thread pools](#%28tech._parallel._thread._pool%29)."} {"text": "# 10.4 Continuations\nIf keep is 'results, results are recorded with the thread so that they can be reported by [thread-wait](#%28def._%28%28quote._~23~25kernel%29._thread-wait%29%29). Otherwise, then the results of thunk are ignored.\nChanged in version 8.18.0.2 of package base: Added the #:pool and #:keep arguments.\n> ```\n(thread? v)  →  thread?\n  v : any/c\n```\n(current-thread)\t→```\n\n\nReturns the [thread descriptor](#%28tech._thread._descriptor%29) for the currently executing thread.\n\n> ```\n(thread/suspend-to-kill thunk)  →  thread?\n  thunk : ( →  any)\n```\n(current-custodian)\t→\t\n(-> any)```\nCreates a nested thread managed by cust to execute thunk. (The nested thread’s current custodian is inherited from the creating thread, independent of the cust argument.) The current thread blocks until thunk returns, and the result of the [call-in-nested-thread](#%28def._%28%28quote._~23~25kernel%29._call-in-nested-thread%29%29) call is the result returned by thunk.\nThe nested thread’s exception handler is initialized to a procedure that jumps to the beginning of the thread and transfers the exception to the original thread. The handler thus terminates the nested thread and re-raises the exception in the original thread."} {"text": "# 10.4 Continuations\nIf the thread created by [call-in-nested-thread](#%28def._%28%28quote._~23~25kernel%29._call-in-nested-thread%29%29) dies before thunk returns, the [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) exception is raised in the original thread. If the original thread is killed before thunk returns, a break is queued for the nested thread.\nIf a break is queued for the original thread (with [break-thread](#%28def._%28%28quote._~23~25kernel%29._break-thread%29%29)) while the nested thread is running, the break is redirected to the nested thread. If a break is already queued on the original thread when the nested thread is created, the break is moved to the nested thread. If a break remains queued on the nested thread when it completes, the break is moved to the original thread.\nIf the thread created by [call-in-nested-thread](#%28def._%28%28quote._~23~25kernel%29._call-in-nested-thread%29%29) dies while itself in a call to [call-in-nested-thread](#%28def._%28%28quote._~23~25kernel%29._call-in-nested-thread%29%29), the outer call to [call-in-nested-thread](#%28def._%28%28quote._~23~25kernel%29._call-in-nested-thread%29%29) waits for the innermost nested thread to complete, and any breaks pending on the inner threads are moved to the original thread."} {"text": "#### 11.1.2 Suspending, Resuming, and Killing Threads\n> ```\n(parameter)\t→\n```\n(parameter)\t→\t\n(-> or/c thread? custodian? #f)```\n\n\nResumes the execution of thd if it is suspended and has at least one custodian (possibly added through benefactor, as described below). If the thread has terminated, or if the thread is already running and benefactor is not supplied, or if the thread has no custodian and benefactor is not supplied, then [thread-resume](#%28def._%28%28quote._~23~25kernel%29._thread-resume%29%29) has no effect. Otherwise, if benefactor is supplied, it triggers up to three additional actions:\n\n- If benefactor is a thread, whenever it is resumed from a suspended state in the future, then thd is also resumed. (Resuming thd may trigger the resumption of other threads that were previously attached to thd through [thread-resume](#%28def._%28%28quote._~23~25kernel%29._thread-resume%29%29).)\n\n- New custodians may be added to thd’s set of managers. If benefactor is a thread, then all of the thread’s custodians are added to thd. Otherwise, benefactor is a custodian, and it is added to thd (unless the custodian is already shut down). If thd becomes managed by both a custodian and one or more of its subordinates, the redundant subordinates are removed from thd. If thd is suspended and a custodian is added, then thd is resumed only after the addition.\n\n- If benefactor is a thread, whenever it receives a new managing custodian in the future, then thd also receives the custodian. (Adding custodians to thd may trigger adding the custodians to other threads that were previously attached to thd through [thread-resume](#%28def._%28%28quote._~23~25kernel%29._thread-resume%29%29).)\n\n> ```\n(parameter)\t→\n```"} {"text": "# 10.4 Continuations\n(parameter)\t→\t\n(-> or/c #f 'hang-up 'terminate)```\nRegisters a break with the specified thread. The optional kind value indicates the kind of break to register, where #f, 'hang-up, and 'terminate correspond to interrupt, hang-up, and terminate breaks respectively. If breaking is disabled in thd, the break will be ignored until breaks are re-enabled. See [Breaks](breakhandler.html) for details.\n> ```\n(parameter)\t→\t\n(-> =/c 0)\n```\n\n\nCauses the current thread to sleep until at least secs seconds have passed after it starts sleeping. A zero value for secs simply acts as a hint to allow other threads to execute. The value of secs can be a non-integer to request a sleep duration to any precision; the precision of the actual sleep time is unspecified.\n\n> ```\n(thread-running? thd)  →  any\n  thd : thread?\n```\nReturns #t if thd has not terminated and is not suspended, #f otherwise.\n> ```\n(thread-dead? thd)  →  any\n  thd : thread?"} {"text": "# 10.4 Continuations\n```\nReturns #t if thd has terminated, #f otherwise.\n\n#### 11.1.3 Synchronizing Thread State\n\n> ```\n(thread-wait thd [fail-k) → any\n  thd : thread?\n  fail-k : (procedure-arity-includes/c 0) = void```\n\n\nBlocks execution of the current thread until thd has terminated. If the thread’s procedure raised an exception or otherwise aborted to the thread’s initial [prompt](eval-model.html#%28tech._prompt%29), fail-k is called to produce the result of [thread-wait](#%28def._%28%28quote._~23~25kernel%29._thread-wait%29%29). Otherwise, if the thread records its results (see #:keep in [thread](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._thread%29%29)), those results are returned, while [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13) is return if the thread does not keep its results.\n\nNote that ([thread-wait](#%28def._%28%28quote._~23~25kernel%29._thread-wait%29%29) ([current-thread](#%28def._%28%28quote._~23~25kernel%29._current-thread%29%29))) deadlocks the current thread, but a break can end the deadlock if breaking is enabled and if the thread is the main thread or otherwise accessible; see [Breaks](breakhandler.html).\n\nUnless thd was created with [thread/suspend-to-kill](#%28def._%28%28quote._~23~25kernel%29._thread%2Fsuspend-to-kill%29%29), a ([thread-wait](#%28def._%28%28quote._~23~25kernel%29._thread-wait%29%29) thd) may potentially continue even if thd is otherwise inaccessible, because a [custodian](eval-model.html#%28tech._custodian%29) shut down could terminate the thread. As a result, a thread blocking with [thread-wait](#%28def._%28%28quote._~23~25kernel%29._thread-wait%29%29) normally cannot be garbage collected (see [Garbage Collection](eval-model.html#%28part._gc-model%29)). As a special case, however, ([thread-wait](#%28def._%28%28quote._~23~25kernel%29._thread-wait%29%29) thd) blocks without preventing garbage collection of the thread if thd is the current thread, since the thread could only continue if a break escapes from the wait.\n\nChanged in version 8.18.0.2 of package base: Added support for threads with values and the fail-k argument.\n\n> ```\n(thread-dead-evt thd)  →  evt?\n  thd : thread?\n```"} {"text": "# 10.4 Continuations\nReturns a synchronizable event (see Events) that is ready for synchronization if and only if thd has terminated. Unlike using thd directly, however, retaining a reference to the event does not prevent thd from being garbage collected (see Garbage Collection). The synchronization result of a thread-dead event is the thread-dead event itself.\nA thread waiting on the result of (thread-dead-evt thd) normally cannot itself be garbage collected, unless thd was created with thread/suspend-to-kill, along the same lines as waiting via thread-wait. However, there is no special case for waiting on the result of (thread-dead-evt thd) where thd is the current thread.\nFor a given thd, thread-dead-evt always returns the same (i.e., eq?) result.\n> ```\n(thread-resume-evt thd)  →  evt?\n  thd : thread?```"} {"text": "# 10.4 Continuations\nReturns a [synchronizable event](sync.html#%28tech._synchronizable._event%29) (see [Events](sync.html)) that becomes [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29) when thd is running. (If thd has terminated, the event never becomes ready.) If thd runs and is then suspended after a call to [thread-resume-evt](#%28def._%28%28quote._~23~25kernel%29._thread-resume-evt%29%29), the result event remains ready; after each suspend of thd a fresh event is generated to be returned by [thread-resume-evt](#%28def._%28%28quote._~23~25kernel%29._thread-resume-evt%29%29). The result of the event is thd, but if thd is never resumed, then reference to the event does not prevent thd from being garbage collected (see [Garbage Collection](eval-model.html#%28part._gc-model%29)).\n> ```\n(thread-suspend-evt thd)  →  evt?\n  thd : thread?"} {"text": "# 10.4 Continuations\n```\nReturns a synchronizable event (see Events) that becomes ready for synchronization when thd is suspended. (If thd has terminated, the event will never unblock.) If thd is suspended and then resumes after a call to thread-suspend-evt, the result event remains ready; each resume of thd creates a fresh event to be returned by thread-suspend-evt. The result of the event is thd, but if thd was created with thread (as opposed to thread/suspend-to-kill) and is never resumed, then reference to the event does not prevent thd from being garbage collected (see Garbage Collection).\n\nIf thd was created with thread/suspend-to-kill, then waiting on (thread-suspend-evt thd) prevents garbage collection of the waiting thread in the same way as (thread-dead-evt another-thd) for a another-thd created via thread. Furthermore, since the event result is thd, waiting on (thread-suspend-evt thd) prevents garbage collection of thd.\n\n#### 11.1.4 Thread Mailboxes\n\nEach thread has a mailbox through which it can receive arbitrary messages. In other words, each thread has a built-in asynchronous channel.\n\n> > > \"+\"See also Buffered Asynchronous Channels.\n\n> ```\n(thread-send thd v [fail-thunk) → any\n  thd : thread?\n  v : any/c\n   fail-thunk   :   (or/c ( →  any) #f)\n      =   (lambda () (raise-mismatch-error ....))```\n\n\nQueues v as a message to thd without blocking. If the message is queued, the result is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13). If thd stops running—as in [thread-running?](#%28def._%28%28quote._~23~25kernel%29._thread-running~3f%29%29)—before the message is queued, then fail-thunk is called (through a tail call) if it is a procedure to produce the result, or #f is returned if fail-thunk is #f.\n\n> ```\n(thread-receive)  →  any/c\n```"} {"text": "# 10.4 Continuations\nReceives and dequeues a message queued for the current thread, if any. If no message is available, thread-receive blocks until one is available.\n> ```\n(thread-try-receive)  →  any/c```\nReceives and dequeues a message queued for the current thread, if any, or returns #f immediately if no message is available.\n> ```\n(thread-receive-evt)  →  evt?\n```\n(parameter)\t→```\n\n\nPushes the elements of lst back onto the front of the current thread’s queue. The elements are pushed one by one, so that the first available message is the last element of lst.\n\n#### 11.1.5 Parallel Thread Pools\n\n> ```\n(parallel-thread-pool? v)  →  thread?\n  v : any/c\n```\nReturns #t if v is a parallel thread pool, #f otherwise.\nAdded in version 8.18.0.2 of package base.\n> ```\n(make-parallel-thread-pool [n) → parallel-thread-pool?\n  n : exact-positive-integer? = (processor-count)```\nCreates a parallel thread pool that can be used to group a [parallel thread](eval-model.html#%28tech._parallel._thread%29) with other parallel threads. The threads in a pool can use up to n processors to run. If more than n threads are in the pool, not all of them will run in parallel, but they will still all run concurrently."} {"text": "# 10.4 Continuations\nThe new thread pool is placed into the management of the current [custodian](eval-model.html#%28tech._custodian%29). If the custodian is shut down, then the pool is closed in the same way as with [parallel-thread-pool-close](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._parallel-thread-pool-close%29%29), but in addition, no parallel threads in the pool will be able to continue. The threads will not count as terminated (since each thread has its own custodians for that purpose), but they will cease to make progress.\nA parallel thread pool cannot run threads in parallel on the [BC](implementations.html#%28tech._bc%29) variant of Racket or when Racket is compiled without support for parallelism. In that case, parallel threads behave the same as [coroutine threads](eval-model.html#%28tech._coroutine._thread%29). For the [CS](implementations.html#%28tech._c%29) variant of Racket, the [futures-enabled?](futures.html#%28def._%28%28lib._racket%2Ffuture..rkt%29._futures-enabled~3f%29%29) predicate can be used to detect when parallel threads behave differently from coroutine threads.\nAdded in version 8.18.0.2 of package base.\n> ```\n(parameter)\t→"} {"text": "# 10.4 Continuations\n```\nCloses a parallel thread pool so that no threads can be added to the pool. Any existing threads in the pool are allowed to continue running, and they continue to share the pool’s processor resources.\n\nWhen no more threads are running within a closed thread pool, or when no threads are allowed to make progress because the pool’s custodian has been shut down, then processor resources allocated to the pool can be returned to the operating system (i.e., operating-system threads allocated to the pool are terminated).\n\nAdded in version 8.18.0.2 of package base.\n\n------------------------------------------------------------------------\n\n# 11.2 Synchronization\n\n### 11.2 Synchronization\n\nRacket’s synchronization toolbox spans four layers:\n\n- synchronizable events — a general framework for synchronization;\n\n- channels — a primitive that can be used, in principle, to build most other kinds of synchronizable events (except the ones that compose events); and\n\n- semaphores — a simple and especially cheap primitive for synchronization.\n\n- future semaphores — a simple synchronization primitive for use with futures.\n\n| |\n|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n|     11.2.1 Events |\n|     11.2.2 Channels |\n|     11.2.3 Semaphores |\n|     11.2.4 Buffered Asynchronous Channels |\n|       11.2.4.1 Creating and Using Asynchronous Channels |\n|       11.2.4.2 Contracts and Impersonators on Asynchronous Channels |\n\n------------------------------------------------------------------------\n\n# 11.2.1 Events\n\n#### 11.2.1 Events\n\nA synchronizable event (or just event for short) works with the sync procedure to coordinate synchronization among threads. Certain kinds of objects double as events, including ports and threads. Other kinds of objects exist only for their use as events. Racket’s event system is based on Concurrent ML \\[Reppy99\\].\n\nAt any point in time, an event is either ready for synchronization, or it is not; depending on the kind of event and how it is used by other threads, an event can switch from not ready to ready (or back), at any time. If a thread synchronizes on an event when it is ready, then the event produces a particular synchronization result.\n\nSynchronizing an event may affect the state of the event. For example, when synchronizing a semaphore, then the semaphore’s internal count is decremented, just as with semaphore-wait. For most kinds of events, however (such as a port), synchronizing does not modify the event’s state.\n\nRacket values that act as synchronizable events include asynchronous channels, channels, custodian boxes, log receivers, place channels, ports, semaphores, subprocesses, TCP listeners, threads, and will executors. Libraries can define new synchronizable events, especially though prop:evt.\n\n> ```\n(evt? v) → boolean?\n  v : any/c```\n\n\nReturns #t if v is a [synchronizable event](#%28tech._synchronizable._event%29), #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( evt? never-evt )\n> #t\n> > ( evt? ( make-channel ) )\n> #t\n> > ( evt? 5 )\n> #f\n> ```\n\n> ```\n(sync evt ...) → any\n  evt : evt?\n```"} {"text": "# 10.4 Continuations\n(parameter)\t→\t\n(-> or/c #f (and/c real? (not/c negative?)) (→ any))```\nLike [sync](#%28def._%28%28quote._~23~25kernel%29._sync%29%29) if timeout is #f. If timeout is a real number, then the result is #f if timeout seconds pass without a successful synchronization. If timeout is a procedure, then it is called in tail position if polling the evts discovers no ready events.\nA zero value for timeout is equivalent to ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) () #f). In either case, each evt is checked at least once before returning #f or calling timeout.\nSee also [alarm-evt](#%28def._%28%28quote._~23~25kernel%29._alarm-evt%29%29) for an alternative timeout mechanism.\nExamples:\n> ```racket\n> ; times out before waking up\n> > ( sync/timeout 0.5 ( thread ( λ ( ) ( sleep 1 ) ( displayln \"woke up!\" ) ) ) )\n> #f\n> > ( sync/timeout ( λ ( ) ( displayln \"no ready events\" ) ) never-evt )\n> no ready events\n> ```\nChanged in version 6.1.0.3 of package base: Allow 1 argument instead of 2 or more.\n> ```\n(sync/enable-break evt ...) → any\n  evt : evt?"} {"text": "# 10.4 Continuations\n```\nLike sync, but breaking is enabled (see Breaks) while waiting on the evts. If breaking is disabled when sync/enable-break is called, then either all evts remain unchosen or the exn:break exception is raised, but not both.\n\n> ```\n(sync/timeout/enable-break timeout evt ...) → any\n  timeout : (or/c #f (and/c real? (not/c negative?)) ( →  any))\n  evt : evt?```\n\n\nLike [sync/enable-break](#%28def._%28%28quote._~23~25kernel%29._sync%2Fenable-break%29%29), but with a timeout as for [sync/timeout](#%28def._%28%28quote._~23~25kernel%29._sync%2Ftimeout%29%29).\n\n> ```\n(choice-evt evt ...) → evt?\n  evt : evt?\n```\nCreates and returns a single event that combines the evts. Supplying the result to sync is the same as supplying each evt to the same call.\nThat is, an event returned by choice-evt is ready for synchronization when one or more of the evts supplied to choice-evt are ready for synchronization. If the choice event is chosen, one of its ready evts is chosen pseudo-randomly, and the synchronization result is the chosen evt’s synchronization result.\nExamples:\n> ```racket\n> > ( define ch1 ( make-channel ) )\n> > ( define ch2 ( make-channel ) )\n> > ( define either-channel ( choice-evt ch1 ch2 ) )\n> > ( thread ( λ ( ) ( displayln ( sync either-channel ) ) ) )\n> #\n> > ( channel-put ( if ( > ( random ) 0.5 ) ch1 ch2 ) ' tuturuu )\n> tuturuu\n> ```\n> ```\n(wrap-evt evt wrap) → evt?\n  evt : evt?\n  wrap : (any/c ... . → . any)```"} {"text": "# 10.4 Continuations\nCreates an event that is [ready for synchronization](#%28tech._ready._for._synchronization%29) when evt is [ready for synchronization](#%28tech._ready._for._synchronization%29), but whose [synchronization result](#%28tech._synchronization._result%29) is determined by applying wrap to the [synchronization result](#%28tech._synchronization._result%29) of evt. The number of arguments accepted by wrap must match the number of values for the synchronization result of evt.\nThe call to wrap is [parameterize-break](breakhandler.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize-break%29%29)ed to disable breaks initially.\nExamples:\n> ```racket\n> > ( define ch ( make-channel ) )\n> > ( define evt ( wrap-evt ch ( λ ( v ) ( format \"you've got mail: ~a\" v ) ) ) )\n> > ( thread ( λ ( ) ( displayln ( sync evt ) ) ) )\n> #\n> > ( channel-put ch \"Dear Alice ...\" )\n> you've got mail: Dear Alice ...\n> ```\n> ```\n(handle-evt evt handle) → handle-evt?\n  evt : evt?\n  handle : (any/c ... . → . any)"} {"text": "# 10.4 Continuations\n```\nLike wrap-evt, except that handle is called in tail position with respect to the synchronization request—and without breaks explicitly disabled—when it is not wrapped by wrap-evt, chaperone-evt, or another handle-evt.\n\nExamples:\n\n> ```racket\n> > ( define msg-ch ( make-channel ) )\n> > ( define exit-ch ( make-channel ) )\n> > ( thread ( λ ( ) ( let loop ( [ val 0 ] ) ( printf \"val = ~a~n\" val ) ( sync ( handle-evt msg-ch ( λ ( val ) ( loop val ) ) ) ( handle-evt exit-ch ( λ ( val ) ( displayln val ) ) ) ) ) ) )\n> val = 0\n> #\n> > ( channel-put msg-ch 5 )\n> val = 5\n> > ( channel-put msg-ch 7 )\n> val = 7\n> > ( channel-put exit-ch ' done )\n> done\n> ```\n\n> ```\n(guard-evt maker) → evt?\n  maker : ( →  (or/c evt? any/c))```\n\n\nCreates a value that behaves as an event, but that is actually an event maker.\n\nAn event guard returned by [guard-evt](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._guard-evt%29%29) generates an event when guard is used with [sync](#%28def._%28%28quote._~23~25kernel%29._sync%29%29) (or whenever it is part of a choice event used with [sync](#%28def._%28%28quote._~23~25kernel%29._sync%29%29), etc.), where the generated event is the result of calling maker. The maker procedure may be called by [sync](#%28def._%28%28quote._~23~25kernel%29._sync%29%29) at most once for a given call to [sync](#%28def._%28%28quote._~23~25kernel%29._sync%29%29), but maker may not be called if a ready event is chosen before guard is even considered.\n\nIf maker returns a non-event, then maker’s result is replaced with an event that is [ready for synchronization](#%28tech._ready._for._synchronization%29) and whose [synchronization result](#%28tech._synchronization._result%29) is guard.\n\n> ```\n(nack-guard-evt maker)  →  evt?\n  maker : (evt? . → . (or/c evt? any/c))\n```"} {"text": "# 10.4 Continuations\nLike guard-evt, but when maker is called, it is given a NACK (“negative acknowledgment”) event. After starting the call to maker, if the event from maker is not ultimately chosen as the ready event, then the NACK event supplied to maker becomes ready for synchronization with a # value.\nThe NACK event becomes ready for synchronization when the event is abandoned when either some other event is chosen, the synchronizing thread is dead, or control escapes from the call to sync (even if nack-guard’s maker has not yet returned a value). If the event returned by maker is chosen, then the NACK event never becomes ready for synchronization.\n> ```\n(poll-guard-evt maker)  →  evt?\n  maker : (boolean? . → . (or/c evt? any/c))```\nLike [guard-evt](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._guard-evt%29%29), but when maker is called, it is provided a boolean value that indicates whether the event will be used for a poll, #t, or for a blocking synchronization, #f.\nIf #t is supplied to maker, if breaks are disabled, if the polling thread is not terminated, and if polling the resulting event produces a [synchronization result](#%28tech._synchronization._result%29), then the event will certainly be chosen for its result.\n> ```\n(replace-evt evt maker) → evt?\n  evt : evt?\n  maker : (any/c ... . → . (or/c evt? any/c))"} {"text": "# 10.4 Continuations\n```\nLike guard-evt, but maker is called only after evt becomes ready for synchronization, and the synchronization result of evt is passed to maker.\n\nThe attempt to synchronize on evt proceeds concurrently as the attempt to synchronize on the result guard from replace-evt; despite that concurrency, if maker is called, it is called in the thread that is synchronizing on guard. Synchronization can succeed for both evt and another synchronized with guard at the same time; the single-choice guarantee of synchronization applies only to the result of maker and other events synchronized with guard.\n\nIf maker returns a non-event, then maker’s result is replaced with an event that is ready for synchronization and whose synchronization result is guard.\n\nAdded in version 6.1.0.3 of package base.\n\n>
\n\n

value

\n\n

always-evt : evt?

\n\nA constant event that is always ready for synchronization, with itself as its synchronization result.\n\nExample:\n\n> ```racket\n> > ( sync always-evt )\n> #\n> ```\n\n>
\n\n

value

\n\n

never-evt : evt?

\n\nA constant event that is never ready for synchronization.\n\nExample:\n\n> ```racket\n> > ( sync/timeout 0.1 never-evt )\n> #f\n> ```\n\n> ```\n(system-idle-evt) → evt?```\n\n\nReturns an event that is [ready for synchronization](#%28tech._ready._for._synchronization%29) when the system is otherwise idle: if the result event were replaced by [never-evt](#%28def._%28%28quote._~23~25kernel%29._never-evt%29%29), no thread in the system would be available to run. In other words, all threads must be suspended or blocked on events with timeouts that have not yet expired. The system-idle event’s [synchronization result](#%28tech._synchronization._result%29) is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13). The result of the [system-idle-evt](#%28def._%28%28quote._~23~25kernel%29._system-idle-evt%29%29) procedure is always the same event.\n\nExamples:\n\n> ```racket\n> > ( define th ( thread ( λ ( ) ( let loop ( ) ( loop ) ) ) ) )\n> > ( sync/timeout 0.1 ( system-idle-evt ) )\n> #f\n> > ( kill-thread th )\n> > ( sync ( system-idle-evt ) )\n> ```\n\n> ```\n(alarm-evt msecs [monotonic?) → evt?\n  msecs : real?\n  monotonic? : any/c = #f\n```"} {"text": "# 10.4 Continuations\n(milliseconds)\t→```\nReturns #t if evt was created by [handle-evt](#%28def._%28%28quote._~23~25kernel%29._handle-evt%29%29) or by [choice-evt](#%28def._%28%28quote._~23~25kernel%29._choice-evt%29%29) applied to another event for which [handle-evt?](#%28def._%28%28quote._~23~25kernel%29._handle-evt~3f%29%29) produces #t. For any other event, [handle-evt?](#%28def._%28%28quote._~23~25kernel%29._handle-evt~3f%29%29) produces #f.\nExamples:\n> ```racket\n> > ( handle-evt? never-evt )\n> #f\n> > ( handle-evt? ( handle-evt always-evt values ) )\n> #t\n> ```\n>
\n

value

\n

[prop:evt](#%28def._%28%28quote._~23~25kernel%29._prop~3aevt%29%29) : [struct-type-property?](structprops.html#%28def._%28%28quote._~23~25kernel%29._struct-type-property~3f%29%29)

\nA [structure type property](structprops.html#%28tech._structure._type._property%29) that identifies structure types whose instances can serve as [synchronizable events](#%28tech._synchronizable._event%29). The property value can be any of the following:\n- An event evt: In this case, using the structure as an event is equivalent to using evt."} {"text": "# 10.4 Continuations\n- A procedure proc of one argument: In this case, the structure is similar to an event generated by [guard-evt](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._guard-evt%29%29), except that the would-be guard procedure proc receives the structure as an argument, instead of no arguments; also, a non-event result from proc is replaced with an event that is already [ready for synchronization](#%28tech._ready._for._synchronization%29) and whose [synchronization result](#%28tech._synchronization._result%29) is the structure.\n- An exact, non-negative integer between 0 (inclusive) and the number of non-automatic fields in the structure type (exclusive, not counting supertype fields): The integer identifies a field in the structure, and the field must be designated as immutable. If the field contains an object or an event-generating procedure of one argument, the event or procedure is used as above. Otherwise, the structure acts as an event that is never ready.\n> > > For working with foreign libraries, a [prop:evt](#%28def._%28%28quote._~23~25kernel%29._prop~3aevt%29%29) value can also be a result of [unsafe-poller](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=foreign&rel=Thread_Scheduling.html%23%2528def._%2528%2528lib._ffi%252Funsafe%252Fschedule..rkt%2529._unsafe-poller%2529%2529&version=8.18.0.13), although that possibility is omitted from the safe contract of [prop:evt](#%28def._%28%28quote._~23~25kernel%29._prop~3aevt%29%29)."} {"text": "# 10.4 Continuations\nInstances of a structure type with the [prop:input-port](portstructs.html#%28def._%28%28quote._~23~25kernel%29._prop~3ainput-port%29%29) or [prop:output-port](portstructs.html#%28def._%28%28quote._~23~25kernel%29._prop~3aoutput-port%29%29) property are also [synchronizable events](#%28tech._synchronizable._event%29) by virtue of being a port. If the structure type has more than one of [prop:evt](#%28def._%28%28quote._~23~25kernel%29._prop~3aevt%29%29), [prop:input-port](portstructs.html#%28def._%28%28quote._~23~25kernel%29._prop~3ainput-port%29%29), and [prop:output-port](portstructs.html#%28def._%28%28quote._~23~25kernel%29._prop~3aoutput-port%29%29), then the [prop:evt](#%28def._%28%28quote._~23~25kernel%29._prop~3aevt%29%29) value (if any) takes precedence for determining the instance’s behavior as an event, and the [prop:input-port](portstructs.html#%28def._%28%28quote._~23~25kernel%29._prop~3ainput-port%29%29) property takes precedence over [prop:output-port](portstructs.html#%28def._%28%28quote._~23~25kernel%29._prop~3aoutput-port%29%29) for synchronization.\nExamples:"} {"text": "# 10.4 Continuations\n> ```racket\n> > ( struct wt ( base val ) #:property prop:evt ( struct-field-index base ) )\n> > ( define sema ( make-semaphore ) )\n> > ( sync/timeout 0 ( wt sema #f ) )\n> #f\n> > ( semaphore-post sema )\n> > ( sync/timeout 0 ( wt sema #f ) )\n> #\n> > ( semaphore-post sema )\n> > ( sync/timeout 0 ( wt ( lambda ( self ) ( wt-val self ) ) sema ) )\n> #\n> > ( semaphore-post sema )\n> > ( define my-wt ( wt ( lambda ( self ) ( wrap-evt ( wt-val self ) ( lambda ( x ) self ) ) ) sema ) )\n> > ( sync/timeout 0 my-wt )\n> #\n> > ( sync/timeout 0 my-wt )\n> #f\n> ```\n> ```\n(current-evt-pseudo-random-generator)\t→\t\n(-> current-evt-pseudo-random-generator generator)\n(current-evt-pseudo-random-generator generator) → void?\n generator\t:\t\n(-> current-evt-pseudo-random-generator generator)\n```\n(atomic)\t→```\n\n\nReturns #t if v is a [channel](#%28tech._channel%29), #f otherwise.\n\n> ```\n(make-channel)  →  channel?\n```\nCreates and returns a new channel. The channel can be used with channel-get, with channel-try-get, or as a synchronizable event (see Events) to receive a value through the channel. The channel can be used with channel-put or through the result of channel-put-evt to send a value through the channel.\n> ```\n(channel-get ch)  →  any\n  ch : channel?```\nBlocks until a sender is ready to provide a value through ch. The result is the sent value.\n> ```\n(channel-try-get ch)  →  any\n  ch : channel?"} {"text": "# 10.4 Continuations\n```\n(parameter)\t→```\n\n\nBlocks until a receiver is ready to accept the value v through ch.\n\n> ```\n(channel-put-evt ch v)  →  channel-put-evt?\n  ch : channel?\n  v : any/c\n```\nReturns a fresh synchronizable event for use with sync. The event is ready for synchronization when (channel-put ch v) would not block, and the event’s synchronization result is the event itself.\n> ```\n(channel-put-evt? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a channel-put event produced by [channel-put-evt](#%28def._%28%28quote._~23~25kernel%29._channel-put-evt%29%29), #f otherwise.\n------------------------------------------------------------------------"} {"text": "# 11.2.3 Semaphores"} {"text": "#### 11.2.3 Semaphores\nA semaphore has an internal counter; when this counter is zero, the semaphore can block a thread’s execution (through [semaphore-wait](#%28def._%28%28quote._~23~25kernel%29._semaphore-wait%29%29)) until another thread increments the counter (using [semaphore-post](#%28def._%28%28quote._~23~25kernel%29._semaphore-post%29%29)). The maximum value for a semaphore’s internal counter is platform-specific, but always at least 10000.\nA semaphore’s counter is updated in a single-threaded manner, so that semaphores can be used for reliable synchronization. Semaphore waiting is fair: if a thread is blocked on a semaphore and the semaphore’s internal value is non-zero infinitely often, then the thread is eventually unblocked.\nIn addition to its use with semaphore-specific procedures, a semaphore can be used as a [synchronizable event](sync.html#%28tech._synchronizable._event%29) (see [Events](sync.html)). A semaphore is [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29) when [semaphore-wait](#%28def._%28%28quote._~23~25kernel%29._semaphore-wait%29%29) would not block. Upon synchronization, the semaphore’s counter is decremented, and the [synchronization result](sync.html#%28tech._synchronization._result%29) of a semaphore is the semaphore itself.\n> ```\n(semaphore? v)  →  boolean?\n  v : any/c"} {"text": "# 11.2.3 Semaphores\n```\nReturns #t if v is a semaphore, #f otherwise.\n\n> ```\n(make-semaphore [init) → semaphore?\n  init : exact-nonnegative-integer? = 0```\n\n\nCreates and returns a new semaphore with the counter initially set to init. If init is larger than a semaphore’s maximum internal counter value, the [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) exception is raised.\n\n> ```\n(parameter)\t→\n```\n(parameter)\t→```\nBlocks until the internal counter for semaphore sema is non-zero. When the counter is non-zero, it is decremented and [semaphore-wait](#%28def._%28%28quote._~23~25kernel%29._semaphore-wait%29%29) returns [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13).\n> ```\n(semaphore-try-wait? sema)  →  boolean?\n  sema : semaphore?\n```\n(parameter)\t→```\n\n\nLike [semaphore-wait](#%28def._%28%28quote._~23~25kernel%29._semaphore-wait%29%29), but breaking is enabled (see [Breaks](breakhandler.html)) while waiting on sema. If breaking is disabled when [semaphore-wait/enable-break](#%28def._%28%28quote._~23~25kernel%29._semaphore-wait%2Fenable-break%29%29) is called, then either the semaphore’s counter is decremented or the [exn:break](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak%29%29) exception is raised, but not both.\n\n> ```\n(semaphore-peek-evt sema)  →  semaphore-peek-evt?\n  sema : semaphore?\n```"} {"text": "# 11.2.3 Semaphores\nCreates and returns a new synchronizable event (for use with sync, for example) that is ready for synchronization when sema is ready, but synchronizing the event does not decrement sema’s internal count. The synchronization result of a semaphore-peek event is the semaphore-peek event itself.\n> ```\n(semaphore-peek-evt? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a semaphore wrapper produced by [semaphore-peek-evt](#%28def._%28%28quote._~23~25kernel%29._semaphore-peek-evt%29%29), #f otherwise.\n> ```\n(call-with-semaphore sema\n    proc        \n   [ try-fail-thunk]        \n    arg ...)   →   any\n  sema : semaphore?\n  proc : procedure?\n  try-fail-thunk : (or/c ( →  any) #f) = #f\n  arg : any/c"} {"text": "# 11.2.3 Semaphores\n```\nWaits on sema using semaphore-wait, calls proc with all args, and then posts to sema. A continuation barrier blocks full continuation jumps into or out of proc (see Prompts, Delimited Continuations, and Barriers), but escape jumps are allowed, and sema is posted on escape. If try-fail-thunk is provided and is not #f, then semaphore-try-wait? is called on sema instead of semaphore-wait, and try-fail-thunk is called if the wait fails.\n\n> ```\n(call-with-semaphore/enable-break sema\n    proc        \n   [ try-fail-thunk]        \n    arg ...)   →   any\n\n  sema : semaphore?\n  proc : procedure?\n  try-fail-thunk : (or/c ( →  any) #f) = #f\n  arg : any/c```\n\n\nLike [call-with-semaphore](#%28def._%28%28quote._~23~25kernel%29._call-with-semaphore%29%29), except that [semaphore-wait/enable-break](#%28def._%28%28quote._~23~25kernel%29._semaphore-wait%2Fenable-break%29%29) is used with sema in non-try mode. When try-fail-thunk is provided and not #f, then breaks are enabled around the use of [semaphore-try-wait?](#%28def._%28%28quote._~23~25kernel%29._semaphore-try-wait~3f%29%29) on sema.\n\n------------------------------------------------------------------------\n\n# 11.2.4 Buffered Asynchronous Channels\n\n#### 11.2.4 Buffered Asynchronous Channels\n\n| | |\n|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/async-channel]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/async-channel]() library, not [racket/base](index.html) or [racket](index.html).\n\n##### 11.2.4.1 Creating and Using Asynchronous Channels\n\n> > > \"+\"See also [Thread Mailboxes](threads.html#%28part._threadmbox%29).\n\nAn asynchronous channel is like a [channel](channel.html#%28tech._channel%29), but it buffers values so that a send operation does not wait on a receive operation.\n\nIn addition to its use with procedures that are specific to asynchronous channels, an asynchronous channel can be used as a [synchronizable event](sync.html#%28tech._synchronizable._event%29) (see [Events](sync.html)). An asynchronous channel is [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29) when [async-channel-get](#%28def._%28%28lib._racket%2Fasync-channel..rkt%29._async-channel-get%29%29) would not block; the asynchronous channel’s [synchronization result](sync.html#%28tech._synchronization._result%29) is the same as the [async-channel-get](#%28def._%28%28lib._racket%2Fasync-channel..rkt%29._async-channel-get%29%29) result.\n\n> ```\n(async-channel? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 11.2.3 Semaphores\nReturns #t if v is an asynchronous channel, #f otherwise.\n> ```\n(make-async-channel [limit) → async-channel?\n  limit : (or/c exact-positive-integer? #f) = #f```\nReturns an asynchronous channel with a buffer limit of limit items. A get operation blocks when the channel is empty, and a put operation blocks when the channel has limit items already. If limit is #f, the channel buffer has no limit (so a put never blocks).\n> ```\n(async-channel-get ach)  →  any/c\n  ach : async-channel?\n```\n\n\nBlocks until at least one value is available in ach, and then returns the first of the values that were put into async-channel.\n\n> ```\n(async-channel-try-get ach)  →  any/c\n  ach : async-channel?\n```\nIf at least one value is immediately available in ach, returns the first of the values that were put into ach. If async-channel is empty, the result is #f.\n> ```\n(parameter)\t→\n```\n\n\nPuts v into ach, blocking if ach’s buffer is full until space is available.\n\n> ```\n(async-channel-put-evt ach v)  →  evt?\n  ach : async-channel?\n  v : any/c\n```\nReturns a [synchronizable event](sync.html#%28tech._synchronizable._event%29) that is [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29) when ([async-channel-put](#%28def._%28%28lib._racket%2Fasync-channel..rkt%29._async-channel-put%29%29) ach v) would return a value (i.e., when the channel holds fewer values already than its limit); the [synchronization result](sync.html#%28tech._synchronization._result%29) of a asynchronous channel-put event is the asynchronous channel-put event itself.\nExamples:"} {"text": "# 11.2.3 Semaphores\n> ```racket\n> ( define ( server input-channel output-channel ) ( thread ( lambda ( ) ( define ( get ) ( async-channel-get input-channel ) ) ( define ( put x ) ( async-channel-put output-channel x ) ) ( define ( do-large-computation ) ( sqrt 9 ) ) ( let loop ( [ data ( get ) ] ) ( case data [ ( quit ) ( void ) ] [ ( add ) ( begin ( put ( + 1 ( get ) ) ) ( loop ( get ) ) ) ] [ ( long ) ( begin ( put ( do-large-computation ) ) ( loop ( get ) ) ) ] ) ) ) ) ) ( define to-server ( make-async-channel ) ) ( define from-server ( make-async-channel ) )\n> > ( server to-server from-server )\n> #\n> > ( async-channel? to-server )\n> #t\n> > ( printf \"Adding 1 to 4\\n\" )\n> Adding 1 to 4\n> > ( async-channel-put to-server ' add )\n> > ( async-channel-put to-server 4 )\n> > ( printf \"Result is ~a\\n\" ( async-channel-get from-server ) )\n> Result is 5\n> > ( printf \"Ask server to do a long computation\\n\" )\n> Ask server to do a long computation\n> > ( async-channel-put to-server ' long )\n> > ( printf \"I can do other stuff\\n\" )\n> I can do other stuff\n> > ( printf \"Ok, computation from server is ~a\\n\" ( async-channel-get from-server ) )\n> Ok, computation from server is 3\n> > ( async-channel-put to-server ' quit )\n> ```"} {"text": "##### 11.2.4.2 Contracts and Impersonators on Asynchronous Channels\n> ```\n(async-channel/c c)  →  contract?\n  c : contract?\n```\nReturns a contract that recognizes asynchronous channels. Values put into or retrieved from the channel must match c.\n\nIf the c argument is a flat contract or a chaperone contract, then the result will be a chaperone contract. Otherwise, the result will be an impersonator contract.\n\nWhen an async-channel/c contract is applied to an asynchronous channel, the result is not eq? to the input. The result will be either a chaperone or impersonator of the input depending on the type of contract.\n\n> ```\n(impersonate-async-channel channel\n    get-proc  \n    put-proc  \n    prop  \n    prop-val ...  \n    ...)  \n\n  →  (and/c async-channel? impersonator?)\n  channel : async-channel?\n  get-proc : (any/c . → . any/c)\n  put-proc : (any/c . → . any/c)\n  prop : impersonator-property?\n  prop-val : any```\n\n\nReturns an impersonator of channel, which redirects the [async-channel-get](#%28def._%28%28lib._racket%2Fasync-channel..rkt%29._async-channel-get%29%29) and [async-channel-put](#%28def._%28%28lib._racket%2Fasync-channel..rkt%29._async-channel-put%29%29) operations.\n\nThe get-proc must accept the value that [async-channel-get](#%28def._%28%28lib._racket%2Fasync-channel..rkt%29._async-channel-get%29%29) produces on channel; it must produce a replacement value, which is the result of the get operation on the impersonator.\n\nThe put-proc must accept the value passed to [async-channel-put](#%28def._%28%28lib._racket%2Fasync-channel..rkt%29._async-channel-put%29%29) called on channel; it must produce a replacement value, which is the value passed to the put procedure called on the original channel.\n\nThe get-proc and put-proc procedures are called for all operations that get or put values from the channel, not just [async-channel-get](#%28def._%28%28lib._racket%2Fasync-channel..rkt%29._async-channel-get%29%29) and [async-channel-put](#%28def._%28%28lib._racket%2Fasync-channel..rkt%29._async-channel-put%29%29).\n\nPairs of prop and prop-val (the number of arguments to [impersonate-async-channel](#%28def._%28%28lib._racket%2Fasync-channel..rkt%29._impersonate-async-channel%29%29) must be odd) add [impersonator properties](chaperones.html#%28tech._impersonator._property%29) or override [impersonator property](chaperones.html#%28tech._impersonator._property%29) values of channel.\n\n> ```\n(chaperone-async-channel channel\n    get-proc  \n    put-proc  \n    prop  \n    prop-val ...  \n    ...)  \n\n  →  (and/c async-channel? chaperone?)\n  channel : async-channel?\n  get-proc : (any/c . → . any/c)\n  put-proc : (any/c . → . any/c)\n  prop : impersonator-property?\n  prop-val : any\n```"} {"text": "# 11.2.3 Semaphores\n(parameter)\t→```\nReturns #t if v is a [thread cell](eval-model.html#%28tech._thread._cell%29), #f otherwise.\n> ```\n(make-thread-cell v [preserved?) → thread-cell?\n  v : any/c\n  preserved? : any/c = #f\n```\n\n\nCreates and returns a new thread cell. Initially, v is the cell’s value for all threads. If preserved? is true, then the cell’s initial value for a newly created threads is the creating thread’s value for the cell, otherwise the cell’s value is initially v in all future threads.\n\n> ```\n(thread-cell-ref cell)  →  any\n  cell : thread-cell?\n```\nReturns the current value of cell for the current thread.\n> ```\n(thread-cell-set! cell v)  →  any\n  cell : thread-cell?\n  v : any/c\n```\n(nerve)\t→\t\n(-> current-preserved-thread-cell-values thread-cell-vals)```\n\n\nWhen called with no arguments, this procedure produces a thread-cell-vals that represents the current values (in the current thread) for all preserved thread cells.\n\nWhen called with a thread-cell-vals generated by a previous call to [current-preserved-thread-cell-values](#%28def._%28%28quote._~23~25kernel%29._current-preserved-thread-cell-values%29%29), the values of all preserved thread cells (in the current thread) are set to the values captured in thread-cell-vals; if a preserved thread cell was created after thread-cell-vals was generated, then the thread cell’s value for the current thread reverts to its initial value.\n\n> ```\n(thread-cell-values? v)  →  boolean?\n  v : any/c\n```\n(parameter)\t→\t\n(-> or/c (any/c . → . any) #f)```"} {"text": "# 11.2.3 Semaphores\nReturns a new parameter procedure. The value of the parameter is initialized to v in all threads.\nIf guard is not #f, it is used as the parameter’s guard procedure. A guard procedure takes one argument. Whenever the parameter procedure is applied to an argument, the argument is passed on to the guard procedure. The result returned by the guard procedure is used as the new parameter value. A guard procedure can raise an exception to reject a change to the parameter’s value. The guard is not applied to the initial v.\nThe name argument is used as the parameter procedure’s name as reported by [object-name](inspectors.html#%28def._%28%28quote._~23~25kernel%29._object-name%29%29), and realm is used as the reported as reported by [procedure-realm](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._procedure-realm%29%29).\nChanged in version 7.4.0.6 of package base: Added the name argument. \nChanged in version 8.4.0.2: Added the realm argument.\n> ```\nsyntax\n(parameterize ([parameter-expr value-expr] ...)\n> body ...+ )\n   parameter-expr   :   parameter?"} {"text": "# 11.2.3 Semaphores\n```\n(interleaved)\t→```\n\n\nAnalogous to [let*](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%2A%29%29) compared to [let](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%29%29), [parameterize*](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize%2A%29%29) is the same as a nested series of single-parameter [parameterize](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize%29%29) forms.\n\n> ```\n(parameter)\t→\t\n(-> any/c . → . any)\n```\nReturns a parameter procedure that sets or retrieves the same value as parameter, but with:\n- guard applied when setting the parameter (before any guard associated with parameter), and\n- wrap applied when obtaining the parameter’s value.\nThe name argument is used as the parameter procedure’s name as reported by object-name, and realm is used as the reported as reported by procedure-realm. Supply values for guard and wrap if the goal is merely to replace the name or realm of parameter.\nSee also chaperone-procedure, which can also be used to guard parameter procedures.\nChanged in version 8.15.0.4 of package base: Added the name and realm arguments.\n> ```\n(parameter? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a parameter procedure, #f otherwise.\n> ```\n(parameter-procedure=? a b) → boolean?\n  a : parameter?\n  b : parameter?"} {"text": "# 11.2.3 Semaphores\n```\n(current-parameterization)\t→```\n\n\nReturns the current continuation’s [parameterization](eval-model.html#%28tech._parameterization%29).\n\n> ```\n(call-with-parameterization   parameterization        \n    thunk)   →   any\n\n  parameterization : parameterization?\n  thunk : ( →  any)\n```\nCalls thunk (via a tail call) with parameterization as the current parameterization.\n> ```\n(parameterization? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a [parameterization](eval-model.html#%28tech._parameterization%29) returned by [current-parameterization](#%28def._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._current-parameterization%29%29), #f otherwise.\n------------------------------------------------------------------------"} {"text": "# 11.4 Futures"} {"text": "### 11.4 Futures\n> > > \"+\"[Parallelism with Futures](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=parallelism.html%23%2528part._effective-futures%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces futures.\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/future]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/future]() and [racket](index.html) libraries, but not [racket/base](index.html)."} {"text": "# 11.4 Futures\n> > > Support for parallelism via [future](#%28def._%28%28lib._racket%2Ffuture..rkt%29._future%29%29) is normally enabled for all platforms in the [CS](implementations.html#%28tech._c%29) implementation of Racket. In the [BC](implementations.html#%28tech._bc%29) implementation, support for parallelism is enabled by default for Windows, Linux x86/x86_64, and Mac OS x86/x86_64. To enable support for other platforms building Racket [BC](implementations.html#%28tech._bc%29), use --enable-futures with configure.\nThe [future](#%28def._%28%28lib._racket%2Ffuture..rkt%29._future%29%29) and [touch](#%28def._%28%28lib._racket%2Ffuture..rkt%29._touch%29%29) functions from [racket/future]() provide access to parallelism as supported by the hardware and operating system. In contrast to [thread](threads.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._thread%29%29), which provides concurrency for arbitrary computations without parallelism, [future](#%28def._%28%28lib._racket%2Ffuture..rkt%29._future%29%29) provides parallelism. A future executes its work in parallel (assuming that support for parallelism is available) until it detects an attempt to perform an operation that cannot run safely in parallel. Similarly, work in a future is suspended if it depends in some way on the current continuation, such as raising an exception. Operations that suspend a future are blocking operations. A suspended computation for a future is resumed when [touch](#%28def._%28%28lib._racket%2Ffuture..rkt%29._touch%29%29) is applied to the future."} {"text": "# 11.4 Futures\n“Safe” parallel execution of a future means that all operations provided by the system must be able to enforce contracts and produce results as documented. “Safe” does not preclude concurrent access to mutable data that is visible in the program. For example, a computation in a future might use [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) to modify a shared variable, in which case concurrent assignment to the variable can be visible in other futures and threads. Furthermore, guarantees about the visibility of effects and ordering are determined by the operating system and hardware—which rarely support, for example, the guarantee of sequential consistency that is provided for [thread](threads.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._thread%29%29)-based concurrency; see also [Machine Memory Order](memory-order.html). A system operation that seems obviously safe may have an internal implementation that cannot run in parallel; see [Parallelism with Futures](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=parallelism.html%23%2528part._effective-futures%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) for more discussion and an introduction to using [future-visualizer](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?tag=%28mod-path._.%27future-visualizer.%27%29&version=8.18.0.13)) to understand the behavior of system operations."} {"text": "# 11.4 Futures\nA future never runs in parallel if all of the [custodians](eval-model.html#%28tech._custodian%29) that allow its creating thread to run are shut down. Such futures can execute through a call to [touch](#%28def._%28%28lib._racket%2Ffuture..rkt%29._touch%29%29), however."} {"text": "#### 11.4.1 Creating and Touching Futures\n> ```\n(future thunk)  →  future?\n  thunk : ( →  any)\n(touch f)  →  any\n  f : future?\n```\nThe future procedure returns a future value that encapsulates thunk. The touch function forces the evaluation of the thunk inside the given future, returning the values produced by thunk. After touch forces the evaluation of a thunk, the resulting values are retained by the future in place of thunk, and additional touches of the future return those values.\n\nBetween a call to future and touch for a given future, the given thunk may run speculatively in parallel to other computations, as described above.\n\nExample:\n\n> ```racket\n> > ( let ( [ f ( future ( lambda ( ) ( + 1 2 ) ) ) ] ) ( list ( + 3 4 ) ( touch f ) ) )\n> '(7 3)\n> ```\n\n> ```\n(futures-enabled?) → boolean?```\n\n\nReturns whether parallel support for futures is enabled in the current Racket configuration.\n\n> ```\n(current-future)\t→\t\n(-> or/c #f future?)\n```\nReturns the descriptor of the future whose thunk execution is the current continuation; that is, if a future descriptor f is returned, (touch f) will produce the result of the current continuation. If a future thunk itself uses touch, future-thunk executions can be nested, in which case the descriptor of the most immediately executing future is returned. If the current continuation does not return to the touch of any future, the result is #f.\n> ```\n(future? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a future value, #f otherwise.\n> ```\n(would-be-future thunk)  →  future?\n  thunk : ( →  any)"} {"text": "# 11.4 Futures\n```\nReturns a future that never runs in parallel, but that consistently logs all potentially “unsafe” operations during the execution of the future’s thunk (i.e., operations that interfere with parallel execution).\n\nWith a normal future, certain circumstances might prevent the logging of unsafe operations. For example, when executed with debug-level logging,\n\n> ```racket\n> ( touch ( future ( lambda ( )\n> ( printf \"hello1\" )\n> ( printf \"hello2\" )\n> ( printf \"hello3\" ) ) ) )\n> ```\n\nmight log three messages, one for each printf invocation. However, if the touch is performed before the future has a chance to start running in parallel, the future thunk evaluates in the same manner as any ordinary thunk, and no unsafe operations are logged. Replacing future with would-be-future ensures the logging of all three calls to printf.\n\n> ```\n(processor-count)  →  exact-positive-integer?```\n\n\nReturns the number of parallel computation units (e.g., processors or cores) that are available on the current machine.\n\nThis is the same binding as available from [racket/place](places.html).\n\n>
\n\n

syntax

\n\n

([for/async](#%28form._%28%28lib._racket%2Ffuture..rkt%29._for%2Fasync%29%29) (for-clause ...) body-or-break ... body)

\n\n

syntax

\n\n

([for*/async](#%28form._%28%28lib._racket%2Ffuture..rkt%29._for%2A%2Fasync%29%29) (for-clause ...) body-or-break ... body)

\n\nLike [for](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%29%29) and [for*](for.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for%2A%29%29), but each iteration of the body is executed in a separate [future](#%28def._%28%28lib._racket%2Ffuture..rkt%29._future%29%29), and the futures may be [touch](#%28def._%28%28lib._racket%2Ffuture..rkt%29._touch%29%29)ed in any order.\n\n#### 11.4.2 Future Semaphores\n\n> ```\n(make-fsemaphore init)  →  fsemaphore?\n  init : exact-nonnegative-integer?\n```"} {"text": "# 11.4 Futures\nCreates and returns a new future semaphore with the counter initially set to init.\nA future semaphore is similar to a plain semaphore, but future-semaphore operations can be performed safely in parallel (to synchronize parallel computations). In contrast, operations on plain semaphores are not safe to perform in parallel, and they therefore prevent a computation from continuing in parallel.\nBeware of trying to use an fsemaphore to implement a lock. A future may run concurrently and in parallel to other futures, but a future that is not demanded by a Racket thread can be suspended at any time—such as just after it takes a lock and before it releases the lock. If you must share mutable data among futures, lock-free data structures are generally a better fit.\n> ```\n(fsemaphore? v)  →  boolean?\n  v : any/c```\nReturns #t if v is an [future semaphore](#%28tech._future._semaphore%29) value, #f otherwise.\n> ```\n(parameter)\t→\n```\n(parameter)\t→```\n\n\nBlocks until the internal counter for fsema is non-zero. When the counter is non-zero, it is decremented and [fsemaphore-wait](#%28def._%28%28lib._racket%2Ffuture..rkt%29._fsemaphore-wait%29%29) returns [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13).\n\n> ```\n(fsemaphore-try-wait? fsema)  →  boolean?\n  fsema : fsemaphore?\n```"} {"text": "# 11.4 Futures\nLike fsemaphore-wait, but fsemaphore-try-wait? never blocks execution. If fsema’s internal counter is zero, fsemaphore-try-wait? returns #f immediately without decrementing the counter. If fsema’s counter is positive, it is decremented and #t is returned.\n> ```\n(fsemaphore-count fsema)  →  exact-nonnegative-integer?\n  fsema : fsemaphore?```\nReturns fsema’s current internal counter value."} {"text": "#### 11.4.3 Future Performance Logging\nRacket traces use logging (see [Logging](logging.html)) extensively to report information about how futures are evaluated. Logging output is useful for debugging the performance of programs that use futures.\nThough textual log output can be viewed directly (or retrieved in code via [trace-futures](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=future-visualizer&rel=futures-trace.html%23%2528form._%2528%2528lib._future-visualizer%252Ftrace..rkt%2529._trace-futures%2529%2529&version=8.18.0.13)), it is much easier to use the graphical profiler tool provided by [future-visualizer](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?tag=%28mod-path._.%27future-visualizer.%27%29&version=8.18.0.13).\nFuture events are logged with the topic 'future. In addition to its string message, each event logged for a future has a data value that is an instance of a [future-event](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=future-visualizer&rel=futures-trace.html%23%2528def._%2528%2528lib._future-visualizer%252Ftrace..rkt%2529._future-event%2529%2529&version=8.18.0.13) [prefab](structures.html#%28tech._prefab%29) structure:\n> ```racket\n> ( struct future-event ( future-id proc-id action time prim-name user-data )\n> #:prefab )\n> ```\nThe future-id field is an exact integer that identifies a future, or it is #f when action is 'missing. The future-id field is particularly useful for correlating logged events."} {"text": "# 11.4 Futures\nThe proc-id fields is an exact, non-negative integer that identifies a parallel process. Process 0 is the main Racket process, where all expressions other than future thunks evaluate.\nThe [time](time.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._time%29%29) field is an inexact number that represents time in the same way as [current-inexact-milliseconds](time.html#%28def._%28%28quote._~23~25kernel%29._current-inexact-milliseconds%29%29).\nThe action field is a symbol:\n- 'create: a future was created.\n- 'complete: a future’s thunk evaluated successfully, so that [touch](#%28def._%28%28lib._racket%2Ffuture..rkt%29._touch%29%29) will produce a value for the future immediately.\n- 'start-work and 'end-work: a particular process started and ended working on a particular future.\n- 'start-0-work: like 'start-work, but for a future thunk that for some structural reason could not be started in a process other than 0 (e.g., the thunk requires too much local storage to start).\n- 'start-overflow-work: like 'start-work, where the future thunk’s work was previously stopped due to an internal stack overflow.\n- 'sync: blocking (processes other than 0) or initiation of handing (process 0) for an “unsafe” operation in a future thunk’s evaluation; the operation must run in process 0.\n- 'block: like 'sync, but for a part of evaluation that must be delayed until the future is [touch](#%28def._%28%28lib._racket%2Ffuture..rkt%29._touch%29%29)ed, because the evaluation may depend on the current continuation."} {"text": "# 11.4 Futures\n- 'touch (never in process 0): like 'sync or 'block, but for a [touch](#%28def._%28%28lib._racket%2Ffuture..rkt%29._touch%29%29) operation within a future thunk.\n- 'overflow (never in process 0): like 'sync or 'block, but for the case that a process encountered an internal stack overflow while evaluating a future thunk.\n- 'result or 'abort: waiting or handling for 'sync, 'block, or 'touch ended with a value or an error, respectively.\n- 'suspend (never in process 0): a process blocked by 'sync, 'block, or 'touch abandoned evaluation of a future; some other process may pick up the future later.\n- 'touch-pause and 'touch-resume (in process 0, only): waiting in [touch](#%28def._%28%28lib._racket%2Ffuture..rkt%29._touch%29%29) for a future whose thunk is being evaluated in another process.\n- 'missing: one or more events for the process were lost due to internal buffer limits before they could be reported, and the time-id field reports an upper limit on the time of the missing events; this kind of event is rare.\nAssuming no 'missing events, then 'start-work, 'start-0-work, 'start-overflow-work is always paired with 'end-work; 'sync, 'block, and 'touch are always paired with 'result, 'abort, or 'suspend; and 'touch-pause is always paired with 'touch-resume.\nIn process 0, some event pairs can be nested within other event pairs: 'sync, 'block, or 'touch with 'result or 'abort; 'touch-pause with 'touch-resume; and 'start-work with 'end-work."} {"text": "# 11.4 Futures\nA 'block in process 0 is generated when an unsafe operation is handled. This type of event will contain a symbol in the unsafe-op-name field that is the name of the operation. In all other cases, this field contains #f.\nThe prim-name field will always be #f unless the event occurred on process 0 and its action is either 'block or 'sync. If these conditions are met, prim-name will contain the name of the Racket primitive which required the future to synchronize with the runtime thread (represented as a symbol).\nThe user-data field may take on a number of different values depending on both the action and prim-name fields:\n- 'touch on process 0: contains the integer ID of the future being touched.\n- 'sync and prim-name is '\\|allocate memory\\|: The size (in bytes) of the requested allocation.\n- 'sync and prim-name is 'jit_on_demand: The runtime thread is performing a JIT compilation on behalf of the future future-id. The field contains the name of the function being JIT compiled (as a symbol).\n- 'create: A new future was created. The field contains the integer ID of the newly created future.\n------------------------------------------------------------------------"} {"text": "# 11.5 Places"} {"text": "### 11.5 Places\n> > > \"+\"[Parallelism with Places](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=parallelism.html%23%2528part._effective-places%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces places.\n| | |\n|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/place]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/place/dynamic]()) | |"} {"text": "# 11.5 Places\nThe bindings documented in this section are provided by the [racket/place](), [racket/place/dynamic](), and [racket](index.html) libraries, but not [racket/base](index.html).\n[Places](#%28tech._place%29) enable the development of parallel programs that take advantage of machines with multiple processors, cores, or hardware threads.\n> > > Currently, parallel support for places is enabled on all platforms that support Racket [CS](implementations.html#%28tech._c%29), the default implementation of Racket. The [3m](implementations.html#%28tech._3m%29) implementation also supports parallel execution of places by default on Windows, Linux x86/x86_64, and Mac OS x86/x86_64. To enable support for other platforms with [3m](implementations.html#%28tech._3m%29), use --enable-places with configure when building Racket. The [place-enabled?](#%28def._%28%28lib._racket%2Fplace..rkt%29._place-enabled~3f%29%29) function reports whether places run in parallel.\n> > >\n> > > Implementation and operating-system constraints may limit the scalability of places. For example, although places can perform garbage collections in parallel in the [CS](implementations.html#%28tech._c%29) implementation or independently in the [3m](implementations.html#%28tech._3m%29) implementation, a garbage collection may need to manipulate a page table that is shared across all places, and that shared page table can be a bottleneck with enough places—perhaps around 8 or 16."} {"text": "# 11.5 Places\nA place is a parallel task that is effectively a separate instance of the Racket virtual machine, although all places run within a single operating-system process. Places communicate through place channels, which are endpoints for a two-way buffered communication.\nTo a first approximation, place channels support only immutable, transparent values as messages. In addition, place channels themselves can be sent across channels to establish new (possibly more direct) lines of communication in addition to any existing lines. Finally, mutable values produced by [shared-flvector](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._shared-flvector%29%29), [make-shared-flvector](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._make-shared-flvector%29%29), [shared-fxvector](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._shared-fxvector%29%29), [make-shared-fxvector](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._make-shared-fxvector%29%29), [shared-bytes](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._shared-bytes%29%29), and [make-shared-bytes](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._make-shared-bytes%29%29) can be sent across place channels; mutation of such values is visible to all places that share the value, because they are allowed in a shared memory space. See [place-message-allowed?](#%28def._%28%28lib._racket%2Fplace..rkt%29._place-message-allowed~3f%29%29)."} {"text": "# 11.5 Places\nA [place channel](#%28tech._place._channel%29) can be used as a [synchronizable event](sync.html#%28tech._synchronizable._event%29) (see [Events](sync.html)) to receive a value through the channel. A [place channel](#%28tech._place._channel%29) is [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29) when a message is available on the channel, and the [place channel](#%28tech._place._channel%29)’s [synchronization result](sync.html#%28tech._synchronization._result%29) is the message (which is removed on synchronization). A place can also receive messages with [place-channel-get](#%28def._%28%28lib._racket%2Fplace..rkt%29._place-channel-get%29%29), and messages can be sent with [place-channel-put](#%28def._%28%28lib._racket%2Fplace..rkt%29._place-channel-put%29%29).\nTwo [place channels](#%28tech._place._channel%29) are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) if they are endpoints for the same underlying channels while both or neither is a [place descriptor](#%28tech._place._descriptor%29). [Place channels](#%28tech._place._channel%29) can be [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) without being [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) after being sent messages through a [place channel](#%28tech._place._channel%29)."} {"text": "# 11.5 Places\nConstraints on messages across a place channel—and therefore on the kinds of data that places share—enable greater parallelism than [future](futures.html#%28def._%28%28lib._racket%2Ffuture..rkt%29._future%29%29), even including separate [garbage collection](eval-model.html#%28tech._garbage._collection%29) of separate places. At the same time, the setup and communication costs for places can be higher than for [futures](futures.html#%28tech._future%29).\nFor example, the following expression launches two places, echoes a message to each, and then waits for the places to terminate:\n> ```racket\n> ( let ( [ pls ( for/list ( [ i ( in-range 2 ) ] )\n> ( dynamic-place \"place-worker.rkt\" ' place-main ) ) ] )\n> ( for ( [ i ( in-range 2 ) ]\n> [ p pls ] )\n> ( place-channel-put p i )\n> ( printf \"~a\\n\" ( place-channel-get p ) ) )\n> ( for-each place-wait pls ) )\n> ```\nThe \"place-worker.rkt\" module (in a file that is separate from the above code) must export the place-main function that each place executes, where place-main must accept a single [place channel](#%28tech._place._channel%29) argument:\n> > \"place-worker.rkt\"\n> >\n> > > ```racket\n> > > #lang racket\n> > > ( provide place-main )\n> > > ( define ( place-main pch )\n> > > ( place-channel-put pch ( format \"Hello from place ~a\"\n> > > ( place-channel-get pch ) ) ) )\n> > > ```"} {"text": "# 11.5 Places\nPlace channels are subject to [garbage collection](eval-model.html#%28tech._garbage._collection%29), like other Racket values, and a [thread](eval-model.html#%28tech._thread%29) that is blocked reading from a [place channel](#%28tech._place._channel%29) can be garbage collected if [place channel](#%28tech._place._channel%29)’s writing end becomes unreachable. However, unlike normal [channel](channel.html#%28tech._channel%29) blocking, if otherwise unreachable threads are mutually blocked on place channels that are reachable only from the same threads, the threads and place channels are all considered reachable, instead of unreachable.\nWhen a place is created, its [parameter](eval-model.html#%28tech._parameter%29) values are generally set to the initial values of the parameters in the creating place, except that the current values of the following parameters are used: [current-library-collection-paths](collects.html#%28def._%28%28quote._~23~25kernel%29._current-library-collection-paths%29%29), [current-library-collection-links](collects.html#%28def._%28%28quote._~23~25kernel%29._current-library-collection-links%29%29), and [current-compiled-file-roots](eval.html#%28def._%28%28quote._~23~25kernel%29._current-compiled-file-roots%29%29).\nA newly created place is registered with the [current custodian](eval-model.html#%28tech._current._custodian%29), so that the place is terminated when the custodian is shut down."} {"text": "#### 11.5.1 Using Places\n> ```\n(place-enabled?)  →  boolean?\n```\nReturns #t if Racket is configured so that dynamic-place and place create places that can run in parallel, #f if dynamic-place and place are simulated using thread.\n\n> ```\n(place? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a place descriptor value, #f otherwise. Every [place descriptor](#%28tech._place._descriptor%29) is also a [place channel](#%28tech._place._channel%29).\n\n> ```\n(place-channel? v)  →  boolean?\n  v : any/c\n```\n(parameter)\t→\t\n(-> or/c module-path? path?)```\nCreates a [place](#%28tech._place%29) to run the procedure that is identified by module-path and start-name. The result is a [place descriptor](#%28tech._place._descriptor%29) value that represents the new parallel task; the place descriptor is returned immediately. The place descriptor value is also a [place channel](#%28tech._place._channel%29) that permits communication with the place.\nThe module indicated by module-path must export a function with the name start-name. The function must accept a single argument, which is a [place channel](#%28tech._place._channel%29) that corresponds to the other end of communication for the [place descriptor](#%28tech._place._descriptor%29) returned by [place](#%28form._%28%28lib._racket%2Fplace..rkt%29._place%29%29)."} {"text": "# 11.5 Places\nIf location is provided, it must be a [place location](#%28tech._place._location%29), such as a distributed places node produced by [create-place-node](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=distributed-places&rel=index.html%23%2528def._%2528%2528lib._racket%252Fplace%252Fdistributed..rkt%2529._create-place-node%2529%2529&version=8.18.0.13).\nWhen the [place](#%28tech._place%29) is created, the initial [exit handler](Exiting.html#%28tech._exit._handler%29) terminates the place, using the argument to the exit handler as the place’s completion value. Use ([exit](Exiting.html#%28def._%28%28quote._~23~25kernel%29._exit%29%29) v) to immediately terminate a place with the completion value v. Since a completion value is limited to an exact integer between 0 and 255, any other value for v is converted to 0.\nIf the function indicated by module-path and start-name returns, then the place terminates with the [completion value](#%28tech._completion._value%29) 0."} {"text": "# 11.5 Places\nIn the created place, the [current-input-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._current-input-port%29%29) parameter is set to an empty input port, while the values of the [current-output-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._current-output-port%29%29) and [current-error-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._current-error-port%29%29) parameters are connected to the current ports in the creating place. If the output ports in the creating place are [file-stream ports](file-ports.html#%28tech._file._stream._port%29), then the connected ports in the created place share the underlying streams, otherwise a [thread](eval-model.html#%28tech._thread%29) in the creating place pumps bytes from the created place’s ports to the current ports in the creating place.\nMost [parameters](eval-model.html#%28tech._parameter%29) in the created place have their original initial values, but the created place inherits the creating place’s values for the following parameters: [current-directory](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29), [current-library-collection-paths](collects.html#%28def._%28%28quote._~23~25kernel%29._current-library-collection-paths%29%29), [current-library-collection-links](collects.html#%28def._%28%28quote._~23~25kernel%29._current-library-collection-links%29%29), and [current-compiled-file-roots](eval.html#%28def._%28%28quote._~23~25kernel%29._current-compiled-file-roots%29%29)."} {"text": "# 11.5 Places\nThe module-path argument must not be a module path of the form ([quote](quote.html#%28form._%28%28quote._~23~25kernel%29._quote%29%29) sym) unless the module is predefined (see [module-predefined?](Module_Names_and_Loading.html#%28def._%28%28quote._~23~25kernel%29._module-predefined~3f%29%29)).\nThe [dynamic-place](#%28def._%28%28lib._racket%2Fplace..rkt%29._dynamic-place%29%29) binding is protected in the sense of [protect-out](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._protect-out%29%29), so access to this operation can be prevented by adjusting the code inspector (see [Code Inspectors](modprotect.html)).\nChanged in version 8.2.0.7 of package base: Changed created place to inherit the creating place’s [current-directory](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29) value.\n> ```\n(current-output-port)\t→\t\n(-> or/c output-port? #f)\n```\n(parameter)\t→```\n\n\nReturns the [completion value](#%28tech._completion._value%29) of the place indicated by p, blocking until the place has terminated.\n\nIf any pumping threads were created to connect a non-[file-stream port](file-ports.html#%28tech._file._stream._port%29) to the ports in the place for p (see [dynamic-place](#%28def._%28%28lib._racket%2Fplace..rkt%29._dynamic-place%29%29)), [place-wait](#%28def._%28%28lib._racket%2Fplace..rkt%29._place-wait%29%29) returns only when the pumping threads have completed.\n\n> ```\n(place-dead-evt p)  →  evt?\n  p : place?\n```\n(parameter)\t→```"} {"text": "# 11.5 Places\nImmediately terminates the place, setting the place’s [completion value](#%28tech._completion._value%29) to 1 if the place does not have a completion value already.\n> ```\n(parameter)\t→\t\n(-> or/c #f 'hang-up 'terminate)\n```\nSends the main thread of place p a break; see Breaks.\n\n> ```\n(place-channel)   →   place-channel?   place-channel?```\n\n\nReturns two [place channels](#%28tech._place._channel%29). Data sent through the first channel can be received through the second channel, and data sent through the second channel can be received from the first.\n\nTypically, one place channel is used by the current [place](#%28tech._place%29) to send messages to a destination [place](#%28tech._place%29); the other place channel is sent to the destination [place](#%28tech._place%29) (via an existing [place channel](#%28tech._place._channel%29)).\n\n> ```\n(place-channel-put pch v)  →  void\n  pch : place-channel?\n  v : place-message-allowed?\n```\nSends a message v on channel pch. Since place channels are asynchronous, place-channel-put calls are non-blocking.\nSee place-message-allowed? form information on automatic coercions in v, such as converting a mutable string to an immutable string.\n> ```\n(place-channel-get pch)  →  place-message-allowed?\n  pch : place-channel?```\nReturns a message received on channel pch, blocking until a message is available.\n> ```\n(place-channel-put/get pch v)  →  any/c\n  pch : place-channel?\n  v : any/c"} {"text": "# 11.5 Places\n```\n\n\nSends an immutable message v on channel pch and then waits for a message (perhaps a reply) on the same channel.\n\n> ```\n(place-message-allowed? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is allowed as a message on a place channel, #f otherwise.\nIf ([place-enabled?](#%28def._%28%28lib._racket%2Fplace..rkt%29._place-enabled~3f%29%29)) returns #f, then the result is always #t and no conversions are performed on v as a message. Otherwise, the following kinds of data are allowed as messages:\n- [numbers](numbers.html#%28tech._number%29), [characters](characters.html#%28tech._character%29), [booleans](booleans.html#%28tech._boolean%29), [keywords](keywords.html#%28tech._keyword%29), and [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13);\n- [symbols](symbols.html#%28tech._symbol%29), where the [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)ness of [uninterned](symbols.html#%28tech._uninterned%29) symbols is preserved within a single message, but not across messages;\n- [strings](strings.html#%28tech._string%29) and [byte strings](bytestrings.html#%28tech._byte._string%29), where mutable strings and byte strings are automatically replaced by immutable variants;\n- [paths](pathutils.html#%28tech._path%29) (for any platform);"} {"text": "# 11.5 Places\n- [pairs](pairs.html#%28tech._pair%29), [lists](pairs.html#%28tech._list%29), [box](boxes.html#%28tech._box%29)es, [vectors](vectors.html#%28tech._vector%29), and immutable [prefab](structures.html#%28tech._prefab%29) structures containing message-allowed values, where a mutable box is automatically replaced by an immutable box, a mutable vector is automatically replaced by an immutable vector and where [impersonators](chaperones.html#%28tech._impersonator%29) of boxes, vectors and [prefab](structures.html#%28tech._prefab%29) structures are copied;\n- [hash tables](hashtables.html#%28tech._hash._table%29) where mutable hash tables are automatically replaced by immutable variants, and where a hash table [impersonator](chaperones.html#%28tech._impersonator%29) is copied;\n- [place channels](#%28tech._place._channel%29), where a [place descriptor](#%28tech._place._descriptor%29) is automatically replaced by a plain place channel;\n- [file-stream ports](file-ports.html#%28tech._file._stream._port%29) and [TCP ports](tcp.html#%28tech._tcp._port%29), where the underlying representation (such as a file descriptor, socket, or handle) is duplicated in the sending place and attached to a fresh port in the receiving place;"} {"text": "# 11.5 Places\n- [C pointers](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=foreign&rel=Pointer_Types.html%23%2528tech._c._pointer%2529&version=8.18.0.13) as created or accessed via [ffi/unsafe](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=foreign&rel=index.html&version=8.18.0.13); and\n- values produced by [shared-flvector](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._shared-flvector%29%29), [make-shared-flvector](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._make-shared-flvector%29%29), [shared-fxvector](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._shared-fxvector%29%29), [make-shared-fxvector](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._make-shared-fxvector%29%29), [shared-bytes](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._shared-bytes%29%29), and [make-shared-bytes](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._make-shared-bytes%29%29).\nChanged in version 8.4.0.7 of package base: Include boxes in allowed messages.\n> ```\nvalue\nprop:place-location : struct-type-property?\n(place-location? v)  →  boolean?\n  v : any/c"} {"text": "# 11.5 Places\n```\nA structure type property and associated predicate for implementations of place locations. The value of prop:place-location must be a procedure of four arguments: the place location itself, a module path, a symbol for the start function exported by the module, and a place name (which can be #f for an anonymous place).\n\nA place location can be passed as the #:at argument to dynamic-place, which in turn simply calls the prop:place-location value of the place location.\n\nA distributed places note created with create-place-node is an example of a place location.\n\n#### 11.5.2 Syntactic Support for Using Places\n\nThe bindings in this section are not provided by [racket/place/dynamic]().\n\n>
\n\n

syntax

\n\n

(place id body ...+)

\n\nCreates a place that evaluates body expressions with id bound to a place channel. The bodys close only over id plus the top-level bindings of the enclosing module, because the bodys are lifted to a submodule. The result of place is a place descriptor, like the result of dynamic-place.\n\nThe generated submodule has the name place-body-n for an integer n, and the submodule exports a main function that takes a place channel for the new place. The submodule is not intended for use, however, except by the expansion of the place form.\n\nThe place binding is protected in the same way as dynamic-place.\n\n> ```\nsyntax\n\n(place* maybe-port ...\n> id\n> body ...+ )\n \nmaybe-port   =  \n    |   #:in in-expr\n    |   #:out out-expr\n    |   #:err err-expr```\n\n\nLike [place](#%28form._%28%28lib._racket%2Fplace..rkt%29._place%29%29), but supports optional #:in, #:out, and #:err expressions (at most one of each) to specify ports in the same way and with the same defaults as [dynamic-place*](#%28def._%28%28lib._racket%2Fplace..rkt%29._dynamic-place%2A%29%29). The result of a [place*](#%28form._%28%28lib._racket%2Fplace..rkt%29._place%2A%29%29) form is also the same as for [dynamic-place*](#%28def._%28%28lib._racket%2Fplace..rkt%29._dynamic-place%2A%29%29).\n\nThe [place*](#%28form._%28%28lib._racket%2Fplace..rkt%29._place%2A%29%29) binding is protected in the same way as [dynamic-place](#%28def._%28%28lib._racket%2Fplace..rkt%29._dynamic-place%29%29).\n\n>
\n\n

syntax

\n\n

([place/context](#%28form._%28%28lib._racket%2Fplace..rkt%29._place%2Fcontext%29%29) id body ...+)

\n\nLike [place](#%28form._%28%28lib._racket%2Fplace..rkt%29._place%29%29), but body [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) may have free lexical variables, which are automatically sent to the newly-created place. Note that these variables must have values accepted by [place-message-allowed?](#%28def._%28%28lib._racket%2Fplace..rkt%29._place-message-allowed~3f%29%29), otherwise an [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\n> ```\n(processor-count)  →  exact-positive-integer?\n```"} {"text": "# 11.5 Places\n(current-logger)\t→\t\n(-> (any/c . → . void?) . → . any/c)```\nReturns an engine object to encapsulate a thread that runs only when allowed. The proc procedure should accept one argument, and proc is run in the engine thread when [engine-run](#%28def._%28%28lib._racket%2Fengine..rkt%29._engine-run%29%29) is called. If [engine-run](#%28def._%28%28lib._racket%2Fengine..rkt%29._engine-run%29%29) returns due to a timeout, then the engine thread is suspended until a future call to [engine-run](#%28def._%28%28lib._racket%2Fengine..rkt%29._engine-run%29%29). Thus, proc only executes during the dynamic extent of a [engine-run](#%28def._%28%28lib._racket%2Fengine..rkt%29._engine-run%29%29) call.\nThe argument to proc is a procedure that takes a boolean, and it can be used to disable suspends (in case proc has critical regions where it should not be suspended). A true value passed to the procedure enables suspends, and #f disables suspends. Initially, suspends are allowed.\n> ```\n(engine? v)  →  any\n  v : any/c"} {"text": "# 11.5 Places\n```\nReturns #t if v is an engine produced by engine, #f otherwise.\n\n> ```\n(engine-run until engine)  →  boolean?\n  until : (or/c evt? real?)\n  engine : engine?```\n\n\nAllows the thread associated with engine to execute for up to as long as until milliseconds (if until is a real number) or until is ready (if until is an event). If engine’s procedure disables suspends, then the engine can run arbitrarily long until it re-enables suspends.\n\nThe [engine-run](#%28def._%28%28lib._racket%2Fengine..rkt%29._engine-run%29%29) procedure returns #t if engine’s procedure completes (or if it completed earlier), and the result is available via [engine-result](#%28def._%28%28lib._racket%2Fengine..rkt%29._engine-result%29%29). The [engine-run](#%28def._%28%28lib._racket%2Fengine..rkt%29._engine-run%29%29) procedure returns #f if engine’s procedure does not complete before it is suspended. If engine’s procedure raises an exception, then it is re-raised by [engine-run](#%28def._%28%28lib._racket%2Fengine..rkt%29._engine-run%29%29).\n\n> ```\n(engine-result engine)  →  any\n  engine : engine?\n```\n(parameter)\t→```\nForcibly terminates the thread associated with engine if it is still running, leaving the engine result unchanged.\n------------------------------------------------------------------------"} {"text": "# 11.7 Machine Memory Order"} {"text": "### 11.7 Machine Memory Order\nUnlike Racket [threads](eval-model.html#%28tech._thread%29), futures and places can expose the underlying machine’s memory model, including a weak memory ordering. For example, when a future writes to multiple slots in a mutable vector, it’s possible on some platforms for another future to observe the writes in a different order or not at all, unless the futures are explicitly synchronized. Similarly, shared byte strings or [fxvectors](fixnums.html#%28tech._fxvector%29) can expose the machine’s memory model across places.\nRacket ensures that a machine’s memory model is not observed in a way that unsafely exposes the implementation of primitive datatypes. For example, it is not possible for one future to see a partially constructed primitive value as a result of reading a vector that is mutated by another future."} {"text": "# 11.7 Machine Memory Order\nThe [box-cas!](boxes.html#%28def._%28%28quote._~23~25kernel%29._box-cas%21%29%29), [vector-cas!](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector-cas%21%29%29), [unsafe-box*-cas!](unsafe.html#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-box%2A-cas%21%29%29), [unsafe-vector*-cas!](unsafe.html#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-vector%2A-cas%21%29%29), and [unsafe-struct*-cas!](unsafe.html#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-struct%2A-cas%21%29%29) operations all provide a machine-level compare-and-set, so they can be used in ways that are specifically supported by the a machine’s memory model. The ([memory-order-acquire](#%28def._%28%28quote._~23~25kernel%29._memory-order-acquire%29%29)) and ([memory-order-release](#%28def._%28%28quote._~23~25kernel%29._memory-order-release%29%29)) operations similarly constrain machine-level stores and loads. Synchronization operations such as place messages, future [touch](futures.html#%28def._%28%28lib._racket%2Ffuture..rkt%29._touch%29%29)es, and [future semaphores](futures.html#%28tech._future._semaphore%29) imply suitable machine-level acquire and release ordering.\n> ```\n(memory-order-acquire)\t→\t\n(-> memory-order-release)"} {"text": "# 11.7 Machine Memory Order\n```\n(parameter)\t→```\n\n\nFinds the first pattern that matches the syntax object produced by stx-expr, and for which the corresponding fender-expr (if any) produces a true value; the result is from the corresponding result-expr, which is in tail position for the [syntax-case](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax-case%29%29) form. If no clause matches, then the [exn:fail:syntax](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3asyntax%29%29) exception is raised; the exception is generated by calling [raise-syntax-error](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._raise-syntax-error%29%29) with #f as the “name” argument, a string with a generic error message, and the result of stx-expr.\n\nA syntax object matches a pattern as follows:\n\n> > | |\n> > |-----|\n> > | \\_ |\n>\n> A [_](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29.__%29%29) pattern (i.e., an identifier with the same binding as [_](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29.__%29%29) and not among the literal-ids) matches any syntax object.\n\n> > | |\n> > |-----|\n> > | id |\n>\n> An id matches any syntax object when it is not bound to [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) or [_](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29.__%29%29) and does not have the same binding as any literal-id. The id is further bound as pattern variable for the corresponding fender-expr (if any) and result-expr. A pattern-variable binding is a transformer binding; the pattern variable can be referenced only through forms like [syntax](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax%29%29). The binding’s value is the syntax object that matched the pattern with a depth marker of 0.\n>\n> With a stat-pattern, [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) is not treated specially. It either matches a literal-id or is bound as a pattern variable.\n>\n> An id that has the same binding as a literal-id matches a syntax object that is an identifier with the same binding in the sense of [free-identifier=?](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._free-identifier~3d~3f%29%29). The match does not introduce any [pattern variables](#%28tech._pattern._variable%29).\n\n> > | |\n> > |---------------|\n> > | (pattern ...) |\n>\n> A (pattern ...) pattern matches a syntax object whose datum form (i.e., without lexical information) is a list with as many elements as sub-patterns in the pattern, and where each syntax object that corresponds to an element of the list matches the corresponding sub-pattern.\n>\n> Any [pattern variables](#%28tech._pattern._variable%29) bound by the sub-patterns are bound by the complete pattern; the bindings must all be distinct.\n\n> > | |\n> > |-----------------------------|\n> > | (pattern ...+ . np-pattern) |\n>\n> Like the previous kind of pattern, but matches syntax objects that are not necessarily lists; for n sub-patterns before the final np-pattern, the syntax object’s datum must be a pair such that n-1 [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29)s produce pairs. The final np-pattern is matched against the syntax object corresponding to the nth [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) (or the [datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29) coercion of the datum using the nearest enclosing syntax object’s lexical context and source location).\n\n> > | |\n> > |--------------------------------------------|\n> > | (pattern ... pattern ellipsis pattern ...) |\n>\n> Like the (pattern ...) kind of pattern, but matching a syntax object with any number (zero or more) elements that match the sub-pattern followed by ellipsis in the corresponding position relative to other sub-patterns.\n>\n> For each pattern variable bound by the sub-pattern followed by ellipsis, the larger pattern binds the same pattern variable to a list of values, one for each element of the syntax object matched to the sub-pattern, with an incremented [depth marker](#%28tech._depth._marker%29). (The sub-pattern itself may contain ellipsis, leading to a pattern variables bound to lists of lists of syntax objects with a [depth marker](#%28tech._depth._marker%29) of 2, and so on.)\n>\n> All patterns forms with ellipsis apply only when ellipsis is not among the literal-ids.\n\n> > | |\n> > |---------------------------------------------------------|\n> > | (pattern ... pattern ellipsis pattern ... . np-pattern) |\n>\n> Like the previous kind of pattern, but with a final np-pattern as for (pattern [...+](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=syntax&rel=stxparse-patterns.html%23%2528form._%2528%2528lib._syntax%252Fparse..rkt%2529._......%252B%2529%2529&version=8.18.0.13) . np-pattern). The final np-pattern never matches a syntax object whose datum is a pair.\n\n> > | |\n> > |----------------|\n> > | #(pattern ...) |\n>\n> Like a (pattern ...) pattern, but matching a vector syntax object whose elements match the corresponding sub-patterns.\n\n> > | |\n> > |---------------------------------------------|\n> > | #(pattern ... pattern ellipsis pattern ...) |\n>\n> Like a (pattern [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) pattern ellipsis pattern [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) pattern, but matching a vector syntax object whose elements match the corresponding sub-patterns.\n\n> > | |\n> > |-----------|\n> > | #&pattern |\n>\n> Matches a box syntax object whose content matches the pattern.\n\n> > | |\n> > |---------------------------|\n> > | #s(key-datum pattern ...) |\n>\n> Like a (pattern ...) pattern, but matching a [prefab](structures.html#%28tech._prefab%29) structure syntax object whose fields match the corresponding sub-patterns. The key-datum must correspond to a valid first argument to [make-prefab-struct](structutils.html#%28def._%28%28quote._~23~25kernel%29._make-prefab-struct%29%29).\n\n> > | |\n> > |--------------------------------------------------------|\n> > | #s(key-datum pattern ... pattern ellipsis pattern ...) |\n>\n> Like a (pattern ... pattern ellipsis pattern ...) pattern, but matching a [prefab](structures.html#%28tech._prefab%29) structure syntax object whose elements match the corresponding sub-patterns.\n\n> > | |\n> > |-------------------------|\n> > | (ellipsis stat-pattern) |\n>\n> Matches the same as stat-pattern, which is like a pattern, but identifiers with the binding [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) are treated the same as other ids.\n\n> > | |\n> > |-------|\n> > | const |\n>\n> A const is any datum that does not match one of the preceding forms; a syntax object matches a const pattern when its datum is [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) to the [quote](quote.html#%28form._%28%28quote._~23~25kernel%29._quote%29%29)d const.\n\nIf stx-expr produces a non-[syntax object](syntax-model.html#%28tech._syntax._object%29), then its result is converted to a syntax object using [datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29) and the lexical context and source location of the stx-expr.\n\nIf stx-expr produces a syntax object that is [tainted](stxcerts.html#%28tech._tainted%29), then any syntax object bound by a pattern are [tainted](stxcerts.html#%28tech._tainted%29).\n\nExamples:\n\n> ```racket\n> > ( require ( for-syntax racket/base ) )\n> > ( define-syntax ( swap stx ) ( syntax-case stx ( ) [ ( _ a b ) #' ( let ( [ t a ] ) ( set! a b ) ( set! b t ) ) ] ) )\n> > ( let ( [ x 5 ] [ y 10 ] ) ( swap x y ) ( list x y ) )\n> '(10 5)\n> > ( syntax-case #' ( ops 1 2 3 => + ) ( => ) [ ( _ x ... => op ) #' ( op x ... ) ] )\n> #\n> > ( syntax-case #' ( let ( [ x 5 ] [ y 9 ] [ z 12 ] ) ( + x y z ) ) ( let ) [ ( let ( [ var expr ] ... ) body ... ) ( list #' ( var ... ) #' ( expr ... ) ) ] )\n> '(# #)\n> ```\n\n> ```\nsyntax\n\n(syntax-case* stx-expr (literal-id ...) id-compare-expr\n> clause ... )\n```"} {"text": "# 11.7 Machine Memory Order\nLike syntax-case, but id-compare-expr must produce a procedure that accepts two arguments. A literal-id in a pattern matches an identifier for which the procedure returns true when given the identifier to match (as the first argument) and the identifier in the pattern (as the second argument).\nIn other words, syntax-case is like syntax-case* with an id-compare-expr that produces free-identifier=?.\n> ```\nsyntax\n(with-syntax ([pattern stx-expr] ...)\n> body ...+ )```\nSimilar to [syntax-case](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax-case%29%29), in that it matches a pattern to a syntax object. Unlike [syntax-case](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax-case%29%29), all patterns are matched, each to the result of a corresponding stx-expr, and the pattern variables from all matches (which must be distinct) are bound with a single body sequence. The result of the [with-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._with-syntax%29%29) form is the result of the last body, which is in tail position with respect to the [with-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._with-syntax%29%29) form.\nIf any pattern fails to match the corresponding stx-expr, the [exn:fail:syntax](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3asyntax%29%29) exception is raised."} {"text": "# 11.7 Machine Memory Order\nA [with-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._with-syntax%29%29) form is roughly equivalent to the following [syntax-case](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax-case%29%29) form:\n> ```racket\n> ( syntax-case ( list stx-expr ... ) ( )\n> [ ( pattern ... ) ( let ( ) body ...+ ) ] )\n> ```\nHowever, if any individual stx-expr produces a non-[syntax object](syntax-model.html#%28tech._syntax._object%29), then it is converted to one using [datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29) and the lexical context and source location of the individual stx-expr.\nExamples:\n> ```racket\n> > ( define-syntax ( hello stx ) ( syntax-case stx ( ) [ ( _ name place ) ( with-syntax ( [ print-name #' ( printf \"~a\\n\" ' name ) ] [ print-place #' ( printf \"~a\\n\" ' place ) ] ) #' ( begin ( define ( name times ) ( printf \"Hello\\n\" ) ( for ( [ i ( in-range 0 times ) ] ) print-name ) ) ( define ( place times ) ( printf \"From\\n\" ) ( for ( [ i ( in-range 0 times ) ] ) print-place ) ) ) ) ] ) )\n> > ( hello jon utah )\n> > ( jon 2 )\n> Hello jon jon\n> > ( utah 2 )\n> From utah utah\n> > ( define-syntax ( math stx ) ( define ( make+1 expression ) ( with-syntax ( [ e expression ] ) #' ( + e 1 ) ) ) ( syntax-case stx ( ) [ ( _ numbers ... ) ( with-syntax ( [ ( added ... ) ( map make+1 ( syntax->list #' ( numbers ... ) ) ) ] ) #' ( begin ( printf \"got ~a\\n\" added ) ... ) ) ] ) )\n> > ( math 3 1 4 1 5 9 )\n> got 4 got 2 got 5 got 2 got 6 got 10\n> ```"} {"text": "# 11.7 Machine Memory Order\n>
\n

syntax

\n

([syntax](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax%29%29) template)

 
template = id
  | (head-template ...)
  | (head-template ...+ . template)
  | #(head-template ...)
  | #&template
  | #s(key-datum head-template ...)
  | ([~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29) template template)
  | (ellipsis stat-template)
  | const
     
head-template = template
  | head-template ellipsis ...+
  | ([~@](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~40%29%29) . template)
  | ([~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29) head-template head-template)
  | ([~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29) head-template)
     
stat-template = like template, but without [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29), [~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29), and [~@](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~40%29%29)
     
ellipsis = [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)
"} {"text": "# 11.7 Machine Memory Order\nConstructs a syntax object based on a template, which can include [pattern variables](#%28tech._pattern._variable%29) bound by [syntax-case](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax-case%29%29) or [with-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._with-syntax%29%29).\nA template produces a single syntax object. A head-template produces a sequence of zero or more syntax objects. A stat-template is like a template, except that [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29), [~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29), and [~@](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~40%29%29) are interpreted as constants instead of template forms.\nA template produces a syntax object as follows:"} {"text": "# 11.7 Machine Memory Order\n> > | |\n> > |-----|\n> > | id |\n>\n> If id is bound as a [pattern variable](#%28tech._pattern._variable%29), then id as a template produces the [pattern variable](#%28tech._pattern._variable%29)’s match result. Unless the id is a sub-template that is replicated by ellipsis in a larger template, the [pattern variable](#%28tech._pattern._variable%29)’s value must be a syntax object with a [depth marker](#%28tech._depth._marker%29) of 0 (as opposed to a list of matches).\n>\n> More generally, if the [pattern variable](#%28tech._pattern._variable%29)’s value has a depth marker n, then it can only appear within a template where it is replicated by at least n ellipsises. In that case, the template will be replicated enough times to use each match result at least once.\n>\n> If id is not bound as a pattern variable, then id as a template produces ([quote-syntax](Syntax_Quoting__quote-syntax.html#%28form._%28%28quote._~23~25kernel%29._quote-syntax%29%29) id).\n> > | |\n> > |---------------------|\n> > | (head-template ...) |\n>\n> Produces a syntax object whose datum is a list, and where the elements of the list correspond to syntax objects produced by the head-templates.\n> > | |\n> > |--------------------------------|\n> > | (head-template ... . template) |\n>\n> Like the previous form, but the result is not necessarily a list; instead, the place of the empty list in the resulting syntax object’s datum is taken by the syntax object produced by template."} {"text": "# 11.7 Machine Memory Order\n> > | |\n> > |----------------------|\n> > | #(head-template ...) |\n>\n> Like the (head-template [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) form, but producing a syntax object whose datum is a vector instead of a list.\n> > | |\n> > |------------|\n> > | #&template |\n>\n> Produces a syntax object whose datum is a box holding the syntax object produced by template.\n> > | |\n> > |---------------------------------|\n> > | #s(key-datum head-template ...) |\n>\n> Like the (head-template [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) form, but producing a syntax object whose datum is a [prefab](structures.html#%28tech._prefab%29) structure instead of a list. The key-datum must correspond to a valid first argument of [make-prefab-struct](structutils.html#%28def._%28%28quote._~23~25kernel%29._make-prefab-struct%29%29)."} {"text": "# 11.7 Machine Memory Order\n> > | |\n> > |----------------------------------------------------------------------------------------------------------------------------------------|\n> > | ([~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29) template1 template2) |\n>\n> Produces the result of template1 if template1 has no pattern variables with “missing values”; otherwise, produces the result of template2.\n>\n> A pattern variable bound by [syntax-case](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax-case%29%29) never has a missing value, but pattern variables bound by [syntax-parse](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=syntax&rel=Parsing_Syntax.html%23%2528form._%2528%2528lib._syntax%252Fparse..rkt%2529._syntax-parse%2529%2529&version=8.18.0.13) (for example, [~or](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=syntax&rel=stxparse-patterns.html%23%2528form._%2528%2528lib._syntax%252Fparse..rkt%2529._%7E7eor%2529%2529&version=8.18.0.13) or [~optional](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=syntax&rel=stxparse-patterns.html%23%2528form._%2528%2528lib._syntax%252Fparse..rkt%2529._%7E7eoptional%2529%2529&version=8.18.0.13) patterns) can.\n>\n> \n>\n> Examples:\n>\n> \n>\n> "} {"text": "# 11.7 Machine Memory Order\n>\n> > ```racket\n> > > ( syntax-parse #' ( m 1 2 3 ) [ ( _ ( ~optional ( ~seq #:op op:expr ) ) arg:expr ... ) #' ( ( ~? op + ) arg ... ) ] )\n> > #\n> > > ( syntax-parse #' ( m #:op max 1 2 3 ) [ ( _ ( ~optional ( ~seq #:op op:expr ) ) arg:expr ... ) #' ( ( ~? op + ) arg ... ) ] )\n> > #\n> > ```\n>\n> \n> > | |\n> > |--------------------------|\n> > | (ellipsis stat-template) |\n>\n> Produces the same result as stat-template, which is like a template, but [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29), [~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29), and [~@](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~40%29%29) are treated like an id (with no pattern binding).\n> > | |\n> > |-------|\n> > | const |\n>\n> A const template is any form that does not match the preceding cases, and it produces the result ([quote-syntax](Syntax_Quoting__quote-syntax.html#%28form._%28%28quote._~23~25kernel%29._quote-syntax%29%29) const).\nA head-template produces a sequence of syntax objects; that sequence is “inlined” into the result of the enclosing template. The result of a head-template is defined as follows:\n> > | |\n> > |----------|\n> > | template |\n>\n> Produces one syntax object, according to the rules for template above."} {"text": "# 11.7 Machine Memory Order\n> > | |\n> > |-----------------------------|\n> > | head-template ellipsis ...+ |\n>\n> Generates a sequence of syntax objects by “[map](pairs.html#%28def._%28%28lib._racket%2Fprivate%2Fmap..rkt%29._map%29%29)ping” the head-template over the values of its pattern variables. The number of iterations depends on the values of the [pattern variables](#%28tech._pattern._variable%29) referenced within the sub-template.\n>\n> To be more precise: Let outer be inner followed by one ellipsis. A [pattern variable](#%28tech._pattern._variable%29) is an iteration pattern variable for outer if occurs at a depth equal to its [depth marker](#%28tech._depth._marker%29). There must be at least one; otherwise, an error is raised. If there are multiple iteration variables, then all of their values must be lists of the same length. The result for outer is produced by [map](pairs.html#%28def._%28%28lib._racket%2Fprivate%2Fmap..rkt%29._map%29%29)ping the inner template over the [iteration pattern variable](#%28tech._iteration._pattern._variable%29) values and decreasing their effective [depth markers](#%28tech._depth._marker%29) by 1 within inner. The outer result is formed by appending the inner results.\n>\n> Consequently, if a [pattern variable](#%28tech._pattern._variable%29) occurs at a depth greater than its [depth marker](#%28tech._depth._marker%29), it is used as an [iteration pattern variable](#%28tech._iteration._pattern._variable%29) for the innermost ellipses but not the outermost. A [pattern variable](#%28tech._pattern._variable%29) must not occur at a depth less than its [depth marker](#%28tech._depth._marker%29); otherwise, an error is raised."} {"text": "# 11.7 Machine Memory Order\n> \n>\n> >
\n

syntax

\n

([~@](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~40%29%29) . template)

\n>\n> \n>\n> \n>\n> Produces the sequence of elements in the syntax list produced by template. If template does not produce a proper syntax list, an exception is raised.\n>\n> \n>\n> \n>\n> Examples:\n>\n> \n>\n> \n>\n> > ```racket\n> > > ( with-syntax ( [ ( key ... ) #' ( ' a ' b ' c ) ] [ ( val ... ) #' ( 1 2 3 ) ] ) #' ( hash ( ~@ key val ) ... ) )\n> > #\n> > > ( with-syntax ( [ xs #' ( 2 3 4 ) ] ) #' ( list 1 ( ~@ . xs ) 5 ) )\n> > #\n> > ```\n>\n> \n> \n>\n> >
\n

syntax

\n

([~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29) head-template1 head-template2)

\n>\n> \n>\n> \n>\n> Produces the result of head-template1 if none of its pattern variables have “missing values”; otherwise produces the result of head-template2.\n>\n> "} {"text": "# 11.7 Machine Memory Order\n> > | |\n> > |----------------------------------------------------------------------------------------------------------------------------------|\n> > | ([~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29) head-template) |\n>\n> Produces the result of head-template if none of its pattern variables have “missing values”; otherwise produces nothing.\n>\n> Equivalent to ([~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29) head-template ([~@](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~40%29%29))).\nA (syntax template) form is normally abbreviated as #'template; see also [Reading Quotes](reader.html#%28part._parse-quote%29). If template contains no pattern variables, then #'template is equivalent to ([quote-syntax](Syntax_Quoting__quote-syntax.html#%28form._%28%28quote._~23~25kernel%29._quote-syntax%29%29) template).\nChanged in version 6.90.0.25 of package base: Added [~@](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~40%29%29) and [~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29).\n>
\n

syntax

\n

([quasisyntax](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._quasisyntax%29%29) template)

"} {"text": "# 11.7 Machine Memory Order\nLike [syntax](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax%29%29), but ([unsyntax](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._unsyntax%29%29) expr) and ([unsyntax-splicing](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._unsyntax-splicing%29%29) expr) escape to an expression within the template.\nThe expr must produce a syntax object (or syntax list) to be substituted in place of the [unsyntax](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._unsyntax%29%29) or [unsyntax-splicing](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._unsyntax-splicing%29%29) form within the quasiquoting template, just like [unquote](quasiquote.html#%28form._%28%28quote._~23~25kernel%29._unquote%29%29) and [unquote-splicing](quasiquote.html#%28form._%28%28quote._~23~25kernel%29._unquote-splicing%29%29) within [quasiquote](quasiquote.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._quasiquote%29%29), except that a hash table value position is not an escape position for [quasisyntax](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._quasisyntax%29%29). (If the escaped expression does not generate a syntax object, it is converted to one in the same way as for the right-hand side of [with-syntax](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._with-syntax%29%29).) Nested [quasisyntax](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._quasisyntax%29%29)es introduce quasiquoting layers in the same way as nested [quasiquote](quasiquote.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._quasiquote%29%29)s."} {"text": "# 11.7 Machine Memory Order\nAlso analogous to [quasiquote](quasiquote.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._quasiquote%29%29), the reader converts #\\` to [quasisyntax](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._quasisyntax%29%29), #, to [unsyntax](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._unsyntax%29%29), and #,@ to [unsyntax-splicing](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._unsyntax-splicing%29%29). See also [Reading Quotes](reader.html#%28part._parse-quote%29).\n>
\n

syntax

\n

([unsyntax](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._unsyntax%29%29) [expr](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=syntax&rel=Library_Syntax_Classes_and_Literal_Sets.html%23%2528form._%2528%2528lib._syntax%252Fparse..rkt%2529._expr%2529%2529&version=8.18.0.13))

\nIllegal as an expression form. The [unsyntax](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._unsyntax%29%29) form is for use only with a [quasisyntax](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._quasisyntax%29%29) template.\n>
\n

syntax

\n

([unsyntax-splicing](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._unsyntax-splicing%29%29) expr)

"} {"text": "# 11.7 Machine Memory Order\nIllegal as an expression form. The [unsyntax-splicing](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._unsyntax-splicing%29%29) form is for use only with a [quasisyntax](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._quasisyntax%29%29) template.\n>
\n

syntax

\n

([syntax/loc](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax%2Floc%29%29) loc-expr template)

 
  loc-expr : 
( or/c #f srcloc? syntax?\n> ( list/c any/c\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f ) )\n> ( vector/c any/c\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f ) ) )
\nLike [syntax](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax%29%29), except that the immediate resulting syntax object takes its source-location information from the result of loc-expr."} {"text": "# 11.7 Machine Memory Order\nOnly the source location of the immediate result—the “outermost” syntax object—is adjusted. The source location is not adjusted if both the source and position of loc-expr are #f. The source location is adjusted only if the resulting syntax object comes from the template itself rather than the value of a syntax pattern variable. For example, if x is a syntax pattern variable, then ([syntax/loc](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax%2Floc%29%29) loc-expr x) does not use the location of loc-expr.\nChanged in version 6.90.0.25 of package base: Previously, [syntax/loc](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax%2Floc%29%29) did not enforce the contract on loc-expr if template was just a pattern variable. \nChanged in version 8.2.0.6: Allows loc-expr to be any source location value that [datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29) accepts.\n>
\n

syntax

"} {"text": "# 11.7 Machine Memory Order\n

([quasisyntax/loc](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._quasisyntax%2Floc%29%29) loc-expr template)

 
  loc-expr : 
( or/c #f srcloc? syntax?\n> ( list/c any/c\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f ) )\n> ( vector/c any/c\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f ) ) )
\nLike [quasisyntax](#%28form._%28%28lib._racket%2Fprivate%2Fqqstx..rkt%29._quasisyntax%29%29), but with source-location assignment like [syntax/loc](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax%2Floc%29%29).\nChanged in version 8.2.0.6 of package base: Allows loc-expr to be any source location value that [datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29) accepts.\n>
\n

syntax

"} {"text": "# 11.7 Machine Memory Order\n

([quote-syntax/prune](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._quote-syntax%2Fprune%29%29) id)

\nLike [quote-syntax](Syntax_Quoting__quote-syntax.html#%28form._%28%28quote._~23~25kernel%29._quote-syntax%29%29), but the lexical context of id is pruned via [identifier-prune-lexical-context](stxops.html#%28def._%28%28quote._~23~25kernel%29._identifier-prune-lexical-context%29%29) to including binding only for the symbolic name of id and for '#%top. Use this form to quote an identifier when its lexical information will not be transferred to other syntax objects (except maybe to '#%top for a top-level binding).\n> ```\nsyntax\n(syntax-rules (literal-id ...)\n> [ ( id . pattern ) template ] ... )"} {"text": "# 11.7 Machine Memory Order\n```\nEquivalent to\n\n> ```racket\n> ( lambda ( stx )\n> ( syntax-case stx ( literal-id ... )\n> [ ( generated-id . pattern ) ( syntax-protect #' template ) ] ... ) )\n> ```\n\nwhere each generated-id binds no identifier in the corresponding template. This in particular means that the id positions are ignored. Conventionally, the id positions should be the identifier _.\n\nExamples:\n\n> ```racket\n> > ( define-syntax my-let* ( syntax-rules ( ) [ ( _ ( ) body ... ) ( let ( ) body ... ) ] [ ( _ ( [ x v ] binding ... ) body ... ) ( let ( [ x v ] ) ( my-let* ( binding ... ) body ... ) ) ] ) )\n> > ( my-let* ( [ x 42 ] [ x ( + x 1 ) ] ) x )\n> 43\n> ```\n\n> ```\nsyntax\n\n(syntax-id-rules (literal-id ...)\n> [ pattern template ] ... )```\n\n\nEquivalent to\n\n> ```racket\n> ( make-set!-transformer\n> ( lambda ( stx )\n> ( syntax-case stx ( literal-id ... )\n> [ pattern ( syntax-protect #' template ) ] ... ) ) )\n> ```\n\n>
\n\n

syntax

\n\n

([define-syntax-rule](#%28form._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._define-syntax-rule%29%29) (id . pattern) template)

\n\nEquivalent to\n\n> ```racket\n> ( define-syntax id\n> ( syntax-rules ( )\n> [ ( id . pattern ) template ] ) )\n> ```\n\nbut with syntax errors potentially phrased in terms of pattern.\n\n>
\n\n

syntax

\n\n

[...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)

\n\nThe [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) transformer binding prohibits [...](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) from being used as an expression. This binding is useful only in syntax patterns and templates (or other unrelated expression forms that treat it specially like [->](function-contracts.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._-~3e%29%29)), where it indicates repetitions of a pattern or template. See [syntax-case](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax-case%29%29) and [syntax](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax%29%29).\n\n>
\n\n

syntax

\n\n

[_](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29.__%29%29)

\n\nThe [_](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29.__%29%29) transformer binding prohibits [_](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29.__%29%29) from being used as an expression. This binding is useful only in syntax patterns, where it indicates a pattern that matches any syntax object. See [syntax-case](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax-case%29%29).\n\n>
\n\n

syntax

\n\n

[~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29)

\n\n

syntax

\n\n

[~@](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~40%29%29)

\n\nThe [~?](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~3f%29%29) and [~@](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._~7e~40%29%29) transformer bindings prohibit these forms from being used as an expression. The bindings are useful only in syntax templates. See [syntax](#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax%29%29).\n\nAdded in version 6.90.0.25 of package base.\n\n> ```\n(syntax-pattern-variable? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 11.7 Machine Memory Order\nReturns #t if v is a value that, as a transformer-binding value, makes the bound variable as pattern variable in syntax and other forms. To check whether an identifier is a pattern variable, use syntax-local-value to get the identifier’s transformer value, and then test the value with syntax-pattern-variable?.\nThe syntax-pattern-variable? procedure is provided for-syntax by racket/base.\n------------------------------------------------------------------------"} {"text": "# 12.2 Syntax Object Content"} {"text": "### 12.2 Syntax Object Content\n> ```\n(syntax? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a [syntax object](syntax-model.html#%28tech._syntax._object%29), #f otherwise. See also [Syntax Objects](syntax-model.html#%28part._stxobj-model%29).\nExamples:\n> ```racket\n> > ( syntax? #' quinoa )\n> #t\n> > ( syntax? #' ( spelt triticale buckwheat ) )\n> #t\n> > ( syntax? ( datum->syntax #f ' millet ) )\n> #t\n> > ( syntax? \"barley\" )\n> #f\n> ```\n> ```\n(identifier? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a syntax object and (syntax-e stx) produces a symbol.\n\nExamples:\n\n> ```racket\n> > ( identifier? #' linguine )\n> #t\n> > ( identifier? #' ( if wheat? udon soba ) )\n> #f\n> > ( identifier? ' ramen )\n> #f\n> > ( identifier? 15 )\n> #f\n> ```\n\n> ```\n(syntax-source stx)  →  any/c\n  stx : syntax?```\n\n\nReturns the source component of the [source location](exns.html#%28tech._source._location%29) for the [syntax object](syntax-model.html#%28tech._syntax._object%29) stx, or #f if none is known. The source is represented by an arbitrary value (e.g., one passed to [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29)), but it is typically a file path string.\n\nSee also [syntax-srcloc](#%28def._%28%28lib._racket%2Fsyntax-srcloc..rkt%29._syntax-srcloc%29%29) from [racket/syntax-srcloc](#%28mod-path._racket%2Fsyntax-srcloc%29).\n\n> ```\n(syntax-line stx)  →  (or/c exact-positive-integer? #f)\n  stx : syntax?\n```"} {"text": "# 12.2 Syntax Object Content\nReturns the line number (positive exact integer) of the source location for the start of the syntax object in its source, or #f if the line number or source is unknown. See also Counting Positions, Lines, and Columns.\nChanged in version 7.0 of package base: Dropped a guarantee that syntax-line and syntax-column both produce #f or both produce integers.\n> ```\n(syntax-column stx)  →  (or/c exact-nonnegative-integer? #f)\n  stx : syntax?```\nReturns the column number (non-negative exact integer) of the [source location](exns.html#%28tech._source._location%29) for the start of the [syntax object](syntax-model.html#%28tech._syntax._object%29) in its source, or #f if the source column is unknown. See also [Counting Positions, Lines, and Columns](linecol.html).\nChanged in version 7.0 of package base: Dropped a guarantee that [syntax-line](#%28def._%28%28quote._~23~25kernel%29._syntax-line%29%29) and [syntax-column](#%28def._%28%28quote._~23~25kernel%29._syntax-column%29%29) both produce #f or both produce integers.\n> ```\n(syntax-position stx)  →  (or/c exact-positive-integer? #f)\n  stx : syntax?"} {"text": "# 12.2 Syntax Object Content\n```\nReturns the position (positive exact integer) of the source location for the start of the syntax object in its source, or #f if the source position is unknown. The position is intended to be a character position, but reading from a port without line counting enabled will produce a position as a byte offset. See also Counting Positions, Lines, and Columns.\n\n> ```\n(syntax-span stx)  →  (or/c exact-nonnegative-integer? #f)\n  stx : syntax?```\n\n\nReturns the span (non-negative exact integer) of the [source location](exns.html#%28tech._source._location%29) for [syntax object](syntax-model.html#%28tech._syntax._object%29) in its source, or #f if the span is unknown. The span is intended to count in characters, but reading from a port without line counting enabled will produce a span in bytes. See also [Counting Positions, Lines, and Columns](linecol.html).\n\n> ```\n(syntax-original? stx)  →  boolean?\n  stx : syntax?\n```\n(hidden)\t→\t\n(-> or/c module-path-index? symbol? path? resolved-module-path? #f)```"} {"text": "# 12.2 Syntax Object Content\nReturns an indication of the module whose source contains stx, or #f if no source module for stx can be inferred from its lexical context. If source? is #f, then result is a module path index or symbol (see [Compiled Modules and References](Module_Names_and_Loading.html#%28part._modpathidx%29)) or a [resolved module path](Module_Names_and_Loading.html#%28tech._resolved._module._path%29); if source? is true, the result is a path or symbol corresponding to the loaded module’s source in the sense of [current-module-declare-source](Module_Names_and_Loading.html#%28def._%28%28quote._~23~25kernel%29._current-module-declare-source%29%29).\nNote that [syntax-source-module](#%28def._%28%28quote._~23~25kernel%29._syntax-source-module%29%29) does not consult the source location of stx. The result is based on the [lexical information](syntax-model.html#%28tech._lexical._information%29) of stx.\n> ```\n(syntax-e stx)  →  any/c\n  stx : syntax?"} {"text": "# 12.2 Syntax Object Content\n```\nUnwraps the immediate datum structure from a syntax object, leaving nested syntax structure (if any) in place. The result of (syntax-e stx) is one of the following:\n\n- a symbol\n\n- a syntax pair (described below)\n\n- the empty list\n\n- an immutable vector containing syntax objects\n\n- an immutable box containing syntax objects\n\n- an immutable hash table containing syntax object values (but not necessarily syntax object keys)\n\n- an immutable prefab structure containing syntax objects\n\n- some other kind of datum—usually a number, boolean, or string—that is interned when datum-intern-literal would convert the value\n\nExamples:\n\n> ```racket\n> > ( syntax-e #' a )\n> 'a\n> > ( syntax-e #' ( x . y ) )\n> '(# . #)\n> > ( syntax-e #' # ( 1 2 ( + 3 4 ) ) )\n> '#(# # #)\n> > ( syntax-e #' #& \"hello world\" )\n> '#&#\n> > ( syntax-e #' #hash ( ( imperial . \"yellow\" ) ( festival . \"green\" ) ) )\n> '#hash((festival . #) (imperial . #))\n> > ( syntax-e #' # ( point 3 4 ) )\n> '#(# # #)\n> > ( syntax-e #' 3 )\n> 3\n> > ( syntax-e #' \"three\" )\n> \"three\"\n> > ( syntax-e #' #t )\n> #t\n> ```\n\nA syntax pair is a pair containing a syntax object as its first element, and either the empty list, a syntax pair, or a syntax object as its second element.\n\nA syntax object that is the result of read-syntax reflects the use of delimited . in the input by creating a syntax object for every pair of parentheses in the source, and by creating a pair-valued syntax object only for parentheses in the source. See Reading Pairs and Lists for more information.\n\nIf stx is tainted, then any syntax object in the result of (syntax-e stx) is tainted. The results from multiple calls to syntax-e of stx are eq?.\n\n> ```\n(syntax → list stx)  →  (or/c list? #f)\n  stx : syntax?```\n\n\nReturns a list of [syntax object](syntax-model.html#%28tech._syntax._object%29)s or #f. The result is a list of [syntax object](syntax-model.html#%28tech._syntax._object%29)s when ([syntax->datum](#%28def._%28%28quote._~23~25kernel%29._syntax-~3edatum%29%29) stx) would produce a list. In other words, [syntax pairs](#%28tech._syntax._pair%29) in ([syntax-e](#%28def._%28%28quote._~23~25kernel%29._syntax-e%29%29) stx) are flattened.\n\nIf stx is [tainted](stxcerts.html#%28tech._tainted%29), then any syntax object in the result of ([syntax->list](#%28def._%28%28quote._~23~25kernel%29._syntax-~3elist%29%29) stx) is [tainted](stxcerts.html#%28tech._tainted%29).\n\nExamples:\n\n> ```racket\n> > ( syntax->list #' ( ) )\n> '()\n> > ( syntax->list #' ( 1 ( + 3 4 ) 5 6 ) )\n> '(# # # #)\n> > ( syntax->list #' a )\n> #f\n> ```\n\n> ```\n(syntax → datum stx)  →  any/c\n  stx : syntax?\n```"} {"text": "# 12.2 Syntax Object Content\nReturns a datum by stripping the lexical information, source-location information, properties, and tamper status from stx. Inside of pairs, (immutable) vectors, (immutable) boxes, immutable hash table values (not keys), and immutable prefab structures, syntax objects are recursively stripped.\nThe stripping operation does not mutate stx; it creates new pairs, vectors, boxes, hash tables, and prefab structures as needed to strip lexical and source-location information recursively.\nExamples:\n> ```racket\n> > ( syntax → datum #' a )\n> 'a\n> > ( syntax → datum #' ( x . y ) )\n> '(x . y)\n> > ( syntax → datum #' # ( 1 2 ( + 3 4 ) ) )\n> '#(1 2 (+ 3 4))\n> > ( syntax → datum #' #& \"hello world\" )\n> '#&\"hello world\"\n> > ( syntax → datum #' #hash ( ( imperial . \"yellow\" ) ( festival . \"green\" ) ) )\n> '#hash((festival . \"green\") (imperial . \"yellow\"))\n> > ( syntax → datum #' # ( point 3 4 ) )\n> '#(point 3 4)\n> > ( syntax → datum #' 3 )\n> 3\n> > ( syntax → datum #' \"three\" )\n> \"three\"\n> > ( syntax → datum #' #t )\n> #t\n> ```\n> ```\n(datum → syntax ctxt v [srcloc prop ignored) → syntax?\n  ctxt : (or/c syntax? #f)\n  v : any/c\n   srcloc   :   ( or/c #f\n> syntax?\n> srcloc?\n> ( list/c any/c\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f ) )\n> ( vector/c any/c\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f ) ) )\n      =   #f"} {"text": "# 12.2 Syntax Object Content\n  prop : (or/c syntax? #f) = #f\n  ignored : (or/c syntax? #f) = #f```\nConverts the [datum](reader.html#%28tech._datum%29) v to a [syntax object](syntax-model.html#%28tech._syntax._object%29). If v is already a [syntax object](syntax-model.html#%28tech._syntax._object%29), then there is no conversion, and v is returned unmodified. The contents of pairs, vectors, and boxes, the values of immutable hash tables, and the fields of immutable [prefab](structures.html#%28tech._prefab%29) structures are recursively converted. The keys of [prefab](structures.html#%28tech._prefab%29) structures and the keys of immutable hash tables are not converted. Mutable vectors and boxes are replaced by immutable vectors and boxes. For any kind of value other than a pair, vector, box, immutable [hash table](hashtables.html#%28tech._hash._table%29), immutable [prefab](structures.html#%28tech._prefab%29) structure, or [syntax object](syntax-model.html#%28tech._syntax._object%29), conversion means wrapping the value with lexical information, source-location information, and properties after the value is [interned](reader.html#%28tech._interned%29) via [datum-intern-literal](#%28def._%28%28quote._~23~25kernel%29._datum-intern-literal%29%29)."} {"text": "# 12.2 Syntax Object Content\nConverted objects in v are given the lexical context information of ctxt and the source-location information of srcloc. The resulting immediate [syntax object](syntax-model.html#%28tech._syntax._object%29) from conversion is given the properties (see [Syntax Object Properties](stxprops.html)) of prop (even the hidden ones that would not be visible via [syntax-property-symbol-keys](stxprops.html#%28def._%28%28quote._~23~25kernel%29._syntax-property-symbol-keys%29%29)); if v is a pair, vector, box, immutable [hash table](hashtables.html#%28tech._hash._table%29), or immutable [prefab](structures.html#%28tech._prefab%29) structure, recursively converted values are not given properties. If ctxt is [tainted](stxcerts.html#%28tech._tainted%29), then the resulting syntax object from [datum->syntax](#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29) is [tainted](stxcerts.html#%28tech._tainted%29). The [code inspector](modprotect.html#%28tech._code._inspector%29) of ctxt, if any, is compared to the code inspector of the module for the macro currently being transformed, if any; if both inspectors are available and if one is the same as or inferior to the other, then the result syntax has the same/inferior inspector, otherwise it has no code inspector.\nAny of ctxt, srcloc, or prop can be #f, in which case the resulting syntax has no lexical context, source information, and/or new properties."} {"text": "# 12.2 Syntax Object Content\nIf srcloc is not #f, a [srcloc](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29) instance, or a [syntax object](syntax-model.html#%28tech._syntax._object%29), it must be a list or vector of five elements that correspond to [srcloc](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29) fields.\nGraph structure is not preserved by the conversion of v to a [syntax object](syntax-model.html#%28tech._syntax._object%29). Instead, v is essentially unfolded into a tree. If v has a cycle through pairs, vectors, boxes, immutable [hash tables](hashtables.html#%28tech._hash._table%29), and immutable [prefab](structures.html#%28tech._prefab%29) structures, then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nThe ignored argument is allowed for backward compatibility and has no effect on the returned syntax object.\nChanged in version 8.2.0.5 of package base: Allow a [srcloc](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29) value as a srcloc argument.\n> ```\n(syntax-binding-set)\t→\t\n(-> syntax-binding-set)"} {"text": "# 12.2 Syntax Object Content\n```\nA syntax binding set supports explicit construction of binding information for a syntax object. Start by creating an empty binding set with syntax-binding-set, add bindings with syntax-binding-set-extend, and create a syntax object that has the bindings as its lexical information using syntax-binding-set → syntax.\n\nThe first three arguments to syntax-binding-set-extend establish a binding of symbol at phase to an identifier that is defined in the module referenced by mpi. Supply source-symbol to make the binding of symbol refer to a different provided variable from mpi, and so on; the optional arguments correspond to the results of identifier-binding.\n\nAdded in version 7.0.0.12 of package base.\n\n> ```\n(datum-intern-literal v)  →  any/c\n  v : any/c```\n\n\nConverts some values to be consistent with an [interned](reader.html#%28tech._interned%29) result produced by the default reader in [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29) mode.\n\nIf v is a [number](numbers.html#%28tech._number%29), [character](characters.html#%28tech._character%29), [string](strings.html#%28tech._string%29), [byte string](bytestrings.html#%28tech._byte._string%29), or [regular expression](regexp.html#%28tech._regular._expression%29), then the result is a value that is [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) to v and [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to a potential result of the default reader. (Note that mutable strings and byte strings are [interned](reader.html#%28tech._interned%29) as immutable strings and byte strings.)\n\nIf v is an [uninterned](symbols.html#%28tech._uninterned%29) or an [unreadable symbol](symbols.html#%28tech._unreadable._symbol%29), the result is still v, since an [interned](reader.html#%28tech._interned%29) symbol would not be [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) to v.\n\nThe conversion process does not traverse compound values. For example, if v is a [pair](pairs.html#%28tech._pair%29) containing strings, then the strings within v are not [interned](reader.html#%28tech._interned%29).\n\nIf v1 and v2 are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) but not [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29), then it is possible that ([datum-intern-literal](#%28def._%28%28quote._~23~25kernel%29._datum-intern-literal%29%29) v1) will return v1 and—sometime after v1 becomes unreachable as determined by the garbage collector (see [Garbage Collection](eval-model.html#%28part._gc-model%29))—([datum-intern-literal](#%28def._%28%28quote._~23~25kernel%29._datum-intern-literal%29%29) v2) can still return v2. In other words, [datum-intern-literal](#%28def._%28%28quote._~23~25kernel%29._datum-intern-literal%29%29) may adopt a given value as an [interned](reader.html#%28tech._interned%29) representative, but if a former representative becomes otherwise unreachable, then [datum-intern-literal](#%28def._%28%28quote._~23~25kernel%29._datum-intern-literal%29%29) may adopt a new representative.\n\n> ```\n(syntax-shift-phase-level stx shift)  →  syntax?\n  stx : syntax?\n  shift : (or/c exact-integer? #f)\n```"} {"text": "# 12.2 Syntax Object Content\nReturns a syntax object that is like stx, but with all of its top-level and module bindings shifted by shift phase levels. If shift is #f, then only bindings at phase level 0 are shifted to the label phase level. If shift is 0, then the result is stx.\n> ```\n(generate-temporaries v)  →  (listof identifier?)\n  v : stx-list?```\nReturns a list of identifiers that are distinct from all other identifiers. The list contains as many identifiers as v contains elements. The elements of v can be anything, but string, symbol, keyword (possibly wrapped as syntax), and identifier elements will be embedded in the corresponding generated name, which is useful for debugging purposes.\nThe generated identifiers are built with interned symbols (not [gensym](symbols.html#%28def._%28%28quote._~23~25kernel%29._gensym%29%29)s); see also [Printing Compiled Code](printing.html#%28part._print-compiled%29).\nExamples:\n> ```racket\n> > ( generate-temporaries ' ( a b c d ) )\n> '(# # # #)\n> > ( generate-temporaries #' ( 1 2 3 4 ) )\n> '(# # # #)\n> > ( define-syntax ( set!-values stx ) ( syntax-case stx ( ) [ ( _ ( id ... ) expr ) ( with-syntax ( [ ( temp ... ) ( generate-temporaries #' ( id ... ) ) ] ) #' ( let-values ( [ ( temp ... ) expr ] ) ( set! id temp ) ... ( void ) ) ) ] ) )\n> ```\n> ```\n(parameter)\t→\t\n(-> listof symbol?)"} {"text": "# 12.2 Syntax Object Content\n```\nReturns an identifier with the same binding as id-stx, but without possibly lexical information from id-stx that does not apply to the symbols in syms, where even further extension of the lexical information drops information for other symbols. In particular, transferring the lexical context via datum → syntax from the result of this function to a symbol other than one in syms may produce an identifier with no binding.\n\nCurrently, the result is always id-stx exactly. Pruning was intended primarily as a kind of optimization in a previous version of Racket, but it is less useful and difficult to implement efficiently in the current macro expander.\n\nSee also quote-syntax/prune.\n\nChanged in version 6.5 of package base: Always return id-stx.\n\n> ```\n(identifier-prune-to-source-module id-stx)  →  identifier?\n  id-stx : identifier?```\n\n\nReturns an identifier with its lexical context minimized to that needed for [syntax-source-module](#%28def._%28%28quote._~23~25kernel%29._syntax-source-module%29%29). The minimized lexical context does not include any bindings.\n\n> ```\n(syntax-recertify   new-stx        \n    old-stx        \n    inspector        \n    key)   →   syntax?\n\n  new-stx : syntax?\n  old-stx : syntax?\n  inspector : inspector?\n  key : any/c\n```\nFor backward compatibility only; returns new-stx.\n> ```\n(syntax-debug-info stx [phase all-bindings?) → hash?\n  stx : syntax?\n  phase : (or/c exact-integer? #f) = (syntax-local-phase-level)\n  all-bindings? : any/c = #f```"} {"text": "# 12.2 Syntax Object Content\nProduces a hash table that describes the [lexical information](syntax-model.html#%28tech._lexical._information%29) of stx (not counting components when ([syntax-e](#%28def._%28%28quote._~23~25kernel%29._syntax-e%29%29) stx) would return a compound value). The result can include—but is not limited to—the following keys:\n- 'name — the result of ([syntax-e](#%28def._%28%28quote._~23~25kernel%29._syntax-e%29%29) stx), if it is a symbol.\n- 'context — a list of vectors, where each vector represents a scope attached to stx.\n Each vector starts with a number that is distinct for every scope. A symbol afterward provides a hint at the scope’s origin: 'module for a [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) scope, 'macro for a macro-introduction scope, 'use-site for a macro use-site scope, or 'local for a local binding form. In the case of a 'module scope that corresponds to the inside edge, the module’s name and a phase (since an inside-edge scope is generated for each phase) are shown.\n- 'bindings — a list of bindings, each represented by a hash table. A binding table can include—but is not limited to—the following keys:\n - 'name — the symbolic name for the binding.\n - 'context — the scopes, as a list of vectors, for the binding.\n - 'local — a symbol representing a [local binding](syntax-model.html#%28tech._local._binding%29); when this key is present, 'module is absent.\n - 'module — an encoding of a import from another module; when this key is present, 'local is absent."} {"text": "# 12.2 Syntax Object Content\n - 'free-identifier=? — a hash table of debugging information from an identifier for which the binding is an alias.\n- 'fallbacks — a list of hash tables like the one produced by [syntax-debug-info](#%28def._%28%28quote._~23~25kernel%29._syntax-debug-info%29%29) for cross-namespace binding fallbacks.\nAdded in version 6.3 of package base."} {"text": "#### 12.2.1 Syntax Object Source Locations\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/syntax-srcloc](#%28mod-path._racket%2Fsyntax-srcloc%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/syntax-srcloc](#%28mod-path._racket%2Fsyntax-srcloc%29) library, not [racket/base](index.html) or [racket](index.html).\n> ```\n(syntax-srcloc stx)  →  (or/c #f srcloc?)\n  stx : syntax?"} {"text": "# 12.2 Syntax Object Content\n```\nReturns the source location for the syntax object stx, or #f if none is known.\n\nAdded in version 8.2.0.5 of package base.\n\n------------------------------------------------------------------------\n\n# 12.3 Syntax Object Bindings\n\n### 12.3 Syntax Object Bindings\n\n> ```\n(bound-identifier=? a-id b-id [phase-level) → boolean?\n  a-id : syntax?\n  b-id : syntax?\n   phase-level   :   (or/c exact-integer? #f)\n      =   (syntax-local-phase-level)```\n\n\nReturns #t if the identifier a-id would bind b-id (or vice versa) if the identifiers were substituted in a suitable expression context at the [phase level](syntax-model.html#%28tech._phase._level%29) indicated by phase-level, #f otherwise. A #f value for phase-level corresponds to the [label phase level](syntax-model.html#%28tech._label._phase._level%29).\n\nExamples:\n\n> ```racket\n> > ( define-syntax ( check stx ) ( syntax-case stx ( ) [ ( _ x y ) ( if ( bound-identifier=? #' x #' y ) #' ( let ( [ y ' wrong ] ) ( let ( [ x ' binds ] ) y ) ) #' ( let ( [ y ' no-binds ] ) ( let ( [ x ' wrong ] ) y ) ) ) ] ) )\n> > ( check a a )\n> 'binds\n> > ( check a b )\n> 'no-binds\n> > ( define-syntax-rule ( check-a x ) ( check a x ) )\n> > ( check-a a )\n> 'no-binds\n> ```\n\n> ```\n(free-identifier=? a-id\n    b-id        \n   [ a-phase-level        \n    b-phase-level)   →   boolean?\n\n  a-id : identifier?\n  b-id : identifier?\n   a-phase-level   :   (or/c exact-integer? #f)\n      =   (syntax-local-phase-level)\n\n  b-phase-level : (or/c exact-integer? #f) = a-phase-level\n```"} {"text": "# 12.2 Syntax Object Content\nReturns #t if a-id and b-id access the same local binding, module binding, or top-level binding—perhaps via rename transformers—at the phase levels indicated by a-phase-level and b-phase-level, respectively. A #f value for a-phase-level or b-phase-level corresponds to the label phase level.\n“Same module binding” means that the identifiers refer to the same original definition site, and not necessarily to the same require or provide site. Due to renaming in require and provide, or due to a transformer binding to a rename transformer, the identifiers may return distinct results with syntax-e.\nExamples:\n> ```racket\n> > ( define-syntax ( check stx ) ( syntax-case stx ( ) [ ( _ x ) ( if ( free-identifier=? #' car #' x ) #' ( list ' same: x ) #' ( list ' different: x ) ) ] ) )\n> > ( check car )\n> '(same: #)\n> > ( check mcar )\n> '(different: #)\n> > ( let ( [ car list ] ) ( check car ) )\n> '(different: #)\n> > ( require ( rename-in racket/base [ car kar ] ) )\n> > ( check kar )\n> '(same: #)\n> ```\n> ```\n(free-transformer-identifier=? a-id b-id) → boolean?\n  a-id : identifier?\n  b-id : identifier?```\nSame as ([free-identifier=?](#%28def._%28%28quote._~23~25kernel%29._free-identifier~3d~3f%29%29) a-id b-id ([add1](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._add1%29%29) ([syntax-local-phase-level](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._syntax-local-phase-level%29%29)))).\n> ```\n(free-template-identifier=? a-id b-id) → boolean?\n  a-id : identifier?\n  b-id : identifier?"} {"text": "# 12.2 Syntax Object Content\n```\nSame as (free-identifier=? a-id b-id (sub1 (syntax-local-phase-level))).\n\n> ```\n(free-label-identifier=? a-id b-id) → boolean?\n  a-id : identifier?\n  b-id : identifier?```\n\n\nSame as ([free-identifier=?](#%28def._%28%28quote._~23~25kernel%29._free-identifier~3d~3f%29%29) a-id b-id #f).\n\n> ```\n(check-duplicate-identifier ids)  →  (or/c identifier? #f)\n  ids : (listof identifier?)\n```\n(syntax-local-phase-level)\t→\t\n(-> or/c ' lexical\n #f\n (list/c module-path-index?\n symbol?\n module-path-index?\n symbol?\n exact-nonnegative-integer?\n phase+space-shift?\n phase+space?)\n (list/c symbol?))```\nReturns one of three (if top-level-symbol? is #f) or four (if top-level-symbol? is true) kinds of values, depending on the binding of id-stx at the [phase level](syntax-model.html#%28tech._phase._level%29) indicated by phase-level (where a #f value for phase-level corresponds to the [label phase level](syntax-model.html#%28tech._label._phase._level%29)):\n- The result is 'lexical if id-stx has a [local binding](syntax-model.html#%28tech._local._binding%29).\n- The result is a list of seven items when id-stx has a [module binding](syntax-model.html#%28tech._module._binding%29): ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) from-mod from-sym nominal-from-mod nominal-from-sym from-phase import-phase+space-shift nominal-export-phase)."} {"text": "# 12.2 Syntax Object Content\n - from-mod is a module path index (see [Compiled Modules and References](Module_Names_and_Loading.html#%28part._modpathidx%29)) that indicates the defining module. It is the “self” module path index if the binding refers to a definition in the enclosing module of id-stx.\n - from-sym is a symbol for the identifier’s name at its definition site in the originating module. This can be different from the local name returned by [syntax->datum](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-~3edatum%29%29) for several reasons: the identifier is renamed on import, it is renamed on export, or it is implicitly renamed because the binding site was generated by a macro invocation. In that last case, it may be an [unreadable symbol](symbols.html#%28tech._unreadable._symbol%29), and it may be different from the result of [syntax->datum](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-~3edatum%29%29) on the identifier in the original source definition."} {"text": "# 12.2 Syntax Object Content\n - nominal-from-mod is a module path index (see [Compiled Modules and References](Module_Names_and_Loading.html#%28part._modpathidx%29)) that indicates the binding’s module as it appears locally in the source around id-stx: it indicates a module [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29)d into the context of id-stx to provide its binding, or it is the same “self” as from-mod for a binding that refers to a definition in the enclosing module of id-stx. It can be different from from-mod due to a re-export in nominal-from-mod of some imported identifier. If the same binding is imported in multiple ways, an arbitrary representative is chosen.\n - nominal-from-sym is a symbol for the binding’s identifier as it appears locally in the source around id-stx: it is the identifier’s name as exported by nominal-from-mod, or it is the source identifier’s symbol for a definition within the enclosing module of id-stx. It can be different from from-sym due to a renaming [provide](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29), even if from-mod and nominal-from-mod are the same, or due to a definition that was introduced by a macro expansion.\n - from-phase is an exact non-negative integer representing the originating phase. For example, it is 1 if the definition is for-syntax."} {"text": "# 12.2 Syntax Object Content\n - import-phase+space-shift is 0 if the binding import of nominal-from-mode is from a definition or a plain [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29), 1 if it is from a [for-syntax](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-syntax%29%29) import, a phase combined with a space name if it is from a [for-space](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-space%29%29) import, etc.\n - nominal-export-phase+space is the [phase level](syntax-model.html#%28tech._phase._level%29) and [binding space](syntax-model.html#%28tech._binding._space%29) of the export from nominal-from-mod for an imported binding, or it is the phase level of the definition for a binding from the enclosing module of id-stx.\n- The result is ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) top-sym) if id-stx has a [top-level binding](syntax-model.html#%28tech._top._level._binding%29) and top-level-symbol? is true. The top-sym can be different from the name returned by [syntax->datum](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-~3edatum%29%29) when the binding definition was generated by a macro invocation.\n- The result is #f if id-stx has a [top-level binding](syntax-model.html#%28tech._top._level._binding%29) and top-level-symbol? is #f or if id-stx is [unbound](syntax-model.html#%28tech._unbound%29). An unbound identifier is typically treated the same as an identifier whose top-level binding is a variable."} {"text": "# 12.2 Syntax Object Content\nIf id-stx is bound to a [rename-transformer](syntax-model.html#%28tech._rename._transformer%29), the result from [identifier-binding](#%28def._%28%28quote._~23~25kernel%29._identifier-binding%29%29) is for the identifier in the transformer, so that [identifier-binding](#%28def._%28%28quote._~23~25kernel%29._identifier-binding%29%29) is consistent with [free-identifier=?](#%28def._%28%28quote._~23~25kernel%29._free-identifier~3d~3f%29%29).\nIf exact-scopes? is a true value, then the result is #f unless the binding for id-stx has exactly the [scopes](syntax-model.html#%28tech._scope%29) of id-stx. An exact-scopes check is useful for detecting whether an identifier is already bound in a specific definition context, for example.\nChanged in version 6.6.0.4 of package base: Added the top-level-symbol? argument to report information on top-level bindings. \nChanged in version 8.2.0.3: Generalized phase results to phase–space combinations. \nChanged in version 8.6.0.9: Added the exact-scopes? argument.\n> ```\n(syntax-local-phase-level)\t→\t\n(-> or/c ' lexical\n #f\n (listof module-path-index?\n symbol?\n module-path-index?\n symbol?\n exact-nonnegative-integer?\n phase+space-shift?\n phase+space?))"} {"text": "# 12.2 Syntax Object Content\n```\n(parameter)\t→\t\n(-> or/c ' lexical\n #f\n (listof module-path-index?\n symbol?\n module-path-index?\n symbol?\n phase+space?\n phase+space-shift?\n phase+space?))```\n\n\nSame as ([identifier-binding](#%28def._%28%28quote._~23~25kernel%29._identifier-binding%29%29) id-stx ([sub1](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._sub1%29%29) ([syntax-local-phase-level](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._syntax-local-phase-level%29%29)))).\n\nChanged in version 8.2.0.3 of package base: Generalized phase results to phase–space combinations.\n\n> ```\n(parameter)\t→\t\n(-> or/c ' lexical\n #f\n (listof module-path-index?\n symbol?\n module-path-index?\n symbol?\n exact-nonnegative-integer?\n phase+space-shift?\n phase+space?))\n```\n(syntax-local-phase-level)\t→\t\n(-> or/c ' lexical\n #f\n (list/c module-path-index?\n symbol?\n module-path-index?\n symbol?\n exact-nonnegative-integer?\n phase+space-shift?\n phase+space?)\n (list/c symbol?))```\nLike ([identifier-binding](#%28def._%28%28quote._~23~25kernel%29._identifier-binding%29%29) id-stx phase-level top-level-symbol?), but the result is #f if the binding for id-stx has scopes that are a subset of the scopes for wrt-id-stx. That is, if id-stx and wrt-id-stx have the same symbolic name, a binding for id-stx is returned only if the binding does not also apply to wrt-id-stx.\nAdded in version 8.3.0.8 of package base. \nChanged in version 8.8.0.2: Added the top-level-symbol? argument.\n> ```"} {"text": "# 12.2 Syntax Object Content\n(syntax-local-phase-level)\t→\t\n(-> or/c exact-integer? #f)\n```\nLike identifier-binding, but produces a symbol that corresponds to the binding. The symbol result is the same for any identifiers that are free-identifier=?, but the result may also be the same for identifiers that are not free-identifier=? (i.e., different symbols imply different bindings, but the same symbol does not imply the same binding).\n\nWhen identifier-binding would produce a list, then the second element of that list is the result that identifier-binding-symbol produces.\n\n> ```\n(identifier-binding-portal-syntax id-stx\n   [ phase-level)  \n\n  →  (or/c #f syntax?)\n  id-stx : identifier?\n   phase-level   :   (or/c exact-integer? #f)\n      =   (syntax-local-phase-level)```\n\n\nIf id-stx is bound at phase-level to [portal syntax](stxtrans.html#%28tech._portal._syntax%29), either via [define-syntax](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29) or [#%require](require.html#%28form._%28%28quote._~23~25kernel%29._~23~25require%29%29), then the portal syntax content is returned. The module that binds id-stx must be declared, but it need not be instantiated at the relevant phase, and [identifier-binding-portal-syntax](#%28def._%28%28quote._~23~25kernel%29._identifier-binding-portal-syntax%29%29) does not instantiate the module.\n\nAdded in version 8.3.0.8 of package base.\n\n> ```\n(syntax-local-phase-level)\t→\t\n(-> listof symbol?)\n```\n(syntax-local-phase-level)\t→\t\n(-> syntax-local-phase-level)```"} {"text": "# 12.2 Syntax Object Content\nReturns a list of sym names of [interned scopes](stxtrans.html#%28tech._interned._scope%29) for which ([identifier-binding](#%28def._%28%28quote._~23~25kernel%29._identifier-binding%29%29) (([make-interned-syntax-introducer](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._make-interned-syntax-introducer%29%29) sym) stx) phase-level #f exact-scopes?) could produce a non-#f value. This procedure takes time proportional to the number of scopes on stx plus the length of the result list.\nAdded in version 8.13.0.8 of package base.\n> ```\n(syntax-bound-phases stx)  →  (listof (or/c exact-integer? #f))\n  stx : stx?\n```\nReturns a list that includes all phase-levels for which (syntax-bound-symbols stx phase-level) might produce a non-empty list.\n\nExamples:\n\n> ```racket\n> > ( syntax-bound-phases #' anything )\n> '(2 1 0)\n> > ( require ( for-meta 8 racket/base ) )\n> > ( syntax-bound-phases #' anything )\n> '(9 8 2 1 0)\n> ```\n\nAdded in version 8.6.0.8 of package base.\n\n------------------------------------------------------------------------\n\n# 12.4 Syntax Transformers\n\n### 12.4 Syntax Transformers\n\n> ```\n(set!-transformer? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a value created by [make-set!-transformer](#%28def._%28%28quote._~23~25kernel%29._make-set%21-transformer%29%29) or an instance of a structure type with the [prop:set!-transformer](#%28def._%28%28quote._~23~25kernel%29._prop~3aset%21-transformer%29%29) property, #f otherwise.\n\n> ```\n(make-set!-transformer proc)  →  set!-transformer?\n  proc : (syntax? . → . syntax?)\n```"} {"text": "# 12.2 Syntax Object Content\nCreates an assignment transformer that cooperates with set!. If the result of make-set!-transformer is bound to id as a transformer binding, then proc is applied as a transformer when id is used in an expression position, or when it is used as the target of a set! assignment as (set! id expr). When the identifier appears as a set! target, the entire set! expression is provided to the transformer.\nExample:\n> ```racket\n> > ( let ( [ x 1 ] [ y 2 ] ) ( let-syntax ( [ x ( make-set!-transformer ( lambda ( stx ) ( syntax-case stx ( set! ) ; Redirect mutation of x to y [ ( set! id v ) #' ( set! y v ) ] ; Normal use of x really gets x [ id ( identifier? #' id ) #' x ] ) ) ) ] ) ( begin ( set! x 3 ) ( list x y ) ) ) )\n> '(1 3)\n> ```\n> ```\n(set!-transformer-procedure transformer)\n  →  (syntax? . → . syntax?)\n  transformer : set!-transformer?```\nReturns the procedure that was passed to [make-set!-transformer](#%28def._%28%28quote._~23~25kernel%29._make-set%21-transformer%29%29) to create transformer or that is identified by the [prop:set!-transformer](#%28def._%28%28quote._~23~25kernel%29._prop~3aset%21-transformer%29%29) property of transformer.\n>
\n

value

\n

[prop:set!-transformer](#%28def._%28%28quote._~23~25kernel%29._prop~3aset%21-transformer%29%29) : [struct-type-property?](structprops.html#%28def._%28%28quote._~23~25kernel%29._struct-type-property~3f%29%29)

"} {"text": "# 12.2 Syntax Object Content\nA [structure type property](structprops.html#%28tech._structure._type._property%29) to identify structure types that act as [assignment transformers](syntax-model.html#%28tech._assignment._transformer%29) like the ones created by [make-set!-transformer](#%28def._%28%28quote._~23~25kernel%29._make-set%21-transformer%29%29).\nThe property value must be an exact integer or procedure of one or two arguments. In the former case, the integer designates a field within the structure that should contain a procedure; the integer must be between 0 (inclusive) and the number of non-automatic fields in the structure type (exclusive, not counting supertype fields), and the designated field must also be specified as immutable."} {"text": "# 12.2 Syntax Object Content\nIf the property value is a procedure of one argument, then the procedure serves as a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) and for [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) transformations. If the property value is a procedure of two arguments, then the first argument is the structure whose type has [prop:set!-transformer](#%28def._%28%28quote._~23~25kernel%29._prop~3aset%21-transformer%29%29) property, and the second argument is a syntax object as for a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) and for [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) transformations; [set!-transformer-procedure](#%28def._%28%28quote._~23~25kernel%29._set%21-transformer-procedure%29%29) applied to the structure produces a new function that accepts just the syntax object and calls the procedure associated through the property. Finally, if the property value is an integer, the target identifier is extracted from the structure instance; if the field value is not a procedure of one argument, then a procedure that always calls [raise-syntax-error](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._raise-syntax-error%29%29) is used, instead."} {"text": "# 12.2 Syntax Object Content\nIf a value has both the [prop:set!-transformer](#%28def._%28%28quote._~23~25kernel%29._prop~3aset%21-transformer%29%29) and [prop:rename-transformer](#%28def._%28%28quote._~23~25kernel%29._prop~3arename-transformer%29%29) properties, then the latter takes precedence. If a structure type has the [prop:set!-transformer](#%28def._%28%28quote._~23~25kernel%29._prop~3aset%21-transformer%29%29) and [prop:procedure](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._prop~3aprocedure%29%29) properties, then the former takes precedence for the purposes of macro expansion.\n> ```\n(rename-transformer? v)  →  boolean?\n  v : any/c"} {"text": "# 12.2 Syntax Object Content\n```\nReturns #t if v is a value created by make-rename-transformer or an instance of a structure type with the prop:rename-transformer property, #f otherwise.\n\nExamples:\n\n> ```racket\n> > ( rename-transformer? ( make-rename-transformer #' values ) )\n> #t\n> > ( rename-transformer? ' not-a-rename-transformer )\n> #f\n> ```\n\n> ```\n(make-rename-transformer id-stx)  →  rename-transformer?\n  id-stx : syntax?```\n\n\nCreates a [rename transformer](syntax-model.html#%28tech._rename._transformer%29) that, when used as a [transformer](syntax-model.html#%28tech._transformer%29) binding, acts as a transformer that inserts the identifier id-stx in place of whatever identifier binds the transformer, including in non-application positions, in [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) expressions.\n\nSuch a transformer could be written manually, but the one created by [make-rename-transformer](#%28def._%28%28quote._~23~25kernel%29._make-rename-transformer%29%29) triggers special cooperation with the parser and other syntactic forms when id is bound to the rename transformer:\n\n- The parser installs a [free-identifier=?](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._free-identifier~3d~3f%29%29) and [identifier-binding](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._identifier-binding%29%29) equivalence between id and id-stx, as long as id-stx does not have a true value for the 'not-free-identifier=? [syntax property](stxprops.html#%28tech._syntax._property%29).\n\n- A [provide](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) of id provides the binding indicated by id-stx instead of id, as long as id-stx does not have a true value for the 'not-free-identifier=? [syntax property](stxprops.html#%28tech._syntax._property%29) and as long as id-stx has a binding.\n\n- If [provide](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) exports id, it uses a symbol-valued 'nominal-id property of id-stx to specify the “nominal source identifier” of the binding as reported by [identifier-binding](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._identifier-binding%29%29).\n\n- If id-stx has a true value for the 'not-provide-all-defined [syntax property](stxprops.html#%28tech._syntax._property%29), then id (or its target) is not exported by [all-defined-out](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-defined-out%29%29).\n\n- The [syntax-local-value](#%28def._%28%28quote._~23~25kernel%29._syntax-local-value%29%29) function recognizes rename-transformer bindings and consult their targets.\n\nExamples:\n\n> ```racket\n> > ( define-syntax my-or ( make-rename-transformer #' or ) )\n> > ( my-or #f #t )\n> #t\n> > ( free-identifier=? #' my-or #' or )\n> #t\n> ```\n\nChanged in version 6.3 of package base: Removed an optional second argument. \nChanged in version 7.4.0.10: Adjusted rename-transformer expansion to add a macro-introduction scope, the same as regular macro expansion.\n\n> ```\n(rename-transformer-target transformer)  →  identifier?\n  transformer : rename-transformer?\n```"} {"text": "# 12.2 Syntax Object Content\nReturns the identifier passed to make-rename-transformer to create transformer or as indicated by a prop:rename-transformer property on transformer.\nExample:\n> ```racket\n> > ( rename-transformer-target ( make-rename-transformer #' or ) )\n> #\n> ```\n>
\n

value

\n

prop:rename-transformer : struct-type-property?

\nA structure type property to identify structure types that act as rename transformers like the ones created by make-rename-transformer.\nThe property value must be an exact integer, an identifier syntax object, or a procedure that takes one argument. In the former case, the integer designates a field within the structure that should contain an identifier; the integer must be between 0 (inclusive) and the number of non-automatic fields in the structure type (exclusive, not counting supertype fields), and the designated field must also be specified as immutable.\nIf the property value is an identifier, the identifier serves as the target for renaming, just like the first argument to make-rename-transformer. If the property value is an integer, the target identifier is extracted from the structure instance; if the field value is not an identifier, then an identifier ? with an empty context is used, instead."} {"text": "# 12.2 Syntax Object Content\nIf the property value is a procedure that takes one argument, then the procedure is called to obtain the identifier that the rename transformer will use as a target identifier. The returned identifier should probably have the 'not-free-identifier=? syntax property. If the procedure returns any value that is not an identifier, the exn:fail:contract exception is raised.\nExamples:\n> ```racket\n> ; Example of a procedure argument for prop:rename-transformer\n> > ( define-syntax slv-1 ' first-transformer-binding )\n> > ( define-syntax slv-2 ' second-transformer-binding )\n> > ( begin-for-syntax ( struct slv-cooperator ( redirect-to-first? ) #:property prop:rename-transformer ( λ ( inst ) ( if ( slv-cooperator-redirect-to-first? inst ) #' slv-1 #' slv-2 ) ) ) )\n> > ( define-syntax ( slv-lookup stx ) ( syntax-case stx ( ) [ ( _ id ) #` ' #, ( syntax-local-value #' id ) ] ) )\n> > ( define-syntax slv-inst-1 ( slv-cooperator #t ) )\n> > ( define-syntax slv-inst-2 ( slv-cooperator #f ) )\n> > ( slv-lookup slv-inst-1 )\n> 'first-transformer-binding\n> > ( slv-lookup slv-inst-2 )\n> 'second-transformer-binding\n> ```\nChanged in version 6.3 of package base: the property now accepts a procedure of one argument.\n> ```\n(local-expand stx\n    context-v        \n    stop-ids        \n   [ intdef-ctx)   →   syntax?\n  stx : any/c\n  context-v : (or/c 'expression 'top-level 'module 'module-begin list?)\n  stop-ids : (or/c (listof identifier?) empty #f)\n   intdef-ctx   :   ( or/c internal-definition-context?\n> #f\n> ( listof internal-definition-context? ) )   =   #f```"} {"text": "# 12.2 Syntax Object Content\nExpands stx in the lexical context of the expression currently being expanded. The context-v argument is used as the result of [syntax-local-context](#%28def._%28%28quote._~23~25kernel%29._syntax-local-context%29%29) for immediate expansions; a list indicates an [internal-definition context](syntax-model.html#%28tech._internal._definition._context%29), and more information on the form of the list is below. If stx is not already a [syntax object](syntax-model.html#%28tech._syntax._object%29), it is coerced with ([datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29) #f stx) before expansion.\nThe stop-ids argument controls how far [local-expand](#%28def._%28%28quote._~23~25kernel%29._local-expand%29%29) expands stx:\n- If stop-ids is an empty list, then stx is recursively expanded (i.e. expansion proceeds to sub-expressions). The result is guaranteed to be a fully-expanded form, which can include the bindings listed in [Fully Expanded Programs](syntax-model.html#%28part._fully-expanded%29), plus [#%expression](__expression.html#%28form._%28%28quote._~23~25kernel%29._~23~25expression%29%29) in any expression position."} {"text": "# 12.2 Syntax Object Content\n- If stop-ids is a list containing just [module*](module.html#%28form._%28%28quote._~23~25kernel%29._module%2A%29%29), then expansion proceeds as if stop-ids were an empty list, except that expansion does not recur to [submodules](eval-model.html#%28tech._submodule%29) defined with [module*](module.html#%28form._%28%28quote._~23~25kernel%29._module%2A%29%29) (which are left unexpanded in the result).\n- If stop-ids is any other list, then [begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29), [quote](quote.html#%28form._%28%28quote._~23~25kernel%29._quote%29%29), [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29), [#%plain-lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~23~25plain-lambda%29%29), [case-lambda](lambda.html#%28form._%28%28quote._~23~25kernel%29._case-lambda%29%29), [let-values](let.html#%28form._%28%28quote._~23~25kernel%29._let-values%29%29), [letrec-values](let.html#%28form._%28%28quote._~23~25kernel%29._letrec-values%29%29), [if](if.html#%28form._%28%28quote._~23~25kernel%29._if%29%29), [begin0](begin.html#%28form._%28%28quote._~23~25kernel%29._begin0%29%29), [with-continuation-mark](wcm.html#%28form._%28%28quote._~23~25kernel%29._with-continuation-mark%29%29), [letrec-syntaxes+values](let.html#%28form._%28%28quote._~23~25kernel%29._letrec-syntaxes%2Bvalues%29%29), [#%plain-app](application.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~23~25plain-app%29%29), [#%expression](__expression.html#%28form._%28%28quote._~23~25kernel%29._~23~25expression%29%29), [#%top](__top.html#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29), and [#%variable-reference](Locations____variable-reference.html#%28form._%28%28quote._~23~25kernel%29._~23~25variable-reference%29%29) are implicitly added to stop-ids. Expansion proceeds recursively, stopping when the expander encounters any of the forms in stop-ids, and the result is the partially-expanded form."} {"text": "# 12.2 Syntax Object Content\n When the expander would normally implicitly introduce a #%app, #%datum, or #%top identifier as described in [Expansion Steps](syntax-model.html#%28part._expand-steps%29), it checks to see if an identifier with the same [binding](syntax-model.html#%28tech._binding%29) as the one to be introduced appears in stop-ids. If so, the identifier is not introduced; the result of expansion is the bare application, literal data expression, or unbound identifier rather than one wrapped in the respective explicit form.\n When [#%plain-module-begin](module.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~23~25plain-module-begin%29%29) is not in stop-ids, the [#%plain-module-begin](module.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~23~25plain-module-begin%29%29) transformer detects and expands sub-forms (such as [define-values](define.html#%28form._%28%28quote._~23~25kernel%29._define-values%29%29)) regardless of the identifiers presence in stop-ids.\n Expansion does not replace the scopes in a local-variable reference to match the binding identifier.\n- If stop-ids is #f instead of a list, then stx is expanded only as long as the outermost form of stx is a macro (i.e. expansion does not proceed to sub-expressions, and it does not replace the scopes in a local-variable reference to match the binding identifier). The #%app, #%datum, and #%top identifiers are never introduced."} {"text": "# 12.2 Syntax Object Content\nIndependent of stop-ids, when [local-expand](#%28def._%28%28quote._~23~25kernel%29._local-expand%29%29) encounters an identifier that has a local binding but no binding in the current expansion context, the variable is left as-is (as opposed to triggering an “out of context” syntax error).\nWhen context-v is 'module-begin, and the result of expansion is a [#%plain-module-begin](module.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~23~25plain-module-begin%29%29) form, then a 'submodule [syntax property](stxprops.html#%28tech._syntax._property%29) is added to each enclosed [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) form (but not [module*](module.html#%28form._%28%28quote._~23~25kernel%29._module%2A%29%29) forms) in the same way as by [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) expansion."} {"text": "# 12.2 Syntax Object Content\nIf the intdef-ctx argument is an internal-definition context, its [bindings](syntax-model.html#%28tech._binding%29) and [bindings](syntax-model.html#%28tech._binding%29) from all [parent internal-definition contexts](#%28tech._parent._internal._definition._context%29) are added to the [local binding context](syntax-model.html#%28tech._local._binding._context%29) during the dynamic extent of the call to [local-expand](#%28def._%28%28quote._~23~25kernel%29._local-expand%29%29). Additionally, unless #f was provided for the add-scope? argument to [syntax-local-make-definition-context](#%28def._%28%28quote._~23~25kernel%29._syntax-local-make-definition-context%29%29) when the internal-definition context was created, its [inside-edge scope](syntax-model.html#%28tech._inside._edge._scope%29) (but not the scopes of any [parent internal-definition contexts](#%28tech._parent._internal._definition._context%29)) is added to the [lexical information](syntax-model.html#%28tech._lexical._information%29) for both stx prior to its expansion and the expansion result (because the expansion might introduce bindings or references to internal-definition bindings)."} {"text": "# 12.2 Syntax Object Content\nFor backwards compatibility, when intdef-ctx is a list all [bindings](syntax-model.html#%28tech._binding%29) from all of the provided internal-definition contexts and their parents are added to the [local binding context](syntax-model.html#%28tech._local._binding._context%29), and the [inside-edge scope](syntax-model.html#%28tech._inside._edge._scope%29) from each context for which add-scope? was not #f is added in the same way.\nExpansion records [use-site scopes](syntax-model.html#%28tech._use._site._scope%29) for removal from definition bindings. When the intdef-ctx argument is an internal-definition context, use-site scopes are recorded with that context. When intdef-ctx is #f or (for backwards compatibility) a list, use-site scopes are recorded with the current expand context."} {"text": "# 12.2 Syntax Object Content\nFor a particular [internal-definition context](syntax-model.html#%28tech._internal._definition._context%29), generate a unique value and put it into a list for context-v. To allow [liberal expansion](#%28tech._liberal._expansion%29) of [define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) forms, the generated value should be an instance of a structure with a true value for [prop:liberal-define-context](#%28def._%28%28quote._~23~25kernel%29._prop~3aliberal-define-context%29%29). If the internal-definition context is meant to be self-contained, the list for context-v should contain only the generated value; if the internal-definition context is meant to splice into an immediately enclosing context, then when [syntax-local-context](#%28def._%28%28quote._~23~25kernel%29._syntax-local-context%29%29) produces a list, [cons](pairs.html#%28def._%28%28quote._~23~25kernel%29._cons%29%29) the generated value onto that list."} {"text": "# 12.2 Syntax Object Content\nWhen expressions are expanded via [local-expand](#%28def._%28%28quote._~23~25kernel%29._local-expand%29%29) with an internal-definition context intdef-ctx, and when the expanded expressions are incorporated into an overall form new-stx, then typically [internal-definition-context-track](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=syntax&rel=intdef.html%23%2528def._%2528%2528lib._syntax%252Fintdef..rkt%2529._internal-definition-context-track%2529%2529&version=8.18.0.13) should be applied to intdef-ctx and new-stx to provide expansion history to external tools.\nThis procedure must be called during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander or while a module is [visit](syntax-model.html#%28tech._visit%29)ed (see [syntax-transforming?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nExamples:"} {"text": "# 12.2 Syntax Object Content\n> ```racket\n> > ( define-syntax-rule ( do-print x ... ) ( printf x ... ) )\n> > ( define-syntax-rule ( hello x ) ( do-print \"hello ~a\" x ) )\n> > ( define-syntax ( show stx ) ( syntax-case stx ( ) [ ( _ x ) ( let ( [ partly ( local-expand #' ( hello x ) ' expression ( list #' do-print ) ) ] [ fully ( local-expand #' ( hello x ) ' expression #f ) ] ) ( printf \"partly expanded: ~s\\n\" ( syntax->datum partly ) ) ( printf \"fully expanded: ~s\\n\" ( syntax->datum fully ) ) fully ) ] ) )\n> > ( show 1 )\n> partly expanded: (do-print \"hello ~a\" 1) fully expanded: (printf \"hello ~a\" 1) hello 1\n> ```\nThis procedure’s binding is provided as [protected](modprotect.html#%28tech._protected%29) in the sense of [protect-out](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._protect-out%29%29).\nChanged in version 6.0.1.3 of package base: Changed treatment of [#%top](__top.html#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) so that it is never introduced as an explicit wrapper. \nChanged in version 6.0.90.27: Loosened the contract on the intdef-ctx argument to allow an empty list. \nChanged in version 8.2.0.4: Changed binding to [protected](modprotect.html#%28tech._protected%29).\n> ```\n(syntax-local-expand-expression stx\n   [ opaque-only?)  \n  →   (if opaque-only? #f syntax?)   syntax?\n  stx : any/c\n  opaque-only? : any/c = #f"} {"text": "# 12.2 Syntax Object Content\n```\nLike local-expand given 'expression and an empty stop list, but with two results: a syntax object for the fully expanded expression, and a syntax object whose content is opaque.\n\nThe latter can be used in place of the former (perhaps in a larger expression produced by a macro transformer), and when the macro expander encounters the opaque object, it substitutes the fully expanded expression without re-expanding it; the exn:fail:syntax exception is raised if the expansion context includes scopes that were not present for the original expansion, in which case re-expansion might produce different results. Consistent use of syntax-local-expand-expression and the opaque object thus avoids quadratic expansion times when local expansions are nested.\n\nIf opaque-only? is true, then the first result is #f instead of the expanded expression. Obtaining only the second, opaque result can be more efficient in some expansion contexts.\n\nUnlike local-expand, syntax-local-expand-expression normally produces an expanded expression that contains no #%expression forms. However, if syntax-local-expand-expression is used within an expansion that is triggered by an enclosing local-expand call, then the result of syntax-local-expand-expression can include #%expression forms.\n\nThis procedure must be called during the dynamic extent of a syntax transformer application by the expander or while a module is visited (see syntax-transforming?), otherwise the exn:fail:contract exception is raised.\n\nThis procedure’s binding is provided as protected in the sense of protect-out.\n\nChanged in version 6.90.0.13 of package base: Added the opaque-only? argument. \nChanged in version 8.2.0.4: Changed binding to protected.\n\n> ```\n(local-transformer-expand stx\n    context-v        \n    stop-ids        \n   [ intdef-ctx)   →   syntax?\n\n  stx : any/c\n  context-v : (or/c 'expression 'top-level list?)\n  stop-ids : (or/c (listof identifier?) #f)\n   intdef-ctx   :   ( or/c internal-definition-context?\n> #f\n> ( listof internal-definition-context? ) )   =   #f```\n\n\nLike [local-expand](#%28def._%28%28quote._~23~25kernel%29._local-expand%29%29), but stx is expanded as a transformer expression instead of a run-time expression.\n\nAny lifted expressions—from calls to [syntax-local-lift-expression](#%28def._%28%28quote._~23~25kernel%29._syntax-local-lift-expression%29%29) during the expansion of stx—are captured in the result. If context-v is 'top-level, then lifts are captured in a [begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) form, otherwise lifts are captured in [let-values](let.html#%28form._%28%28quote._~23~25kernel%29._let-values%29%29) forms. If no expressions are lifted during expansion, then no [begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) or [let-values](let.html#%28form._%28%28quote._~23~25kernel%29._let-values%29%29) wrapper is added.\n\nThis procedure’s binding is provided as [protected](modprotect.html#%28tech._protected%29) in the sense of [protect-out](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._protect-out%29%29).\n\nChanged in version 6.5.0.3 of package base: Allowed and captured lifts in a 'top-level context. \nChanged in version 8.2.0.4: Changed binding to [protected](modprotect.html#%28tech._protected%29).\n\n> ```\n(local-expand/capture-lifts stx\n    context-v        \n    stop-ids        \n   [ intdef-ctx        \n    lift-ctx)   →   syntax?\n\n  stx : any/c\n  context-v : (or/c 'expression 'top-level 'module 'module-begin list?)\n  stop-ids : (or/c (listof identifier?) #f)\n   intdef-ctx   :   ( or/c internal-definition-context?\n> #f\n> ( listof internal-definition-context? ) )   =   #f\n\n  lift-ctx : any/c = (gensym 'lifts)\n```"} {"text": "# 12.2 Syntax Object Content\nLike local-expand, but the result is a syntax object that represents a begin expression. Lifted expressions—from calls to syntax-local-lift-expression during the expansion of stx—appear with their identifiers in define-values forms, and the expansion of stx is the last expression in the begin. The lift-ctx value is reported by syntax-local-lift-context during local expansion. The lifted expressions are not expanded, but instead left as provided in the begin form.\nIf context-v is 'top-level or 'module, then module forms can appear in the result as added via syntax-local-lift-module. If context-v is 'module, then module* forms can appear, too.\nThis procedure’s binding is provided as protected in the sense of protect-out.\nChanged in version 8.2.0.4 of package base: Changed binding to protected.\n> ```\n(local-transformer-expand/capture-lifts stx\n    context-v        \n    stop-ids        \n   [ intdef-ctx        \n    lift-ctx)   →   syntax?\n  stx : any/c\n  context-v : (or/c 'expression 'top-level list?)\n  stop-ids : (or/c (listof identifier?) #f)\n   intdef-ctx   :   ( or/c internal-definition-context?\n> #f\n> ( listof internal-definition-context? ) )   =   #f\n  lift-ctx : any/c = (gensym 'lifts)```\nLike [local-expand/capture-lifts](#%28def._%28%28quote._~23~25kernel%29._local-expand%2Fcapture-lifts%29%29), but stx is expanded as a transformer expression instead of a run-time expression. Lifted expressions are reported as [define-values](define.html#%28form._%28%28quote._~23~25kernel%29._define-values%29%29) forms (in the transformer environment)."} {"text": "# 12.2 Syntax Object Content\nThis procedure’s binding is provided as [protected](modprotect.html#%28tech._protected%29) in the sense of [protect-out](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._protect-out%29%29).\nChanged in version 8.2.0.4 of package base: Changed binding to [protected](modprotect.html#%28tech._protected%29).\n> ```\n(syntax-local-apply-transformer transformer\n    binding-id        \n    context-v        \n    intdef-ctx        \n    v ...)   →   any\n  transformer : procedure?\n  binding-id : (or/c identifier? #f)\n  context-v : (or/c 'expression 'top-level 'module 'module-begin list?)\n  intdef-ctx : (or/c internal-definition-context? #f)\n  v : any/c"} {"text": "# 12.2 Syntax Object Content\n```\nApplies the procedure transformer to the vs in a new expansion context and local binding context. Adds and flips macro-introduction scopes and use-site scopes on the arguments and return values in the same manner as syntax transformer application. The arguments and returns may be any value; scopes are manipulated only for those that are syntax objects.\n\nThe context-v argument is as in local-expand, and the intdef-ctx is an internal-definition context value or #f. The binding-id specifies a binding associated with the transformer, which the expander uses to determine whether to add use-site scopes and which code inspector to use during expansion.\n\nThis procedure must be called during the dynamic extent of a syntax transformer application by the expander or while a module is visited (see syntax-transforming?), otherwise the exn:fail:contract exception is raised.\n\nAdded in version 8.2.0.7 of package base.\n\n> ```\n(internal-definition-context? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is an [internal-definition context](syntax-model.html#%28tech._internal._definition._context%29), #f otherwise.\n\n> ```\n(syntax-local-make-definition-context [parent-ctx\n    add-scope?)  \n\n  →  internal-definition-context?\n  parent-ctx : (or/c internal-definition-context? #f) = #f\n  add-scope? : any/c = #t\n```\n(partial)\t→\t\n(-> (syntax?) ((or/c 'flip 'add 'remove)) . → * . syntax?)```"} {"text": "# 12.2 Syntax Object Content\nLike [make-syntax-introducer](#%28def._%28%28quote._~23~25kernel%29._make-syntax-introducer%29%29), but the encapsulated [scope](syntax-model.html#%28tech._scope%29) is pruned from [quote-syntax](Syntax_Quoting__quote-syntax.html#%28form._%28%28quote._~23~25kernel%29._quote-syntax%29%29) forms, much like the scopes associated with a new definition context (see [syntax-local-make-definition-context](#%28def._%28%28quote._~23~25kernel%29._syntax-local-make-definition-context%29%29)). The name argument is used as the symbolic name, which serves as a debugging aid.\nTypically, [internal-definition-context-add-scopes](#%28def._%28%28quote._~23~25kernel%29._internal-definition-context-add-scopes%29%29) and [internal-definition-context-splice-binding-identifier](#%28def._%28%28quote._~23~25kernel%29._internal-definition-context-splice-binding-identifier%29%29) are preferred, but this function can be useful when you are sure that you want a single scope that should be pruned from [quote-syntax](Syntax_Quoting__quote-syntax.html#%28form._%28%28quote._~23~25kernel%29._quote-syntax%29%29) forms."} {"text": "# 12.2 Syntax Object Content\nThis procedure must be called during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander or while a module is [visit](syntax-model.html#%28tech._visit%29)ed (see [syntax-transforming?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nAdded in version 8.12.0.8 of package base.\n> ```\n(internal-definition-context-add-scopes   intdef-ctx        \n    stx)   →   syntax?\n  intdef-ctx : internal-definition-context?\n  stx : syntax?"} {"text": "# 12.2 Syntax Object Content\n```\nAdds the outside-edge scope and inside-edge scope for intdef-ctx to stx.\n\nUse this function to apply the definition context scopes to syntax that originates within the definition context before expansion.\n\nAdded in version 8.2.0.7 of package base.\n\n> ```\n(internal-definition-context-splice-binding-identifier  \n    intdef-ctx  \n    id)  \n\n  →  syntax?\n  intdef-ctx : internal-definition-context?\n  id : identifier?```\n\n\nRemoves scopes associated with the intdef-ctx from id: the [outside-edge scope](syntax-model.html#%28tech._outside._edge._scope%29), the [inside-edge scope](syntax-model.html#%28tech._inside._edge._scope%29), and [use-site scopes](syntax-model.html#%28tech._use._site._scope%29) created by expansions within the definition context.\n\nUse when splicing a binding originating within the intdef-ctx into a surrounding context.\n\nAdded in version 8.2.0.7 of package base.\n\n> ```\n(syntax-local-bind-syntaxes id-list\n    expr  \n    intdef-ctx  \n   [ extra-intdef-ctxs)  \n\n  →  (listof identifier?)\n  id-list : (listof identifier?)\n  expr : (or/c syntax? #f)\n  intdef-ctx : internal-definition-context?\n   extra-intdef-ctxs   :   ( or/c internal-definition-context?\n> ( listof internal-definition-context? ) )\n      =   '()\n```\nBinds each identifier in id-list within the internal-definition context represented by intdef-ctx, where intdef-ctx is the result of syntax-local-make-definition-context. Returns identifiers with lexical information matching the new bindings."} {"text": "# 12.2 Syntax Object Content\nFor backwards compatibility, the lexical information of each element of extra-intdef-ctxs is also added to each identifier in id-list before binding.\nSupply #f for expr when the identifiers correspond to define-values bindings, and supply a compile-time expression when the identifiers correspond to define-syntaxes bindings. In the latter case, the number of values produced by the expression should match the number of identifiers, otherwise the exn:fail:contract:arity exception is raised.\nWhen expr is not #f, it is expanded in an expression context and evaluated in the current transformer environment. In this case, the bindings and lexical information from both intdef-ctx and extra-intdef-ctxs are used to enrich expr’s lexical information and extend the local binding context in the same way as the fourth argument to local-expand. If expr is #f, the value provided for extra-intdef-ctxs is ignored.\nThis procedure must be called during the dynamic extent of a syntax transformer application by the expander or while a module is visited (see syntax-transforming?), otherwise the exn:fail:contract exception is raised.\nChanged in version 6.90.0.27 of package base: Added the extra-intdef-ctxs argument. \nChanged in version 8.2.0.7: Changed the return value from # to the list of bound identifiers.\n> ```\n(internal-definition-context-binding-identifiers intdef-ctx)\n  →  (listof identifier?)\n  intdef-ctx : internal-definition-context?```"} {"text": "# 12.2 Syntax Object Content\nReturns a list of all binding identifiers registered for intdef-ctx through [syntax-local-bind-syntaxes](#%28def._%28%28quote._~23~25kernel%29._syntax-local-bind-syntaxes%29%29). Each identifier in the returned list includes the [internal-definition context](syntax-model.html#%28tech._internal._definition._context%29)’s [scope](syntax-model.html#%28tech._scope%29).\nAdded in version 6.3.0.4 of package base.\n> ```\n(internal-definition-context-introduce intdef-ctx\n    stx        \n   [ mode)   →   syntax?\n  intdef-ctx : internal-definition-context?\n  stx : syntax?\n  mode : (or/c 'flip 'add 'remove) = 'flip\n```\n(parameter)\t→```\n\n\nFor backward compatibility only; has no effect.\n\n> ```\n(identifier-remove-from-definition-context   id-stx  \n    intdef-ctx)  \n\n  →  identifier?\n  id-stx : identifier?\n   intdef-ctx   :   ( or/c internal-definition-context?\n> ( listof internal-definition-context? ) )\n```\nRemoves all of the scopes of intdef-ctx (or of each element in a list intdef-ctx) from id-stx.\nThe identifier-remove-from-definition-context function is provided for backward compatibility; the internal-definition-context-splice-binding-identifier function is preferred.\nChanged in version 6.3 of package base: Simplified the operation to scope removal.\n>
\n

value

\n

prop:expansion-contexts : struct-type-property?

"} {"text": "# 12.2 Syntax Object Content\nA structure type property to constrain the use of macro transformers and rename transformers. The property’s value must be a list of symbols, where the allowed symbols are 'expression, 'top-level, 'module, 'module-begin, and 'definition-context. Each symbol corresponds to an expansion context in the same way as for local-expand or as reported by syntax-local-context, except that 'definition-context is used (instead of a list) to represent an internal-definition context.\nIf an identifier is bound to a transformer whose list does not include a symbol for a particular use of the identifier, then the use is adjusted as follows:\n- In a 'module-begin context, then the use is wrapped in a begin form.\n- In a 'module, 'top-level, 'internal-definition or context, if 'expression is present in the list, then the use is wrapped in an #%expression form.\n- Otherwise, a syntax error is reported.\nThe prop:expansion-contexts property is most useful in combination with prop:rename-transformer, since a general transformer procedure can use syntax-local-context. Furthermore, a prop:expansion-contexts property makes the most sense when a rename transformer’s identifier has the 'not-free-identifier=? property, otherwise a definition of the binding creates a binding alias that effectively routes around the prop:expansion-contexts property.\nAdded in version 6.3 of package base.\n> ```\n(syntax-local-value id-stx\n   [ failure-thunk        \n    intdef-ctx)   →   any"} {"text": "# 12.2 Syntax Object Content\n  id-stx : identifier?\n  failure-thunk : (or/c ( →  any) #f) = #f\n   intdef-ctx   :   ( or/c internal-definition-context?\n> #f\n> ( listof internal-definition-context? ) )   =   #f```\nReturns the [transformer](syntax-model.html#%28tech._transformer%29) binding value of the identifier id-stx in the context of the current expansion. If intdef-ctx is not #f, bindings from all provided definition contexts are also considered. Unlike the fourth argument to [local-expand](#%28def._%28%28quote._~23~25kernel%29._local-expand%29%29), the [scopes](syntax-model.html#%28tech._scope%29) associated with the provided definition contexts are not used to enrich id-stx’s [lexical information](syntax-model.html#%28tech._lexical._information%29).\nIf id-stx is bound to a [rename transformer](syntax-model.html#%28tech._rename._transformer%29) created with [make-rename-transformer](#%28def._%28%28quote._~23~25kernel%29._make-rename-transformer%29%29), [syntax-local-value](#%28def._%28%28quote._~23~25kernel%29._syntax-local-value%29%29) effectively calls itself with the target of the rename and returns that result, instead of the [rename transformer](syntax-model.html#%28tech._rename._transformer%29)."} {"text": "# 12.2 Syntax Object Content\nIf id-stx has no [transformer](syntax-model.html#%28tech._transformer%29) binding (via [define-syntax](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29), [let-syntax](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let-syntax%29%29), etc.) in that environment, the result is obtained by applying failure-thunk if not #f. If failure-thunk is [false](booleans.html#%28def._%28%28lib._racket%2Fbool..rkt%29._false%29%29), the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nThis procedure must be called during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander or while a module is [visit](syntax-model.html#%28tech._visit%29)ed (see [syntax-transforming?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nExamples:\n> ```racket\n> > ( define-syntax swiss-cheeses? #t )\n> > ( define-syntax ( transformer stx ) ( if ( syntax-local-value #' swiss-cheeses? ) #' ' ( gruyère emmental raclette ) #' ' ( roquefort camembert boursin ) ) )\n> > ( transformer )\n> '(gruyère emmental raclette)\n> ```\nExamples:\n> ```racket\n> > ( define-syntax ( transformer-2 stx ) ( syntax-local-value #' something-else ( λ ( ) ( error \"no binding\" ) ) ) )\n> > ( transformer-2 )\n> no binding\n> ```\nExamples:"} {"text": "# 12.2 Syntax Object Content\n> ```racket\n> > ( define-syntax nachos #' ( printf \"nachos~n\" ) )\n> > ( define-syntax chips ( make-rename-transformer #' nachos ) )\n> > ( define-syntax ( transformer-3 stx ) ( syntax-local-value #' chips ) )\n> > ( transformer-3 )\n> nachos\n> ```\nThis procedure’s binding is provided as [protected](modprotect.html#%28tech._protected%29) in the sense of [protect-out](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._protect-out%29%29).\nChanged in version 6.90.0.27 of package base: Changed intdef-ctx to accept a list of internal-definition contexts in addition to a single internal-definition context or #f. \nChanged in version 8.2.0.4: Changed binding to [protected](modprotect.html#%28tech._protected%29).\n> ```\n(syntax-local-value/immediate id-stx\n   [ failure-thunk        \n    intdef-ctx)   →   any\n  id-stx : syntax?\n  failure-thunk : (or/c ( →  any) #f) = #f\n   intdef-ctx   :   ( or/c internal-definition-context?\n> #f\n> ( listof internal-definition-context? ) )   =   #f"} {"text": "# 12.2 Syntax Object Content\n```\nLike syntax-local-value, but the result is normally two values. If id-stx is bound to a rename transformer, the results are the rename transformer and the identifier in the transformer. Beware that provide on an id bound to a rename transformer may export the target of the rename instead of id. See make-rename-transformer for more information. If id-stx is not bound to a rename transformer, then the results are the value that syntax-local-value would produce and #f.\n\nIf id-stx has no transformer binding, then failure-thunk is called (and it can return any number of values), or an exception is raised if failure-thunk is #f.\n\nExamples:\n\n> ```racket\n> > ( define-syntax agent-007 ( make-rename-transformer #' james-bond ) )\n> > ( define-syntax ( show-secret-identity stx ) ( syntax-parse stx [ ( _ name:id ) ( define-values [ _ orig-name ] ( syntax-local-value/immediate #' name ) ) #` ' ( name #, orig-name ) ] ) )\n> > ( show-secret-identity agent-007 )\n> '(agent-007 james-bond)\n> ```\n\nThis procedure’s binding is provided as protected in the sense of protect-out.\n\nChanged in version 8.2.0.4 of package base: Changed binding to protected.\n\n> ```\n(syntax-local-lift-expression stx) → identifier?\n  stx : syntax?```\n\n\nReturns a fresh identifier, and cooperates with the [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29), [letrec-syntaxes+values](let.html#%28form._%28%28quote._~23~25kernel%29._letrec-syntaxes%2Bvalues%29%29), [define-syntaxes](define.html#%28form._%28%28quote._~23~25kernel%29._define-syntaxes%29%29), [begin-for-syntax](begin.html#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29), and top-level expanders to bind the generated identifier to the expression stx.\n\nA run-time expression within a module is lifted to the module’s top level, just before the expression whose expansion requests the lift. Similarly, a run-time expression outside of a module is lifted to a top-level definition. A compile-time expression in a [letrec-syntaxes+values](let.html#%28form._%28%28quote._~23~25kernel%29._letrec-syntaxes%2Bvalues%29%29) or [define-syntaxes](define.html#%28form._%28%28quote._~23~25kernel%29._define-syntaxes%29%29) binding is lifted to a [let](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%29%29) wrapper around the corresponding right-hand side of the binding. A compile-time expression within [begin-for-syntax](begin.html#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29) is lifted to a [define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) declaration just before the requesting expression within the [begin-for-syntax](begin.html#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29).\n\nOther syntactic forms can capture lifts by using [local-expand/capture-lifts](#%28def._%28%28quote._~23~25kernel%29._local-expand%2Fcapture-lifts%29%29) or [local-transformer-expand/capture-lifts](#%28def._%28%28quote._~23~25kernel%29._local-transformer-expand%2Fcapture-lifts%29%29).\n\nThis procedure must be called during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander or while a module is [visit](syntax-model.html#%28tech._visit%29)ed (see [syntax-transforming?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nIn addition, this procedure can be called only when a lift target is available, as indicated by [syntax-transforming-with-lifts?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming-with-lifts~3f%29%29).\n\n> ```\n(syntax-local-lift-values-expression n stx)\n  →  (listof identifier?)\n  n : exact-nonnegative-integer?\n  stx : syntax?\n```"} {"text": "# 12.2 Syntax Object Content\nLike syntax-local-lift-expression, but binds the result to n identifiers, and returns a list of the n identifiers.\nThis procedure must be called during the dynamic extent of a syntax transformer application by the expander or while a module is visited (see syntax-transforming?), otherwise the exn:fail:contract exception is raised.\n> ```\n(syntax-local-lift-context)  →  any/c```\nReturns a value that represents the target for expressions lifted via [syntax-local-lift-expression](#%28def._%28%28quote._~23~25kernel%29._syntax-local-lift-expression%29%29). That is, for different transformer calls for which this procedure returns the same value (as determined by [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)), lifted expressions for the two transformer are moved to the same place. Thus, the result is useful for caching lift information to avoid redundant lifts.\nThis procedure must be called during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander or while a module is [visit](syntax-model.html#%28tech._visit%29)ed (see [syntax-transforming?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n> ```\n(parameter)\t→"} {"text": "# 12.2 Syntax Object Content\n```\n(parameter)\t→```\n\n\nCooperates with the [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) form to insert stx as a top-level declaration at the end of the module currently being expanded. If the current expression being transformed is in [phase level](syntax-model.html#%28tech._phase._level%29) 0 and not in the module top-level, then stx is eventually expanded in an expression context. If the current expression being transformed is in a higher [phase level](syntax-model.html#%28tech._phase._level%29) (i.e., nested within some number of [begin-for-syntax](begin.html#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29)es within a module top-level), then the lifted declaration is placed at the very end of the module (under a suitable number of [begin-for-syntax](begin.html#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29)es), instead of merely the end of the enclosing [begin-for-syntax](begin.html#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29).\n\nThis procedure must be called during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander or while a module is [visit](syntax-model.html#%28tech._visit%29)ed (see [syntax-transforming?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nIf the current expression being transformed is not within a [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) form (see [syntax-transforming-module-expression?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming-module-expression~3f%29%29)), then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\n> ```\n(syntax-local-lift-require raw-require-spec\n    stx        \n   [ new-scope?)   →   syntax?\n\n  raw-require-spec : any/c\n  stx : syntax?\n  new-scope? : any/c = #t\n```"} {"text": "# 12.2 Syntax Object Content\n(parameter)\t→```\nLifts a [#%provide](require.html#%28form._%28%28quote._~23~25kernel%29._~23~25provide%29%29) form corresponding to raw-provide-spec-stx to the top of the module currently being expanded or to an enclosing [begin-for-syntax](begin.html#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29).\nThis procedure must be called during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander or while a module is [visit](syntax-model.html#%28tech._visit%29)ed (see [syntax-transforming?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nIf the current expression being transformed is not within a [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) form (see [syntax-transforming-module-expression?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming-module-expression~3f%29%29)), then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n> ```\n(syntax-local-name)  →  any/c"} {"text": "# 12.2 Syntax Object Content\n```\nReturns an inferred name for the expression position being transformed, or #f if no such name is available. A name is normally a symbol or an identifier. See also Inferred Value Names.\n\nThis procedure must be called during the dynamic extent of a syntax transformer application by the expander or while a module is visited (see syntax-transforming?), otherwise the exn:fail:contract exception is raised.\n\n> ```\n(syntax-local-context)\n  →  (or/c 'expression 'top-level 'module 'module-begin list?)```\n\n\nReturns an indication of the context for expansion that triggered a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) call. See [Expansion Context](syntax-model.html#%28part._expand-context-model%29) for more information on contexts.\n\nThe symbol results indicate that the expression is being expanded for an [expression context](syntax-model.html#%28tech._expression._context%29), a [top-level context](syntax-model.html#%28tech._top._level._context%29), a [module context](syntax-model.html#%28tech._module._context%29), or a [module-begin context](syntax-model.html#%28tech._module._begin._context%29).\n\nA list result indicates expansion in an [internal-definition context](syntax-model.html#%28tech._internal._definition._context%29). The identity of the list’s first element (i.e., its [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)ness) reflects the identity of the internal-definition context; in particular two transformer expansions receive the same first value if and only if they are invoked for the same [internal-definition context](syntax-model.html#%28tech._internal._definition._context%29). Later values in the list similarly identify [internal-definition contexts](syntax-model.html#%28tech._internal._definition._context%29) that are still being expanded, and that required the expansion of nested internal-definition contexts.\n\nThis procedure must be called during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander or while a module is [visit](syntax-model.html#%28tech._visit%29)ed (see [syntax-transforming?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\n> ```\n(syntax-local-phase-level)  →  exact-integer?\n```"} {"text": "# 12.2 Syntax Object Content\n(parameter)\t→\t\n(-> listof (cons/c phase+space? (listof symbol?)))```\nReturns an association list from [phase level](syntax-model.html#%28tech._phase._level%29) and [binding space](syntax-model.html#%28tech._binding._space%29) combinations to lists of symbols, where the symbols are the names of [provide](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29)d bindings from mod-path at the corresponding [phase level](syntax-model.html#%28tech._phase._level%29).\nThis procedure must be called during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander or while a module is [visit](syntax-model.html#%28tech._visit%29)ed (see [syntax-transforming?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nChanged in version 8.2.0.3 of package base: Generalized result to phase–space combinations.\n> ```\n(syntax-local-submodules)\t→\t\n(-> listof symbol?)"} {"text": "# 12.2 Syntax Object Content\n```\n(syntax-local-module-interned-scope-symbols)\t→\t\n(-> listof symbol?)```\n\n\nReturns a list of distinct [interned](reader.html#%28tech._interned%29) symbols corresponding to [binding spaces](syntax-model.html#%28tech._binding._space%29) that have been used, so far, for binding within the current expansion context’s module or top-level namespace. The result is conservative in the sense that it may include additional symbols that have not been used in the current module or namespace.\n\nThe current implementation returns all symbols for [reachable](eval-model.html#%28tech._reachable%29) interned scopes, but that behavior may change in the future to return a less conservative list of symbols.\n\nThis procedure must be called during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander or while a module is [visit](syntax-model.html#%28tech._visit%29)ed (see [syntax-transforming?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nAdded in version 8.2.0.7 of package base.\n\n> ```\n(syntax-local-get-shadower id-stx\n   [ only-generated?)   →   identifier?\n\n  id-stx : identifier?\n  only-generated? : any/c = #f\n```\n(parameter)\t→```\nFor (limited) backward compatibility only; raises [exn:fail:unsupported](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aunsupported%29%29)."} {"text": "# 12.2 Syntax Object Content\nChanged in version 6.3 of package base: changed to raise exn:fail:supported.\n> ```\n(syntax-local-certifier [active?)\n  →   ( ( syntax? ) ( any/c ( or/c procedure? #f ) )\n> . → * . syntax? )\n  active? : boolean? = #f\n```\nFor backward compatibility only; returns a procedure that returns its first argument.\n\n> ```\n(syntax-transforming?)  →  boolean?```\n\n\nReturns #t during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander and while a module is being [visit](syntax-model.html#%28tech._visit%29)ed, #f otherwise.\n\n> ```\n(syntax-transforming-with-lifts?)  →  boolean?\n```\nReturns #t if (syntax-transforming?) produces #t and a target context is available for lifting expressions (via syntax-local-lift-expression), #f otherwise.\nCurrently, (syntax-transforming?) implies (syntax-transforming-with-lifts?).\nAdded in version 6.3.0.9 of package base.\n> ```\n(syntax-transforming-module-expression?)  →  boolean?```\nReturns #t during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander for an expression within a [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) form, #f otherwise.\n> ```\n(syntax-local-compiling-module?)  →  boolean?"} {"text": "# 12.2 Syntax Object Content\n```\nReturns #t during the dynamic extent of a syntax transformer application by the expander in a module-begin context and when the expansion is part of a compilation process where a compiled module can be returned directly. See also module.\n\nAdded in version 8.13.0.7 of package base.\n\n> ```\n(syntax-local-identifier-as-binding id-stx\n   [ intdef-ctx)   →   identifier?\n\n  id-stx : identifier?\n  intdef-ctx : (or/c internal-definition-context? #f) = #f```\n\n\nReturns an identifier like id-stx, but without [use-site scopes](syntax-model.html#%28tech._use._site._scope%29) that were previously added to the identifier as part of a macro expansion. When the intdef-ctx is an internal-definition context, the function removes use-site scopes created during expansion in that context. When it is #f (the default), it removes use-site scopes created during expansion in the current expansion context.\n\nIn a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) that runs in a non-expression context and forces the expansion of subforms with [local-expand](#%28def._%28%28quote._~23~25kernel%29._local-expand%29%29), use [syntax-local-identifier-as-binding](#%28def._%28%28quote._~23~25kernel%29._syntax-local-identifier-as-binding%29%29) on an identifier from the expansion before moving it into a binding position or comparing it with [bound-identifier=?](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._bound-identifier~3d~3f%29%29). Otherwise, the results can be inconsistent with the way that [define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) works in the same definition context.\n\nThis procedure must be called during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander or while a module is [visit](syntax-model.html#%28tech._visit%29)ed (see [syntax-transforming?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nAdded in version 6.3 of package base. \nChanged in version 8.2.0.7: Added the optional intdef-ctx argument.\n\n> ```\n(syntax-local-introduce stx)  →  syntax?\n  stx : syntax?\n```"} {"text": "# 12.2 Syntax Object Content\nProduces a syntax object that is like stx, except that the presence of scopes for the current expansion—both the macro-introduction scope and the use-site scope, if any—is flipped on all parts of the syntax object. See Transformer Bindings for information on macro-introduction and use-site scopes.\nThis procedure must be called during the dynamic extent of a syntax transformer application by the expander or while a module is visited (see syntax-transforming?), otherwise the exn:fail:contract exception is raised.\nExample:\n> ```racket\n> > ( module example racket ( define-syntax ( require-math stx ) ( syntax-local-introduce #' ( require racket/math ) ) ) ( require-math ) pi )\n> ```\n> ```\n(make-syntax-introducer [as-use-site?)\n  →  ((syntax?) ((or/c 'flip 'add 'remove)) . → * . syntax?)\n  as-use-site? : any/c = #f```\nProduces a procedure that encapsulates a fresh [scope](syntax-model.html#%28tech._scope%29) and flips, adds, or removes it in a given syntax object. By default, the fresh scope is a [macro-introduction scope](syntax-model.html#%28tech._macro._introduction._scope%29), but providing a true value for as-use-site? creates a scope that is like a [use-site scope](syntax-model.html#%28tech._use._site._scope%29); the difference is in how the scopes are treated by [syntax-original?](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-original~3f%29%29)."} {"text": "# 12.2 Syntax Object Content\nThe action of the generated procedure can be 'flip (the default) to flip the presence of a scope in each part of a given syntax object, 'add to add the scope to each regardless of whether it is present already, or 'remove to remove the scope when it is currently present in any part.\nMultiple applications of the same [make-syntax-introducer](#%28def._%28%28quote._~23~25kernel%29._make-syntax-introducer%29%29) result procedure use the same scope, and different result procedures use distinct scopes.\nChanged in version 6.3 of package base: Added the optional as-use-site? argument, and added the optional operation argument in the result procedure.\n> ```\n(parameter)\t→\t\n(-> (syntax?) ((or/c 'flip 'add 'remove)) . → * . syntax?)"} {"text": "# 12.2 Syntax Object Content\n```\nLike make-syntax-introducer, but the encapsulated scope is an interned scope. Multiple calls to make-interned-syntax-introducer with the same key will produce procedures that flip, add, or remove the same scope, even across phases and module instantiations. Furthermore, the scope remains consistent even when embedded in compiled code, so a scope created with make-interned-syntax-introducer will retain its identity in syntax objects loaded from compiled code. (In this sense, the relationship between make-syntax-introducer and make-interned-syntax-introducer is analogous to the relationship between gensym and quote.)\n\nThis function is intended for the implementation of separate binding spaces within a single phase, for which the scope associated with each environment must be the same across modules.\n\nUnlike make-syntax-introducer, the scope added by a procedure created with make-interned-syntax-introducer is always treated like a use-site scope, not a macro-introduction scope, so it does not affect originalness as reported by syntax-original?.\n\nAdded in version 6.90.0.28 of package base. \nChanged in version 8.2.0.4: Added the constraint that key is interned.\n\n> ```\n(make-syntax-delta-introducer ext-stx\n    base-stx  \n   [ phase-level)  \n\n  →  ((syntax?) ((or/c 'flip 'add 'remove)) . → * . syntax?)\n  ext-stx : identifier?\n  base-stx : (or/c syntax? #f)\n   phase-level   :   (or/c #f exact-integer?)\n      =   (syntax-local-phase-level)```\n\n\nProduces a procedure that behaves like the result of [make-syntax-introducer](#%28def._%28%28quote._~23~25kernel%29._make-syntax-introducer%29%29), but using a set of [scopes](syntax-model.html#%28tech._scope%29) from ext-stx and with a default action of 'add.\n\n- If the scopes of base-stx are a subset of the scopes of ext-stx, then the result of [make-syntax-delta-introducer](#%28def._%28%28quote._~23~25kernel%29._make-syntax-delta-introducer%29%29) adds, removes, or flips scopes that are in the set for ext-stx and not in the set for base-stx.\n\n- If the scopes of base-stx are not a subset of the scopes of ext-stx, but if it has a binding, then the set of scopes associated with the binding id subtracted from the set of scopes for ext-stx, and the result of [make-syntax-delta-introducer](#%28def._%28%28quote._~23~25kernel%29._make-syntax-delta-introducer%29%29) adds, removes, or flips that difference.\n\nA #f value for base-stx is equivalent to a syntax object with no [scopes](syntax-model.html#%28tech._scope%29).\n\nThis procedure is potentially useful when some m-id has a transformer binding that records some orig-id, and a use of m-id introduces a binding of orig-id. In that case, the [scopes](syntax-model.html#%28tech._scope%29) one the use of m-id added since the binding of m-id should be transferred to the binding instance of orig-id, so that it captures uses with the same lexical context as the use of m-id.\n\nIf ext-stx is [tainted](stxcerts.html#%28tech._tainted%29), then an identifier result from the created procedure is [tainted](stxcerts.html#%28tech._tainted%29).\n\n> ```\n(syntax-local-transforming-module-provides?)  →  boolean?\n```"} {"text": "# 12.2 Syntax Object Content\nReturns #t while a provide transformer is running (see make-provide-transformer) or while an expand sub-form of #%provide is expanded, #f otherwise.\n> ```\n(syntax-local-module-defined-identifiers)\n  →  (and/c hash? immutable?)```\nCan be called only while [syntax-local-transforming-module-provides?](#%28def._%28%28quote._~23~25kernel%29._syntax-local-transforming-module-provides~3f%29%29) returns #t.\nIt returns a hash table mapping a [phase-level](syntax-model.html#%28tech._phase._level%29) number (such as 0) to a list of all definitions at that [phase level](syntax-model.html#%28tech._phase._level%29) within the module being expanded. This information is used for implementing [provide](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) sub-forms like [all-defined-out](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._all-defined-out%29%29).\nBeware that the [phase-level](syntax-model.html#%28tech._phase._level%29) keys are absolute relative to the enclosing module, and not relative to the current transformer phase level as reported by [syntax-local-phase-level](#%28def._%28%28quote._~23~25kernel%29._syntax-local-phase-level%29%29).\n> ```\n(syntax-local-module-required-identifiers   mod-path  \n    shift)  \n  →   ( or/c ( listof ( cons/c phase+space?\n> ( listof identifier? ) ) )\n> #f )\n  mod-path : (or/c module-path? #f)\n  shift : (or/c #t phase+space-shift?)"} {"text": "# 12.2 Syntax Object Content\n```\nCan be called only while syntax-local-transforming-module-provides? returns #t.\n\nIt returns an association list mapping phase level and binding space combinations to lists of identifiers. Each list of identifiers includes all bindings imported (into the module being expanded) using the module path mod-path, or all modules if mod-path is #f. The association list includes all identifiers imported with a phase level and binding space shift as represented by shift, or all shifts if shift is #t. If shift is not #t, the result can be #f if no identifiers are imported at that shift.\n\nWhen an identifier is renamed on import, the result association list includes the identifier by its internal name. Use identifier-binding to obtain more information about the identifier.\n\nBeware that the phase-level shifts are absolute relative to the enclosing module, and not relative to the current transformer phase level as reported by syntax-local-phase-level.\n\nChanged in version 8.2.0.3 of package base: Generalized shift and result to phase–space combinations.\n\n> ```\nvalue\n\nprop:liberal-define-context : struct-type-property?\n\n(liberal-define-context? v)  →  boolean?\n  v : any/c```\n\n\nAn instance of a structure type with a true value for the [prop:liberal-define-context](#%28def._%28%28quote._~23~25kernel%29._prop~3aliberal-define-context%29%29) property can be used as an element of an [internal-definition context](syntax-model.html#%28tech._internal._definition._context%29) representation in the result of [syntax-local-context](#%28def._%28%28quote._~23~25kernel%29._syntax-local-context%29%29) or the second argument of [local-expand](#%28def._%28%28quote._~23~25kernel%29._local-expand%29%29). Such a value indicates that the context supports liberal expansion of [define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29) forms into potentially multiple [define-values](define.html#%28form._%28%28quote._~23~25kernel%29._define-values%29%29) and [define-syntaxes](define.html#%28form._%28%28quote._~23~25kernel%29._define-syntaxes%29%29) forms. The 'module and 'module-body contexts implicitly allow [liberal expansion](#%28tech._liberal._expansion%29).\n\nThe [liberal-define-context?](#%28def._%28%28quote._~23~25kernel%29._liberal-define-context~3f%29%29) predicate returns #t if v is an instance of a structure with a true value for the [prop:liberal-define-context](#%28def._%28%28quote._~23~25kernel%29._prop~3aliberal-define-context%29%29) property, #f otherwise.\n\n#### 12.4.1 [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) Transformers\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/require-transform](#%28mod-path._racket%2Frequire-transform%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/require-transform](#%28mod-path._racket%2Frequire-transform%29) library, not [racket/base](index.html) or [racket](index.html).\n\nA [transformer](syntax-model.html#%28tech._transformer%29) binding whose value is a structure with the [prop:require-transformer](#%28def._%28%28lib._racket%2Frequire-transform..rkt%29._prop~3arequire-transformer%29%29) property implements a derived require-spec for [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) as a require transformer.\n\nA [require transformer](#%28tech._require._transformer%29) is called with the syntax object representing its use as a require-spec within a [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) form, and the result must be two lists: a list of [import](#%28def._%28%28lib._racket%2Frequire-transform..rkt%29._import%29%29)s and a list of [import-source](#%28def._%28%28lib._racket%2Frequire-transform..rkt%29._import-source%29%29)s.\n\nIf the derived form contains a sub-form that is a require-spec, then it can call [expand-import](#%28def._%28%28lib._racket%2Frequire-transform..rkt%29._expand-import%29%29) to transform the sub-require-spec to lists of imports and import sources.\n\nSee also [define-require-syntax](define.html#%28form._%28%28lib._racket%2Frequire-syntax..rkt%29._define-require-syntax%29%29), which supports macro-style [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) transformers.\n\n> ```\n(expand-import require-spec)\n  →   (listof import?)   (listof import-source?)\n\n  require-spec : syntax?\n```"} {"text": "# 12.2 Syntax Object Content\nExpands the given require-spec to lists of imports and import sources. The latter specifies modules to be instantiated or visited, so the modules that it represents should be a superset of the modules represented in the former list (so that a module will be instantiated or visited even if all of imports are eventually filtered from the former list).\n> ```\n(make-require-transformer proc)  →  require-transformer?\n   proc   :   ( syntax? . → . ( values\n> ( listof import? )\n> ( listof import-source? ) ) )```\nCreates a [require transformer](#%28tech._require._transformer%29) using the given procedure as the transformer. Often used in combination with [expand-import](#%28def._%28%28lib._racket%2Frequire-transform..rkt%29._expand-import%29%29).\nExamples:\n> ```racket\n> > ( require ( for-syntax racket/require-transform ) )\n> > ( define-syntax printing ( make-require-transformer ( lambda ( stx ) ( syntax-case stx ( ) [ ( _ path ) ( begin ( printf \"Importing: ~a~n\" #' path ) ( expand-import #' path ) ) ] ) ) ) )\n> > ( require ( printing racket/match ) )\n> Importing: #\n> ```\n>
\n

value

\n

[prop:require-transformer](#%28def._%28%28lib._racket%2Frequire-transform..rkt%29._prop~3arequire-transformer%29%29) : [struct-type-property?](structprops.html#%28def._%28%28quote._~23~25kernel%29._struct-type-property~3f%29%29)

"} {"text": "# 12.2 Syntax Object Content\nA property to identify [require transformers](#%28tech._require._transformer%29). The property value must be a procedure that takes the structure and returns a transformer procedure; the returned transformer procedure takes a syntax object and returns import and import-source lists.\n> ```\n(require-transformer? v)  →  boolean?\n  v : any/c\n```\n(current-require-module-path)\t→\t\n(-> or/c #f module-path-index?)\n(current-require-module-path module-path) → void?\n module-path\t:\t\n(-> or/c #f module-path-index?)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines how relative [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29)-level module paths are expanded to [#%require](require.html#%28form._%28%28quote._~23~25kernel%29._~23~25require%29%29)-level module paths by [convert-relative-module-path](#%28def._%28%28lib._racket%2Frequire-transform..rkt%29._convert-relative-module-path%29%29) (which is used implicitly by all built-in [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) sub-forms).\n\nWhen the value of [current-require-module-path](#%28def._%28%28lib._racket%2Frequire-transform..rkt%29._current-require-module-path%29%29) is #f, relative module paths are left as-is, which means that the [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) context determines the resolution of the module path.\n\nThe [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) form [parameterize](parameters.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize%29%29)s [current-require-module-path](#%28def._%28%28lib._racket%2Frequire-transform..rkt%29._current-require-module-path%29%29) as #f while invoking sub-form transformers, while [relative-in](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._relative-in%29%29) [parameterize](parameters.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize%29%29)s to a given module path.\n\n> ```\n(convert-relative-module-path module-path)\n  →   ( or/c module-path?\n> ( syntax/c module-path? ) )\n\n   module-path   :   ( or/c module-path?\n> ( syntax/c module-path? ) )\n```"} {"text": "# 12.2 Syntax Object Content\n(parameter)\t→```\nLifts top-level-stx to the top-level of the enclosing module, immediately following the [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) that is being expanded.\nThis procedure must be called during the dynamic extent of a [syntax transformer](syntax-model.html#%28tech._syntax._transformer%29) application by the expander or while a module is [visit](syntax-model.html#%28tech._visit%29)ed (see [syntax-transforming?](#%28def._%28%28quote._~23~25kernel%29._syntax-transforming~3f%29%29)), otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nIn addition, this procedure may only be called while expanding a [require transformer](#%28tech._require._transformer%29).\nAdded in version 8.12.0.13 of package base.\n> ```\n(syntax-local-require-certifier)\n  →   ( ( syntax? ) ( or/c #f ( syntax? . → . syntax? ) )\n> . → * . syntax? )"} {"text": "# 12.2 Syntax Object Content\n```\nFor backward compatibility only; returns a procedure that returns its first argument.\n\n#### 12.4.2 provide Transformers\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require racket/provide-transform) |  package: base |\n\nThe bindings documented in this section are provided by the racket/provide-transform library, not racket/base or racket.\n\nA transformer binding whose value is a structure with the prop:provide-transformer property implements a derived provide-spec for provide as a provide transformer. A provide transformer is applied as part of the last phase of a module’s expansion, after all other declarations and expressions within the module are expanded.\n\nA transformer binding whose value is a structure with the prop:provide-pre-transformer property implements a derived provide-spec for provide as a provide pre-transformer. A provide pre-transformer is applied as part of the first phase of a module’s expansion. Since it is used in the first phase, a provide pre-transformer can use functions such as syntax-local-lift-expression to introduce expressions and definitions in the enclosing module.\n\nAn identifier can have a transformer binding to a value that acts both as a provide transformer and provide pre-transformer. The result of a provide pre-transformer is not automatically re-expanded, so a provide pre-transformer can usefully expand to itself in that case.\n\nA transformer is called with the syntax object representing its use as a provide-spec within a provide form and a list of symbols representing the export modes specified by enclosing provide-specs. The result of a provide transformer must be a list of exports, while the result of a provide pre-transformer is a syntax object to be used as a provide-spec in the last phase of module expansion.\n\nIf a derived form contains a sub-form that is a provide-spec, then it can call expand-export or pre-expand-export to transform the sub-provide-spec sub-form.\n\nSee also define-provide-syntax, which supports macro-style provide transformers.\n\n> ```\n(expand-export provide-spec modes) → (listof export?)\n  provide-spec : syntax?\n  modes : (listof phase+space?)```\n\n\nExpands the given provide-spec to a list of exports. The modes list controls the expansion of sub-provide-specs; for example, an identifier refers to a binding in the [phase level](syntax-model.html#%28tech._phase._level%29) of the enclosing [provide](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) form, unless the modes list specifies otherwise. Normally, modes is either empty or contains a single element.\n\nChanged in version 8.2.0.3 of package base: Generalized modes to phase–space combinations.\n\n> ```\n(pre-expand-export provide-spec modes)  →  syntax?\n  provide-spec : syntax?\n  modes : (listof phase+space?)\n```"} {"text": "# 12.2 Syntax Object Content\nExpands the given provide-spec at the level of provide pre-transformers. The modes argument is the same as for expand-export.\nChanged in version 8.2.0.3 of package base: Generalized modes to phase–space combinations.\n> ```\n(make-provide-transformer proc)  →  provide-transformer?\n   proc   :   ( syntax? ( listof phase+space? )\n> . → . ( listof export? ) )\n(make-provide-transformer proc pre-proc)\n  →  (and/c provide-transformer? provide-pre-transformer?)\n   proc   :   ( syntax? ( listof phase+space? )\n> . → . ( listof export? ) )\n   pre-proc   :   ( syntax? ( listof phase+space? )\n> . → . syntax? )```\nCreates a [provide transformer](#%28tech._provide._transformer%29) (i.e., a structure with the [prop:provide-transformer](#%28def._%28%28lib._racket%2Fprovide-transform..rkt%29._prop~3aprovide-transformer%29%29) property) using the given procedure as the transformer. If a pre-proc is provided, then the result is also a [provide pre-transformer](#%28tech._provide._pre._transformer%29). Often used in combination with [expand-export](#%28def._%28%28lib._racket%2Fprovide-transform..rkt%29._expand-export%29%29) and/or [pre-expand-export](#%28def._%28%28lib._racket%2Fprovide-transform..rkt%29._pre-expand-export%29%29).\n> ```\n(make-provide-pre-transformer pre-proc)\n  →  provide-pre-transformer?\n   pre-proc   :   ( syntax? ( listof phase+space? )\n> . → . syntax? )"} {"text": "# 12.2 Syntax Object Content\n```\nLike make-provide-transformer, but for a value that is a provide pre-transformer, only. Often used in combination with pre-expand-export.\n\nExamples:\n\n> ```racket\n> > ( module m racket ( require ( for-syntax racket/provide-transform syntax/parse syntax/stx ) ) ( define-syntax wrapped-out ( make-provide-pre-transformer ( lambda ( stx modes ) ( syntax-parse stx [ ( _ f ... ) #:with ( wrapped-f ... ) ( stx-map syntax-local-lift-expression #' ( ( lambda args ( printf \"applying ~a, args: ~a\\n\" ' f args ) ( apply f args ) ) ... ) ) ( pre-expand-export #' ( rename-out [ wrapped-f f ] ... ) modes ) ] ) ) ) ) ( provide ( wrapped-out + - ) ) )\n> > ( require ' m )\n> > ( - 1 ( + 2 3 ) )\n> applying +, args: (2 3) applying -, args: (1 5)\n> -4\n> ```\n\n>
\n\n

value

\n\n

prop:provide-transformer : struct-type-property?

\n\nA property to identify provide transformers. The property value must be a procedure that takes the structure and returns a transformer procedure; the returned transformer procedure takes a syntax object and mode list and returns an export list.\n\n>
\n\n

value

\n\n

prop:provide-pre-transformer : struct-type-property?

\n\nA property to identify provide pre-transformers. The property value must be a procedure that takes the structure and returns a transformer procedure; the returned transformer procedure takes a syntax object and mode list and returns a syntax object.\n\n> ```\n(provide-transformer? v) → boolean?\n  v : any/c```\n\n\nReturns #t if v has the [prop:provide-transformer](#%28def._%28%28lib._racket%2Fprovide-transform..rkt%29._prop~3aprovide-transformer%29%29) property, #f otherwise.\n\n> ```\n(provide-pre-transformer? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 12.2 Syntax Object Content\n(parameter)\t→```\nComposes [syntax-e](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-e%29%29) with [export-out-id](#%28def._%28%28lib._racket%2Fprovide-transform..rkt%29._export-out-id%29%29).\nThis function is intended for backward compatibility. Use [export-out-id](#%28def._%28%28lib._racket%2Fprovide-transform..rkt%29._export-out-id%29%29) directly, instead.\nAdded in version 8.9.0.5 of package base.\n> ```\n(syntax-local-provide-certifier)\n  →   ( ( syntax? ) ( or/c #f ( syntax? . → . syntax? ) )\n> . → * . syntax? )\n```\nFor backward compatibility only; returns a procedure that returns its first argument.\n\n#### 12.4.3 Keyword-Argument Conversion Introspection\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require racket/keyword-transform) |  package: base |\n\nThe bindings documented in this section are provided by the racket/keyword-transform library, not racket/base or racket.\n\n> ```\n(syntax-procedure-alias-property stx)\n  →   ( or/c #f\n> ( letrec ( [ val? ( recursive-contract\n> ( or/c ( cons/c identifier? identifier? )\n> ( cons/c val? val? ) ) ) ] )\n> val? ) )\n\n  stx : syntax?\n\n(syntax-procedure-converted-arguments-property stx)\n  →   ( or/c #f\n> ( letrec ( [ val? ( recursive-contract\n> ( or/c ( cons/c identifier? identifier? )\n> ( cons/c val? val? ) ) ) ] )\n> val? ) )\n\n  stx : syntax?```\n\n\nReports the value of a syntax property that can be attached to an identifier by the expansion of a keyword-application form. See [lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) for more information about the property.\n\nThe property value is normally a pair consisting of the original identifier and an identifier that appears in the expansion. Property-value merging via [syntax-track-origin](stxprops.html#%28def._%28%28quote._~23~25kernel%29._syntax-track-origin%29%29) can make the value a pair of such values, and so on.\n\n#### 12.4.4 Portal Syntax Bindings\n\nAn identifier bound to portal syntax value created by [make-portal-syntax](#%28def._%28%28quote._~23~25kernel%29._make-portal-syntax%29%29) does not act as a transformer, but it encapsulates a syntax object that can be accessed and inspected even without instantiating the enclosing module. Portal syntax is also bound using the portal form of [#%require](require.html#%28form._%28%28quote._~23~25kernel%29._~23~25require%29%29).\n\n> ```\n(portal-syntax? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 12.2 Syntax Object Content\nReturns #t if v is a value created by make-portal-syntax, #f otherwise.\nAdded in version 8.3.0.8 of package base.\n> ```\n(make-portal-syntax stx)  →  portal-syntax?\n  stx : syntax?```\nCreates [portal syntax](#%28tech._portal._syntax%29) with the content stx.\nWhen [define-syntax](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-syntax%29%29) or [define-syntaxes](define.html#%28form._%28%28quote._~23~25kernel%29._define-syntaxes%29%29) binds an identifier to portal syntax immediately in a module body, then in addition to being accessible via [syntax-local-value](#%28def._%28%28quote._~23~25kernel%29._syntax-local-value%29%29) while expanding, the portal syntax content is accessible via [identifier-binding-portal-syntax](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._identifier-binding-portal-syntax%29%29).\nAdded in version 8.3.0.8 of package base.\n> ```\n(portal-syntax-content portal)  →  syntax?\n  portal : portal-syntax?"} {"text": "# 12.2 Syntax Object Content\n```\n(parameter)\t→```\n\n\nThis procedure is intended for use in a [transformer environment](syntax-model.html#%28tech._transformer._environment%29), where id-stx is an identifier bound in the normal environment to a [syntax parameter](#%28tech._syntax._parameter%29). The result is the current value of the [syntax parameter](#%28tech._syntax._parameter%29), as adjusted by [syntax-parameterize](#%28form._%28%28lib._racket%2Fstxparam..rkt%29._syntax-parameterize%29%29) form.\n\nThis binding is provided [for-syntax](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-syntax%29%29) by [racket/stxparam](), since it is normally used in a transformer. It is provided normally by [racket/stxparam-exptime](#%28mod-path._racket%2Fstxparam-exptime%29).\n\n> ```\n(parameter)\t→\n```\n(parameter)\t→\t\n(-> if preserved? (and/c symbol? symbol-interned?) any/c)```\nThe three- or four-argument form extends stx by associating an arbitrary property value v with the key key; the result is a new syntax object with the association (while stx itself is unchanged). The property is added as [preserved](#%28tech._stx._prop._preserved%29) if preserved? is true, in which case key must be an [interned](reader.html#%28tech._interned%29) symbol, and v should be a value as described below that can be saved in marshaled bytecode."} {"text": "# 12.2 Syntax Object Content\nThe two-argument form returns an arbitrary property value associated to stx with the key key, or #f if no value is associated to stx for key. If stx is [tainted](stxcerts.html#%28tech._tainted%29), then syntax objects with the result value are tainted.\nTo support marshaling to bytecode, a value for a preserved syntax property must be a non-cyclic value that is either\n- a [pair](pairs.html#%28tech._pair%29) containing allowed preserved-property values;\n- a [vector](vectors.html#%28tech._vector%29) (unmarshaled as immutable) containing allowed preserved-property values;\n- a [box](boxes.html#%28tech._box%29) (unmarshaled as immutable) containing allowed preserved-property values;\n- an immutable [prefab](structures.html#%28tech._prefab%29) structure containing allowed preserved-property values;\n- an immutable [hash table](hashtables.html#%28tech._hash._table%29) whose keys and values are allowed preserved-property values;\n- a [syntax object](syntax-model.html#%28tech._syntax._object%29); or\n- an empty list, [symbol](symbols.html#%28tech._symbol%29), [number](numbers.html#%28tech._number%29), [character](characters.html#%28tech._character%29), [string](strings.html#%28tech._string%29), [byte string](bytestrings.html#%28tech._byte._string%29), or [regexp value](regexp.html#%28tech._regexp._value%29).\nAny other value for a preserved property triggers an exception at an attempt to marshal the owning syntax object to bytecode form.\nChanged in version 6.4.0.14 of package base: Added the preserved? argument.\n> ```"} {"text": "# 12.2 Syntax Object Content\n(syntax-property-remove stx key)  →  syntax?\n  stx : syntax?\n  key : any/c\n```\n(parameter)\t→\t\n(-> and/c symbol? symbol-interned?)```\n\n\nReturns #t if stx has a [preserved](#%28tech._stx._prop._preserved%29) property value for key, #f otherwise.\n\nAdded in version 6.4.0.14 of package base.\n\n> ```\n(syntax-property-symbol-keys stx)  →  list?\n  stx : syntax?\n```\nReturns a list of all symbols that as keys have associated properties in stx. Uninterned symbols (see Symbols) are not included in the result list.\n> ```\n(syntax-track-origin   new-stx        \n    orig-stx        \n    id-stx)   →   any\n  new-stx : syntax?\n  orig-stx : syntax?\n  id-stx : identifier?```\nAdds properties to new-stx in the same way that macro expansion adds properties to a transformer result. In particular, it merges the properties of orig-stx into new-stx, first adding id-stx as an 'origin property and removing the property recognized by [syntax-original?](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-original~3f%29%29), and it returns the property-extended syntax object. Use the [syntax-track-origin](#%28def._%28%28quote._~23~25kernel%29._syntax-track-origin%29%29) procedure in a macro transformer that discards syntax (corresponding to orig-stx with a keyword id-stx) leaving some other syntax in its place (corresponding to new-stx).\nFor example, the expression\n> ([or](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29) x y)\nexpands to"} {"text": "# 12.2 Syntax Object Content\n> ([let](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%29%29) (\\[or-part x\\]) ([if](if.html#%28form._%28%28quote._~23~25kernel%29._if%29%29) or-part or-part ([or](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29) y)))\nwhich, in turn, expands to\n> ([let-values](let.html#%28form._%28%28quote._~23~25kernel%29._let-values%29%29) (\\[(or-part) x\\]) ([if](if.html#%28form._%28%28quote._~23~25kernel%29._if%29%29) or-part or-part y))\nThe syntax object for the final expression will have an 'origin property whose value is ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) ([quote-syntax](Syntax_Quoting__quote-syntax.html#%28form._%28%28quote._~23~25kernel%29._quote-syntax%29%29) [let](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%29%29)) ([quote-syntax](Syntax_Quoting__quote-syntax.html#%28form._%28%28quote._~23~25kernel%29._quote-syntax%29%29) [or](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29))).\nChanged in version 7.0 of package base: Included the [syntax-original?](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-original~3f%29%29) property among the ones transferred to new-stx. \nChanged in version 8.2.0.7: Corrected back to removing the [syntax-original?](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-original~3f%29%29) property from the set transferred to new-stx.\n------------------------------------------------------------------------"} {"text": "# 12.8 Syntax Taints"} {"text": "### 12.8 Syntax Taints\n> > > \"+\"[Tainted Syntax](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=stx-certs.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13) introduces syntax taints.\nA tainted identifier is rejected by the macro expander for use as either a binding or expression. If a syntax object stx is [tainted](#%28tech._tainted%29), then any syntax object in the result of ([syntax-e](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-e%29%29) stx) is [tainted](#%28tech._tainted%29), and [datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29) with stx as its first argument produces a [tainted](#%28tech._tainted%29) syntax object. Any syntax object in the result of ([syntax-property](stxprops.html#%28def._%28%28quote._~23~25kernel%29._syntax-property%29%29) stx key) is also tainted if it is in a position within the value that would be reached by [datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29)’s conversion. Taints cannot be removed."} {"text": "# 12.8 Syntax Taints\nA syntax object is tainted when it is included in an exception by the macro expander or when it is produced by a function like [expand](Expanding_Top-Level_Forms.html#%28def._%28%28quote._~23~25kernel%29._expand%29%29) using a [code inspector](modprotect.html#%28tech._code._inspector%29) that is not the original code inspector. The function [syntax-taint](#%28def._%28%28quote._~23~25kernel%29._syntax-taint%29%29) also returns a tainted syntax object.\nPrevious versions of Racket included a notion of arming and disarming syntax to trigger taints or avoid taints. That indirection is no longer supported, and the operations [syntax-arm](#%28def._%28%28quote._~23~25kernel%29._syntax-arm%29%29), [syntax-disarm](#%28def._%28%28quote._~23~25kernel%29._syntax-disarm%29%29), [syntax-rearm](#%28def._%28%28quote._~23~25kernel%29._syntax-rearm%29%29), and [syntax-protect](#%28def._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._syntax-protect%29%29) now have no effect on their arguments. Along similar lines, the syntax properties (see [Syntax Object Properties](stxprops.html)) 'taint-mode and 'certify-mode were formerly used to control syntax arming and are no longer specifically recognized by the macro expander.\n> ```\n(syntax-tainted? stx)  →  boolean?\n  stx : syntax?"} {"text": "# 12.8 Syntax Taints\n```\nReturns #t if stx is tainted, #f otherwise.\n\n> ```\n(syntax-arm stx [inspector use-mode?) → syntax?\n  stx : syntax?\n  inspector : (or/c inspector? #f) = #f\n  use-mode? : any/c = #f```\n\n\nReturns stx.\n\nChanged in version 8.2.0.4 of package base: Changed to just return stx instead of returning “armed” syntax.\n\n> ```\n(syntax-protect stx)  →  syntax?\n  stx : syntax?\n```\nReturns stx.\nChanged in version 8.2.0.4 of package base: Changed to just return stx instead of returning “armed” syntax.\n> ```\n(syntax-disarm stx inspector)  →  syntax?\n  stx : syntax?\n  inspector : (or/c inspector? #f)\n```\n\n\nReturns stx.\n\nChanged in version 8.2.0.4 of package base: Changed to just return stx instead of potentially “disarming” syntax.\n\n> ```\n(syntax-rearm stx from-stx [use-mode?) → syntax?\n  stx : syntax?\n  from-stx : syntax?\n  use-mode? : any/c = #f\n```\nReturns stx.\nChanged in version 8.2.0.4 of package base: Changed to just return stx instead of potentially “arming” syntax.\n> ```\n(syntax-taint stx)  →  syntax?\n  stx : syntax?\n```\n\n\nReturns [tainted](#%28tech._tainted%29) version of stx, which is stx if it is already tainted.\n\n------------------------------------------------------------------------\n\n# 12.9 Expanding Top-Level Forms\n\n### 12.9 Expanding Top-Level Forms\n\n> ```\n(current-code-inspector)\t→\t\n(-> current-code-inspector)\n```\n(current-code-inspector)\t→\t\n(-> i.e., the value of (current-code-inspector) when Racket starts)```"} {"text": "# 12.8 Syntax Taints\nLike ([expand](#%28def._%28%28quote._~23~25kernel%29._expand%29%29) stx insp), except that the argument must be a [syntax object](syntax-model.html#%28tech._syntax._object%29), and its lexical context is not enriched before expansion.\nChanged in version 8.2.0.4 of package base: Added the insp argument and tainting.\n> ```\n(current-code-inspector)\t→\t\n(-> current-code-inspector)\n```\n(current-code-inspector)\t→\t\n(-> current-code-inspector)```\n\n\nLike ([expand-once](#%28def._%28%28quote._~23~25kernel%29._expand-once%29%29) stx), except that the argument must be a [syntax object](syntax-model.html#%28tech._syntax._object%29), and its lexical context is not enriched before expansion.\n\nChanged in version 8.2.0.4 of package base: Added the insp argument and tainting.\n\n> ```\n(current-code-inspector)\t→\t\n(-> current-code-inspector)\n```\n(current-code-inspector)\t→\t\n(-> current-code-inspector)```\nLike ([expand-to-top-form](#%28def._%28%28quote._~23~25kernel%29._expand-to-top-form%29%29) stx), except that the argument must be a [syntax object](syntax-model.html#%28tech._syntax._object%29), and its lexical context is not enriched before expansion.\nChanged in version 8.2.0.4 of package base: Added the insp argument and tainting."} {"text": "#### 12.9.1 Information on Expanded Modules\nInformation for an expanded [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) declaration is stored in a set of [syntax properties](stxprops.html#%28tech._syntax._property%29) (see [Syntax Object Properties](stxprops.html)) attached to the syntax object:\n- 'module-body-context — a syntax object whose [lexical information](syntax-model.html#%28tech._lexical._information%29) corresponds to the inside of the module, so it includes the expansion’s [outside-edge scope](syntax-model.html#%28tech._outside._edge._scope%29) and its [inside-edge scope](syntax-model.html#%28tech._inside._edge._scope%29); that is, the syntax object simulates an identifier that is present in the original module body and inaccessible to manipulation by any macro, so that its lexical information includes bindings for the module’s imports and definitions.\n Added in version 6.4.0.1 of package base.\n- 'module-body-inside-context — a syntax object whose [lexical information](syntax-model.html#%28tech._lexical._information%29) corresponds to an identifier that starts with no lexical context and is moved into the macro, so that it includes only the expansions’s [inside-edge scope](syntax-model.html#%28tech._inside._edge._scope%29).\n Added in version 6.4.0.1 of package base."} {"text": "# 12.8 Syntax Taints\n- 'module-body-context-simple? — a boolean, where #t indicates that the bindings of the module’s body (as recorded in the [lexical information](syntax-model.html#%28tech._lexical._information%29) of the value of the 'module-body-inside-context property) can be directly reconstructed from modules directly imported into the module, including imported for-syntax, for-meta, and for-template.\n Added in version 6.4.0.1 of package base.\nChanged in version 7.0 of package base: Removed 'module-variable-provides, 'module-syntax-provides, 'module-indirect-provides, and 'module-indirect-for-meta-provides properties.\n------------------------------------------------------------------------"} {"text": "# 12.10 Serializing Syntax"} {"text": "### 12.10 Serializing Syntax\n> ```\n(current-namespace)\t→\t\n(-> listof symbol?)\n```\nConverts stx to a serialized form that is suitable for use with s-exp → fasl or serialize. Although stx could be serialized with (compile \\`(quote-syntax ,stx)) and then writing the compiled form, syntax-serialize provides more control over serialization:\n\n- The preserve-property-keys lists syntax-property keys to whose values should be preserved in serialization, even if the property value was not added as preserved with syntax-property (so it would be discarded in compiled form). The values associated with the properties to preserve must be serializable in the sense required by syntax-property for a preserved property.\n\n- The provides-namespace argument constrains how much the serialized syntax object can rely on bulk bindings, which are shared binding tables provided by exporting modules. If provides-namespace is #f, then complete binding information is recorded in the syntax object’s serialized form, and no bulk bindings will be needed from the namespace at deserialization. Otherwise, bulk bindings will be used only for modules declared in provides-namespace (i.e., the deserialize-time namespace will have the same module declarations as provides-namespace); note that supplying a namespace with no module bindings is equivalent to supplying #f.\n\n- The base-module-path-index argument specifies a module path index to which binding information in stx is relative. For example, if a syntax object originates from quote-syntax in the body of a module, then base-module-path-index could usefully be the enclosing module’s module path index as produced by (variable-reference → module-path-index (#%variable-reference)) within the module. On deserialization, a different module path index can be supplied to substitute in place of base-module-path-index, which shifts any binding that is relative to the serialize-time module’s identity to be relative to the module identity supplied at deserialize time. If base-module-path-index is #f, then no shifting is supported at deserialize time, and any base-module-path-index supplied at that time is ignored.\n\nA serialized syntax object is otherwise similar to compiled code: it is version-specific, and deserialization will require a sufficiently powerful code inspector.\n\nAdded in version 8.0.0.13 of package base.\n\n> ```\n(syntax-deserialize\n    v  \n   [ #:base-module-path-index base-module-path-index)  \n\n  →  syntax?\n  v : any/c\n  base-module-path-index : (or/c module-path-index? #f) = #f```\n\n\nConverts the result of [syntax-serialize](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._syntax-serialize%29%29) back to a syntax object. See [syntax-serialize](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._syntax-serialize%29%29) for more information.\n\nAdded in version 8.0.0.13 of package base.\n\n------------------------------------------------------------------------\n\n# 12.11 File Inclusion\n\n### 12.11 File Inclusion\n\n| | |\n|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/include]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/include]() and [racket](index.html) libraries, but not [racket/base](index.html).\n\n>
\n\n

syntax

\n\n

([include](#%28form._%28%28lib._racket%2Finclude..rkt%29._include%29%29) path-spec)

 
path-spec = string
  | ([file](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._file%29%29) string)
  | ([lib](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lib%29%29) string ...+)
\n\nInlines the syntax in the file designated by path-spec in place of the [include](#%28form._%28%28lib._racket%2Finclude..rkt%29._include%29%29) expression.\n\nA path-spec resembles a subset of the mod-path forms for [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29), but it specifies a file whose content need not be a module. That is, string refers to a file using a platform-independent relative path, ([file](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._file%29%29) string) refers to a file using platform-specific notation, and ([lib](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lib%29%29) string [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) refers to a file within a collection.\n\nIf path-spec specifies a relative path, the path is resolved relative to the source for the [include](#%28form._%28%28lib._racket%2Finclude..rkt%29._include%29%29) expression, if that source is a complete path string. If the source is not a complete path string, then path-spec is resolved relative to ([current-load-relative-directory](eval.html#%28def._%28%28quote._~23~25kernel%29._current-load-relative-directory%29%29)) if it is not #f, or relative to ([current-directory](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29)) otherwise.\n\nThe included syntax is given the lexical context of the [include](#%28form._%28%28lib._racket%2Finclude..rkt%29._include%29%29) expression, while the included syntax’s source location refers to its actual source.\n\n>
\n\n

syntax

\n\n

([include-at/relative-to](#%28form._%28%28lib._racket%2Finclude..rkt%29._include-at%2Frelative-to%29%29) context source path-spec)

\n\nLike [include](#%28form._%28%28lib._racket%2Finclude..rkt%29._include%29%29), except that the lexical context of context is used for the included syntax, and a relative path-spec is resolved with respect to the source of source. The context and source elements are otherwise discarded by expansion.\n\n>
\n\n

syntax

\n\n

([include/reader](#%28form._%28%28lib._racket%2Finclude..rkt%29._include%2Freader%29%29) path-spec reader-expr)

\n\nLike [include](#%28form._%28%28lib._racket%2Finclude..rkt%29._include%29%29), except that the procedure produced by the expression reader-expr is used to read the included file, instead of [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29).\n\nThe reader-expr is evaluated at expansion time in the [transformer environment](syntax-model.html#%28tech._transformer._environment%29). Since it serves as a replacement for [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29), the expression’s value should be a procedure that consumes two inputs—a string representing the source and an input port—and produces a syntax object or [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29). The procedure will be called repeatedly until it produces [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29).\n\nThe syntax objects returned by the procedure should have source location information, but usually no lexical context; any lexical context in the syntax objects will be ignored.\n\n>
\n\n

syntax

\n\n

([include-at/relative-to/reader](#%28form._%28%28lib._racket%2Finclude..rkt%29._include-at%2Frelative-to%2Freader%29%29) context source path-spec reader-expr)

\n\nCombines [include-at/relative-to](#%28form._%28%28lib._racket%2Finclude..rkt%29._include-at%2Frelative-to%29%29) and [include/reader](#%28form._%28%28lib._racket%2Finclude..rkt%29._include%2Freader%29%29).\n\n------------------------------------------------------------------------\n\n# 12.12 Syntax Utilities\n\n### 12.12 Syntax Utilities\n\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/syntax]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/syntax]() library, not [racket/base](index.html) or [racket](index.html).\n\n#### 12.12.1 Creating formatted identifiers\n\n> ```\n(parameter)\t→\t\n(-> or/c syntax? #f)\n```"} {"text": "# 12.10 Serializing Syntax\n(parameter)\t→\t\n(-> e.g., identifiers will be automatically converted to symbols)```\nLike [format](Writing.html#%28def._%28%28quote._~23~25kernel%29._format%29%29), but produces a symbol. The format string must use only \\~a placeholders. Syntax objects in the argument list are automatically unwrapped (e.g., identifiers will be automatically converted to symbols).\nExample:\n> ```racket\n> > ( format-symbol \"make-~a\" ' triple )\n> 'make-triple\n> ```\nChanged in version 8.7.0.7 of package base: Allowed v to be a syntax object wrapping a string, a keyword, a character, or a number."} {"text": "#### 12.12.2 Pattern variables\n>
\n

syntax

\n

([define/with-syntax](#%28form._%28%28lib._racket%2Fsyntax..rkt%29._define%2Fwith-syntax%29%29) pattern stx-expr)

 
  stx-expr : [syntax?](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax~3f%29%29)
\nDefinition form of [with-syntax](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._with-syntax%29%29). That is, it matches the syntax object result of stx-expr against pattern and creates pattern variable definitions for the pattern variables of pattern.\nExamples:\n> ```racket\n> > ( define/with-syntax ( px ... ) #' ( a b c ) )\n> > ( define/with-syntax ( tmp ... ) ( generate-temporaries #' ( px ... ) ) )\n> > #' ( [ tmp px ] ... )\n> #\n> > ( define/with-syntax name #' Alice )\n> > #' ( hello name )\n> #\n> ```"} {"text": "#### 12.12.3 Error reporting\n> ```\n(current-syntax-context)\t→\t\n(-> or/c syntax? #f)\n(current-syntax-context stx) → void?\n stx\t:\t\n(-> or/c syntax? #f)\n```\nThe current contextual syntax object, defaulting to #f. It determines the special form name that prefixes syntax errors created by wrong-syntax.\n\n> ```\n(wrong-syntax stx format-string v ...) → any\n  stx : syntax?\n  format-string : string?\n  v : any/c```\n\n\nRaises a syntax error using the result of ([current-syntax-context](#%28def._%28%28lib._racket%2Fsyntax..rkt%29._current-syntax-context%29%29)) as the “major” syntax object and the provided stx as the specific syntax object. (The latter, stx, is usually the one highlighted by DrRacket.) The error message is constructed using the format string and arguments, and it is prefixed with the special form name as described under [current-syntax-context](#%28def._%28%28lib._racket%2Fsyntax..rkt%29._current-syntax-context%29%29).\n\nExamples:\n\n> ```racket\n> > ( wrong-syntax #' here \"expected ~s\" ' there )\n> eval:15:0: ?: expected there\n> at: here\n> > ( parameterize ( [ current-syntax-context #' ( look over here ) ] ) ( wrong-syntax #' here \"expected ~s\" ' there ) )\n> eval:16:0: look: expected there\n> at: here\n> in: (look over here)\n> ```\n\nA macro using [wrong-syntax](#%28def._%28%28lib._racket%2Fsyntax..rkt%29._wrong-syntax%29%29) might set the syntax context at the very beginning of its transformation as follows:\n\n> ```racket\n> ( define-syntax ( my-macro stx )\n> ( parameterize ( [ current-syntax-context stx ] )\n> ( syntax-case stx ( )\n> __ ) ) )\n> ```\n\nThen any calls to [wrong-syntax](#%28def._%28%28lib._racket%2Fsyntax..rkt%29._wrong-syntax%29%29) during the macro’s transformation will refer to my-macro (more precisely, the name that referred to my-macro where the macro was used, which may be different due to renaming, prefixing, etc).\n\n#### 12.12.4 Recording disappeared uses\n\n> ```\n(current-recorded-disappeared-uses)\t→\t\n(-> or/c (listof identifier?) #f)\n(current-recorded-disappeared-uses ids) → void?\n ids\t:\t\n(-> or/c (listof identifier?) #f)\n```"} {"text": "# 12.10 Serializing Syntax\nParameter for tracking disappeared uses. Tracking is “enabled” when the parameter has a non-false value. This is done automatically by forms like with-disappeared-uses.\n>
\n

syntax

\n

(with-disappeared-uses body-expr ... stx-expr)

 
  stx-expr : syntax?
\nEvaluates the body-exprs and stx-expr, catching identifiers looked up using syntax-local-value/record. Adds the caught identifiers to the 'disappeared-use syntax property of the syntax object produced by stx-expr.\nChanged in version 6.5.0.7 of package base: Added the option to include body-exprs.\n> ```\n(syntax-local-value/record id predicate) → any/c\n  id : identifier?\n  predicate : ( →  any/c boolean?)```\nLooks up id in the syntactic environment (as [syntax-local-value](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._syntax-local-value%29%29)). If the lookup succeeds and returns a value satisfying the predicate, the value is returned and id is recorded as a disappeared use by calling [record-disappeared-uses](#%28def._%28%28lib._racket%2Fsyntax..rkt%29._record-disappeared-uses%29%29). If the lookup fails or if the value does not satisfy the predicate, #f is returned and the identifier is not recorded as a disappeared use.\n> ```"} {"text": "# 12.10 Serializing Syntax\n(parameter)\t→\t\n(-> or/c identifier? (listof identifier?))\n```\n(current-recorded-disappeared-uses)\t→```\n\n\nGenerates one fresh identifier. Singular form of [generate-temporaries](stxops.html#%28def._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._generate-temporaries%29%29). If name-base is supplied, it is used as the basis for the identifier’s name.\n\n> ```\n(internal-definition-context-apply   intdef-ctx        \n    stx)   →   syntax?\n\n  intdef-ctx : internal-definition-context?\n  stx : syntax?\n```\nEquivalent to (internal-definition-context-introduce intdef-ctx stx 'add). The internal-definition-context-apply function is provided for backwards compatibility; the internal-definition-context-add-scopes function is preferred.\n> ```\n(syntax-local-eval stx [intdef-ctx) → any\n  stx : any/c\n   intdef-ctx   :   ( or/c internal-definition-context?\n> #f\n> ( listof internal-definition-context? ) )\n      =   '()```\nEvaluates stx as an expression in the current [transformer environment](syntax-model.html#%28tech._transformer._environment%29) (that is, at [phase level](syntax-model.html#%28tech._phase._level%29) 1). If intdef-ctx is not #f, the value provided for intdef-ctx is used to enrich stx’s [lexical information](syntax-model.html#%28tech._lexical._information%29) and extend the [local binding context](syntax-model.html#%28tech._local._binding._context%29) in the same way as the fourth argument to [local-expand](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._local-expand%29%29).\nExamples:"} {"text": "# 12.10 Serializing Syntax\n> ```racket\n> > ( define-syntax ( show-me stx ) ( syntax-case stx ( ) [ ( show-me expr ) ( begin ( printf \"at compile time produces ~s\\n\" ( syntax-local-eval #' expr ) ) #' ( printf \"at run time produces ~s\\n\" expr ) ) ] ) )\n> > ( show-me ( + 2 5 ) )\n> at compile time produces 7 at run time produces 7\n> > ( define-for-syntax fruit ' apple )\n> > ( define fruit ' pear )\n> > ( show-me fruit )\n> at compile time produces apple at run time produces pear\n> ```\nChanged in version 6.90.0.27 of package base: Changed intdef-ctx to accept a list of internal-definition contexts in addition to a single internal-definition context or #f.\n> ```\nsyntax\n(with-syntax* ([pattern stx-expr] ...)\n> body ...+ )\n   stx-expr   :   syntax?"} {"text": "# 12.10 Serializing Syntax\n```\nSimilar to with-syntax, but the pattern variables of each pattern are bound in the stx-exprs of subsequent clauses as well as the bodys, and the patterns need not bind distinct pattern variables; later bindings shadow earlier bindings.\n\nExample:\n\n> ```racket\n> > ( with-syntax* ( [ ( x y ) ( list #' val1 #' val2 ) ] [ nest #' ( ( x ) ( y ) ) ] ) #' nest )\n> #\n> ```\n\n------------------------------------------------------------------------\n\n# 12.13 Phase and Space Utilities\n\n### 12.13 Phase and Space Utilities\n\n| | |\n|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/phase+space]()) |  package: base |\n\nThe bindings documented in this section are provided by the [racket/phase+space]() library, not racket/base or racket.\n\nThe [racket/phase+space]() library provides functions for manipulating combined representations of phase levels and binding spaces, particularly as used for require transformers and provide transformers.\n\nWhen identifier-binding (and related functions, like identifier-transformer-binding), syntax-local-module-exports, syntax-local-module-required-identifiers, module-compiled-exports, or module → exports produces a phase–space combination (or phase–space shift combination), then two such values that are equal? will be eqv?.\n\nAdded in version 8.2.0.3 of package base.\n\n> ```\n(phase? v) → boolean?\n  v : any/c```\n\n\nReturns #t if v is a valid representation of a [phase level](syntax-model.html#%28tech._phase._level%29), #f otherwise. A valid representation is either an exact integer representing a numbered phase level or #f representing the [label phase level](syntax-model.html#%28tech._label._phase._level%29).\n\n> ```\n(space? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 12.10 Serializing Syntax\nReturns #t if v is a valid representation of a binding space, #f otherwise. A valid representation is either an interned symbol representing the space whose scope is accessed via make-interned-syntax-introducer, or #f representing the default binding space.\n> ```\n(phase+space? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a valid representation of a [phase level](syntax-model.html#%28tech._phase._level%29) and [binding space](syntax-model.html#%28tech._binding._space%29) combination, #f otherwise. The possible representations are as follows:\n- a phase (in the sense of [phase?](#%28def._%28%28lib._racket%2Fphase%2Bspace..rkt%29._phase~3f%29%29)) by itself, which represents that phase plus the default binding space\n- a pair whose [car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) is a phase and whose [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) is a non-#f space (in the sense of [space?](#%28def._%28%28lib._racket%2Fphase%2Bspace..rkt%29._space~3f%29%29))\n> ```\n(phase+space phase space)  →  phase+space?\n  phase : phase?\n  space : space?\n```\n\n\nReturns a value to represent the combination of phase and space.\n\n> ```\n(phase+space-phase p+s)  →  phase?\n  p+s : phase+space?\n\n(phase+space-space p+s)  →  phase?\n  p+s : phase+space?\n```\nExtracts the [phase level](syntax-model.html#%28tech._phase._level%29) or [binding space](syntax-model.html#%28tech._binding._space%29) component from a combination.\n> ```\n(phase+space-shift? v)  →  boolean?\n  v : any/c"} {"text": "# 12.10 Serializing Syntax\n```\nReturns #t if v is a valid representation of a phase level shift and binding space shift combination, #f otherwise. A shift can be applied to a combination of a phase level and binding space using phase+shift+. The possible representations of a shift are as follows:\n\n- exact integer — represents an amount to shift a phase level and no change to the binding space\n\n- #f — represents a shift to the label phase level and no change to the binding space\n\n- a pair whose car is an exact integer or #f, and whose cdr is a space (in the sense of space?) — represents a phase level shift in the car and a change to the binding space that is in the cdr\n\n> ```\n(phase+space+ p+s shift)  →  phase+space?\n  p+s : phase+space?\n  shift : phase+space-shift?```\n\n\nApplies shift to p+s to produce a new combination of [phase level](syntax-model.html#%28tech._phase._level%29) and [binding space](syntax-model.html#%28tech._binding._space%29).\n\n> ```\n(phase+space-shift+ shift additional-shift)  →  phase+space-shift?\n  shift : phase+space?\n  additional-shift : phase+space-shift?\n```\n(current-locale)\t→\t\n(-> In particular, setting the LC_ALL and LC_CTYPE environment variables does not affect the locale \"\" on Mac OS. Use getenv and current-locale to explicitly install the environment-specified locale, if desired.)\n(current-locale locale) → void?\n locale\t:\t\n(-> In particular, setting the LC_ALL and LC_CTYPE environment variables does not affect the locale \"\" on Mac OS. Use getenv and current-locale to explicitly install the environment-specified locale, if desired.)```"} {"text": "# 12.10 Serializing Syntax\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the current [locale](#%28tech._locale%29) for procedures such as [string-locale-ci=?](strings.html#%28def._%28%28quote._~23~25kernel%29._string-locale-ci~3d~3f%29%29).\nWhen locale sensitivity is disabled by setting the parameter to #f, strings are compared, etc., in a fully portable manner, which is the same as the standard procedures. Otherwise, strings are interpreted according to a locale setting (in the sense of the C library’s setlocale). The \"\" locale is always an alias for the current machine’s default locale, and it is the default. The \"C\" locale is also always available; setting the locale to \"C\" is the same as disabling locale sensitivity with #f only when string operations are restricted to the first 128 characters. Other locale names are platform-specific.\nString or character printing with [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29) is not affected by the parameter, and neither are symbol case or regular expressions (see [Regular Expressions](regexp.html)).\n------------------------------------------------------------------------"} {"text": "# 13.1.2 Managing Ports"} {"text": "#### 13.1.2 Managing Ports\n> ```\n(input-port? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is an input port, #f otherwise.\n\n> ```\n(output-port? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is an [output port](ports.html#%28tech._output._port%29), #f otherwise.\n\n> ```\n(port? v)  →  boolean?\n  v : any/c\n```\n(parameter)\t→```\nCloses the input port in. For some kinds of ports, closing the port releases lower-level resources, such as a file handle. If the port is already closed, [close-input-port](#%28def._%28%28quote._~23~25kernel%29._close-input-port%29%29) has no effect.\n> ```\n(parameter)\t→\n```\nCloses the output port out. For some kinds of ports, closing the port releases lower-level resources, such as a file handle. Also, if the port is buffered, closing may first flush the port before closing it, and this flushing process can block. If the port is already closed, close-output-port has no effect.\n\n> ```\n(port-closed? port)  →  boolean?\n  port : port?```\n\n\nReturns #t if the input or output port port is closed, #f otherwise.\n\n> ```\n(port-closed-evt port)  →  evt?\n  port : port?\n```\n(current-input-port)\t→\t\n(-> current-input-port in)\n(current-input-port in) → void?\n in\t:\t\n(-> current-input-port in)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines a default input port for many operations, such as [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29).\n> ```\n(current-output-port)\t→\t\n(-> current-output-port out)\n(current-output-port out) → void?\n out\t:\t\n(-> current-output-port out)"} {"text": "# 13.1.2 Managing Ports\n```\n(current-error-port)\t→\t\n(-> current-error-port out)\n(current-error-port out) → void?\n out\t:\t\n(-> current-error-port out)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines an output port that is typically used for errors and logging. For example, the default error display handler writes to this port.\n\n> ```\n(file-stream-port? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a file-stream port (see File Ports), #f otherwise.\nChanged in version 7.2.0.5 of package base: Extended file-stream-port? to any value, instead of resticting the domain to ports\n> ```\n(terminal-port? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a port that is attached to an interactive terminal, #f otherwise.\nChanged in version 7.2.0.5 of package base: Extended [terminal-port?](#%28def._%28%28quote._~23~25kernel%29._terminal-port~3f%29%29) to any value, instead of resticting the domain to ports\n> ```\n(port-waiting-peer? port)  →  boolean?\n  port : port?"} {"text": "# 13.1.2 Managing Ports\n```\nReturns #t if port is not ready for reading or writing because it is waiting for a peer process to complete a stream construction, #f otherwise.\n\nOn Unix and Mac OS, opening a fifo for output creates a peer-waiting port if no reader for the same fifo is already opened. In that case, the output port is not ready for writing until a reader is opened; that is, write opertaions will block. Use sync if necessary to wait until writing will not block—that is, until the read end of the fifo is opened.\n\nAdded in version 7.4.0.5 of package base.\n\n>
\n\n

value

\n\n

eof : eof-object?

\n\nA value (distinct from all other values) that represents an end-of-file.\n\n> ```\n(eof-object? v) → boolean?\n  v : any/c```\n\n\nReturns #t if v is [eof](#%28def._%28%28quote._~23~25kernel%29._eof%29%29), #f otherwise.\n\n------------------------------------------------------------------------\n\n# 13.1.3 Port Buffers and Positions\n\n#### 13.1.3 Port Buffers and Positions\n\nSome ports—especially those that read from and write to files—are internally buffered:\n\n- An input port is typically block-buffered by default, which means that on any read, the buffer is filled with immediately-available bytes to speed up future reads. Thus, if a file is modified between a pair of reads to the file, the second read can produce stale data. Calling [file-position](#%28def._%28%28quote._~23~25kernel%29._file-position%29%29) to set an input port’s file position flushes its buffer.\n\n- An output port is typically block-buffered by default, though a terminal output port is line-buffered, and the initial error output port is unbuffered. An output buffer is filled with a sequence of written bytes to be committed as a group, either when the buffer is full (in block mode), when a newline is written (in line mode), when the port is closed via [close-output-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._close-output-port%29%29), or when a flush is explicitly requested via a procedure like [flush-output](#%28def._%28%28quote._~23~25kernel%29._flush-output%29%29).\n\nIf a port supports buffering, its buffer mode can be changed via [file-stream-buffer-mode](#%28def._%28%28quote._~23~25kernel%29._file-stream-buffer-mode%29%29) (even if the port is not a [file-stream port](file-ports.html#%28tech._file._stream._port%29)).\n\nFor an input port, peeking always places peeked bytes into the port’s buffer, even when the port’s buffer mode is 'none; furthermore, on some platforms, testing the port for input (via [char-ready?](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._char-ready~3f%29%29) or [sync](sync.html#%28def._%28%28quote._~23~25kernel%29._sync%29%29)) may be implemented with a peek. If an input port’s buffer mode is 'none, then at most one byte is read for [read-bytes-avail!*](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-bytes-avail%21%2A%29%29), [read-bytes-avail!](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-bytes-avail%21%29%29), [peek-bytes-avail!*](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._peek-bytes-avail%21%2A%29%29), or [peek-bytes-avail!](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._peek-bytes-avail%21%29%29); if any bytes are buffered in the port (e.g., to satisfy a previous peek), the procedures may access multiple buffered bytes, but no further bytes are read.\n\nIn addition, the initial current output and error ports are automatically flushed when they are terminal ports (see [terminal-port?](port-ops.html#%28def._%28%28quote._~23~25kernel%29._terminal-port~3f%29%29)) and when [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29), [read-line](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-line%29%29), [read-bytes](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-bytes%29%29), [read-string](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-string%29%29), etc., are performed on the initial standard input port. (More precisely, instead of [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29), flushing is performed by the default port read handler; see [port-read-handler](Reading.html#%28def._%28%28quote._~23~25kernel%29._port-read-handler%29%29).)\n\n> ```\n(current-output-port)\t→\t\n(-> current-output-port)\n```"} {"text": "# 13.1.2 Managing Ports\n(parameter)\t→\t\n(-> or/c 'none 'line 'block #f)```\nGets or sets the buffer mode for port, if possible. [File-stream ports](file-ports.html#%28tech._file._stream._port%29) support setting the buffer mode, TCP ports (see [Networking](networking.html)) support setting and getting the buffer mode, and custom ports (see [Custom Ports](customport.html)) may support getting and setting buffer modes.\nIf mode is provided, it must be one of 'none, 'line (output only), or 'block, and the port’s buffering is set accordingly. If the port does not support setting the mode, the [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) exception is raised.\nIf mode is not provided, the current mode is returned, or #f is returned if the mode cannot be determined. If port is an input port and mode is 'line, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n> ```\n(parameter)\t→\t\n(-> file-position port pos)"} {"text": "# 13.1.2 Managing Ports\n```\nReturns or sets the current read/write position of port.\n\nCalling file-position without a position on a port other than a file-stream port or string port returns the number of bytes that have been read from that port if the position is known (see Counting Positions, Lines, and Columns), otherwise the exn:fail:filesystem exception is raised.\n\nFor file-stream ports and string ports, the position-setting variant sets the read/write position to pos relative to the beginning of the file or (byte) string if pos is a number, or to the current end of the file or (byte) string if pos is eof. In position-setting mode, file-position raises the exn:fail:contract exception for port kinds other than file-stream ports and string ports. Furthermore, not all file-stream ports support setting the position; if file-position is called with a position argument on such a file-stream port, the exn:fail:filesystem exception is raised.\n\nWhen file-position sets the position pos beyond the current size of an output file or (byte) string, the file/string is enlarged to size pos and the new region is filled with 0 bytes; in the case of a file. In the case of a file output port, the file might not be enlarged until more data is written to the file; in that case, beware that writing to a file opened in 'append mode on Unix and Mac OS will reset the file pointer to the end of a file before each write, which defeats file enlargement via file-position. If pos is beyond the end of an input file or (byte) string, then reading thereafter returns eof without changing the port’s position.\n\nWhen changing the file position for an output port, the port is first flushed if its buffer is not empty. Similarly, setting the position for an input port clears the port’s buffer (even if the new position is the same as the old position). However, although input and output ports produced by open-input-output-file share the file position, setting the position via one port does not flush the other port’s buffer.\n\n> ```\n(file-position* port)  →  (or/c exact-nonnegative-integer? #f)\n  port : port?```\n\n\nLike [file-position](#%28def._%28%28quote._~23~25kernel%29._file-position%29%29) on a single argument, but returns #f if the position is not known.\n\n> ```\n(parameter)\t→\t\n(-> and/c output-port? file-stream-port?)\n```"} {"text": "# 13.1.2 Managing Ports\n(parameter)\t→```\nTurns on [line location](#%28tech._line._location%29) and [column location](#%28tech._column._location%29) counting for a port. Counting can be turned on at any time, though generally it is turned on before any data is read from or written to a port. At the point that line counting is turned on, [port-next-location](#%28def._%28%28quote._~23~25kernel%29._port-next-location%29%29) typically starts reporting as its last result (one more than) the number of characters read since line counting was enabled, instead of (one more than) bytes read since the port was opened.\nWhen a port is created, if the value of the [port-count-lines-enabled](#%28def._%28%28quote._~23~25kernel%29._port-count-lines-enabled%29%29) parameter is true, then line counting is automatically enabled for the port. Line counting cannot be disabled for a port after it is enabled.\n> ```\n(port-counts-lines? port)  →  boolean?\n  port : port?"} {"text": "# 13.1.2 Managing Ports\n```\nReturns #t if line location and column location counting has been enabled for port, #f otherwise.\n\n> ```\n(port-next-location port)\n  →   (or/c exact-positive-integer? #f)\n(or/c exact-nonnegative-integer? #f)\n(or/c exact-positive-integer? #f)\n\n  port : port?```\n\n\nReturns three values: an integer or #f for the line number of the next read/written item, an integer or #f for the next item’s column, and an integer or #f for the next item’s position. The next column and position normally increase as bytes are read from or written to the port, but if line/character counting is enabled for port, the column and position results can decrease after reading or writing a byte that ends a UTF-8 encoding sequence.\n\nIf line counting is not enabled for a port, than the first two results are #f, and the last result is one more than the number of bytes read so far. At the point when line counting is enabled, the first two results typically become non-#f, and last result starts reporting characters instead of bytes, typically starting from the point when line counting is enabled.\n\nEven with line counting enabled, a port may return #f values if it somehow cannot keep track of lines, columns, or positions.\n\n> ```\n(parameter)\t→\t\n(-> or/c exact-positive-integer? #f)\n```\nSets the next line, column, and position for port. If line counting has not been enabled for port or if port is a custom port that defines its own counting function, then set-port-next-location! has no effect.\n> ```\n(port-count-lines-enabled)\t → \t\n( → port-count-lines-enabled on?)```"} {"text": "# 13.1.2 Managing Ports\nA [parameter](eval-model.html#%28tech._parameter%29) that determines whether line counting is enabled automatically for newly created ports. The default value is #f.\n------------------------------------------------------------------------"} {"text": "# 13.1.5 File Ports"} {"text": "#### 13.1.5 File Ports\nA port created by [open-input-file](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._open-input-file%29%29), [open-output-file](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._open-output-file%29%29), [subprocess](subprocess.html#%28def._%28%28quote._~23~25kernel%29._subprocess%29%29), and related functions is a file-stream port. The initial input, output, and error ports in racket are also file-stream ports. The [file-stream-port?](port-ops.html#%28def._%28%28quote._~23~25kernel%29._file-stream-port~3f%29%29) predicate recognizes file-stream ports.\nWhen an input or output file-stream port is created, it is placed into the management of the current custodian (see [Custodians](custodians.html)). In the case of an output port, a [flush callback](plumbers.html#%28tech._flush._callback%29) is registered with the [current plumber](plumbers.html#%28tech._current._plumber%29) to flush the port.\n> ```\n(open-input-file path\n   [ #:mode mode-flag        \n    #:for-module? for-module?)   →   input-port?\n  path : path-string?\n  mode-flag : (or/c 'binary 'text) = 'binary\n  for-module? : any/c = #f"} {"text": "# 13.1.5 File Ports\n```\n(otherwise)\t→\t\n(-> or/c 'binary 'text)```\n\n\nOpens the file specified by path for output. The mode-flag argument specifies how bytes written to the port are translated when written to the file:\n\n- 'binary — bytes are written to the file exactly as written to the port.\n\n- 'text — on Windows, a linefeed byte (10) written to the port is translated to a return-linefeed combination in the file; no filtering occurs for returns.\n\nOn Windows, 'text mode works only with regular files; attempting to use 'text with other kinds of files triggers an [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) exception.\n\nThe exists-flag argument specifies how to handle/require files that already exist:\n\n- 'error — raise [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) if the file exists.\n\n- 'replace — remove the old file, if it exists, and write a new one.\n\n- 'truncate — remove all old data, if the file exists.\n\n- 'must-truncate — remove all old data in an existing file; if the file does not exist, the [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) exception is raised.\n\n- 'truncate/replace — try 'truncate; if it fails (perhaps due to file permissions), try 'replace.\n\n- 'update — open an existing file without truncating it; if the file does not exist, the [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) exception is raised. Use [file-position](port-buffers.html#%28def._%28%28quote._~23~25kernel%29._file-position%29%29) to change the current read/write position.\n\n- 'can-update — open an existing file without truncating it, or create the file if it does not exist.\n\n- 'append — append to the end of the file, whether it already exists or not; on Windows, 'append is equivalent to 'update, except that the file is not required to exist, and the file position is immediately set to the end of the file after opening it.\n\nWhen the file specified by path is created, permissions specifies the permissions of the created file, where an integer representation of permissions is treated the same as for [file-or-directory-permissions](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._file-or-directory-permissions%29%29). On Unix and Mac OS, these permissions bits are combined with the process’s umask. On Windows, the only relevant property of permissions is whether it has the #o2 bit set for write permission. Note that a read-only file can be created with [open-output-file](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._open-output-file%29%29), in which case writing is prohibited only for later attempts to open the file. If replace-permissions? is a true value, then independent of whether the opened file is newly created, the value of permissions is applied to the opened file, and it is applied independent of the process’s umask on Unix and Mac OS.\n\nThe file specified by path need not be a regular file. It might be a device that is connected through the filesystem, such as \"aux\" on Windows or \"/dev/null\" on Unix. The output port is block-buffered by default, unless the file corresponds to a terminal, in which case it is line-buffered by default. On Unix and Mac OS, if the file is a fifo, then the port will block for writing until a reader for the fifo is available; see also [port-waiting-peer?](port-ops.html#%28def._%28%28quote._~23~25kernel%29._port-waiting-peer~3f%29%29).\n\nThe port produced by [open-output-file](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._open-output-file%29%29) should be explicitly closed, either though [close-output-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._close-output-port%29%29) or indirectly via [custodian-shutdown-all](custodians.html#%28def._%28%28quote._~23~25kernel%29._custodian-shutdown-all%29%29), to release the OS-level file handle. The output port will not be closed automatically even if it is otherwise available for garbage collection (see [Garbage Collection](eval-model.html#%28part._gc-model%29)); a [will](willexecutor.html#%28tech._will%29) could be associated with an output port to close it more automatically (see [Wills and Executors](willexecutor.html)).\n\nA [path](pathutils.html#%28tech._path%29) value that is the [cleanse](pathutils.html#%28tech._cleanse%29)d version of path is used as the name of the opened port.\n\nOn variants of Unix and MacOS that support O_CLOEXEC, the file is opened with O_CLOEXEC so that the underlying file descriptor is not shared with a subprocess created by [subprocess](subprocess.html#%28def._%28%28quote._~23~25kernel%29._subprocess%29%29). On Windows, the file is opened as a non-inherited handle.\n\nIf opening the file fails due to an error in the underlying filesystem then [exn:fail:filesystem:errno](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem~3aerrno%29%29) exception is raised.\n\nExamples:\n\n> ```racket\n> > ( define out ( open-output-file some-file ) )\n> > ( write \"hello world\" out )\n> > ( close-output-port out )\n> ```\n\nChanged in version 6.9.0.6 of package base: On Unix and Mac OS, make 'truncate/replace replace on a permission error. On Windows, make 'replace always replace instead truncating like 'truncate/replace. \nChanged in version 7.4.0.5: Changed handling of a fifo on Unix and Mac OS to make the port block for output until the fifo has a reader. \nChanged in version 8.1.0.3: Added the #:permissions argument. \nChanged in version 8.7.0.10: Added the #:replace-permissions? argument. \nChanged in version 8.11.1.6: Changed to use O_CLOEXEC where supported by the operating system.\n\n> ```\n(open-input-output-file\n    path  \n   [ #:mode mode-flag  \n    #:exists exists-flag  \n    #:permissions permissions]  \n    #:replace-permissions? replace-permissions?)  \n\n  →   input-port?   output-port?\n\n  path : path-string?\n  mode-flag : (or/c 'binary 'text) = 'binary\n   exists-flag   :   ( or/c ' error ' append ' update ' can-update\n> ' replace ' truncate\n> ' must-truncate ' truncate/replace )\n      =   'error\n\n  permissions : (integer-in 0 65535) = #o666\n  replace-permissions? : #f\n```"} {"text": "# 13.1.5 File Ports\nLike open-output-file, but producing two values: an input port and an output port. The two ports are connected in that they share the underlying file descriptor. This procedure is intended for use with special devices that can be opened by only one process, such as \"COM1\" in Windows. For regular files, sharing the file descriptor can be confusing. For example, using one port does not automatically flush the other port’s buffer, and reading or writing in one port moves the file position (if any) for the other port. For regular files, use separate open-input-file and open-output-file calls to avoid confusion.\nChanged in version 8.1.0.3 of package base: Added the #:permissions argument. \nChanged in version 8.7.0.10: Added the #:replace-permissions? argument.\n> ```\n(call-with-input-file path\n    proc        \n   [ #:mode mode-flag)   →   any\n  path : path-string?\n  proc : (input-port? . → . any)\n  mode-flag : (or/c 'binary 'text) = 'binary```\nCalls [open-input-file](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._open-input-file%29%29) with the path and mode-flag arguments, and passes the resulting port to proc. The result of proc is the result of the [call-with-input-file](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._call-with-input-file%29%29) call, but the newly opened port is closed when proc returns.\nExamples:\n> ```racket\n> > ( with-output-to-file some-file ( lambda ( ) ( printf \"text in a file\" ) ) )\n> > ( call-with-input-file some-file ( lambda ( in ) ( read-string 14 in ) ) )\n> \"text in a file\"\n> ```\n> ```"} {"text": "# 13.1.5 File Ports\n(call-with-output-file\n    path  \n    proc  \n   [ #:mode mode-flag  \n    #:exists exists-flag  \n    #:permissions permissions]  \n    #:replace-permissions? replace-permissions?)  \n  →  any\n  path : path-string?\n  proc : (output-port? . → . any)\n  mode-flag : (or/c 'binary 'text) = 'binary\n   exists-flag   :   ( or/c ' error ' append ' update ' can-update\n> ' replace ' truncate\n> ' must-truncate ' truncate/replace )\n      =   'error\n  permissions : (integer-in 0 65535) = #o666\n  replace-permissions? : #f\n```\nAnalogous to call-with-input-file, but passing path, mode-flag, exists-flag, and permissions to open-output-file.\n\nExamples:\n\n> ```racket\n> > ( call-with-output-file some-file ( lambda ( out ) ( write ' hello out ) ) )\n> > ( call-with-input-file some-file ( lambda ( in ) ( read-string 5 in ) ) )\n> \"hello\"\n> ```\n\nChanged in version 8.1.0.3 of package base: Added the #:permissions argument. \nChanged in version 8.7.0.10: Added the #:replace-permissions? argument.\n\n> ```\n(call-with-input-file* path\n    proc        \n   [ #:mode mode-flag)   →   any\n\n  path : path-string?\n  proc : (input-port? . → . any)\n  mode-flag : (or/c 'binary 'text) = 'binary```\n\n\nLike [call-with-input-file](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._call-with-input-file%29%29), but the newly opened port is closed whenever control escapes the dynamic extent of the [call-with-input-file*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._call-with-input-file%2A%29%29) call, whether through proc’s return, a continuation application, or a prompt-based abort.\n\n> ```\n(call-with-output-file*\n    path  \n    proc  \n   [ #:mode mode-flag  \n    #:exists exists-flag  \n    #:permissions permissions]  \n    #:replace-permissions? replace-permissions?)  \n\n  →  any\n  path : path-string?\n  proc : (output-port? . → . any)\n  mode-flag : (or/c 'binary 'text) = 'binary\n   exists-flag   :   ( or/c ' error ' append ' update ' can-update\n> ' replace ' truncate\n> ' must-truncate ' truncate/replace )\n      =   'error\n\n  permissions : (integer-in 0 65535) = #o666\n  replace-permissions? : #f\n```"} {"text": "# 13.1.5 File Ports\nLike call-with-output-file, but the newly opened port is closed whenever control escapes the dynamic extent of the call-with-output-file* call, whether through proc’s return, a continuation application, or a prompt-based abort.\nChanged in version 8.1.0.3 of package base: Added the #:permissions argument. \nChanged in version 8.7.0.10: Added the #:replace-permissions? argument.\n> ```\n(with-input-from-file path\n    thunk        \n   [ #:mode mode-flag)   →   any\n  path : path-string?\n  thunk : ( →  any)\n  mode-flag : (or/c 'binary 'text) = 'binary```\nLike [call-with-input-file*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._call-with-input-file%2A%29%29), but instead of passing the newly opened port to the given procedure argument, the port is installed as the current input port (see [current-input-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._current-input-port%29%29)) using [parameterize](parameters.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize%29%29) around the call to thunk.\nExamples:\n> ```racket\n> > ( with-output-to-file some-file ( lambda ( ) ( printf \"hello\" ) ) )\n> > ( with-input-from-file some-file ( lambda ( ) ( read-string 5 ) ) )\n> \"hello\"\n> ```\n> ```\n(with-output-to-file\n    path  \n    thunk  \n   [ #:mode mode-flag  \n    #:exists exists-flag  \n    #:permissions permissions]  \n    #:replace-permissions? replace-permissions?)  \n  →  any\n  path : path-string?\n  thunk : ( →  any)\n  mode-flag : (or/c 'binary 'text) = 'binary\n   exists-flag   :   ( or/c ' error ' append ' update ' can-update"} {"text": "# 13.1.5 File Ports\n> ' replace ' truncate\n> ' must-truncate ' truncate/replace )\n      =   'error\n  permissions : (integer-in 0 65535) = #o666\n  replace-permissions? : #f\n```\n(parameter)\t→\t\n(-> or/c 'shared 'exclusive)```\n\n\nAttempts to acquire a lock on the file using the current platform’s facilities for file locking. Multiple processes can acquire a 'shared lock on a file, but at most one process can hold an 'exclusive lock, and 'shared and 'exclusive locks are mutually exclusive. When mode is 'shared, then port must be an input port; when mode is 'exclusive, then port must be an output port.\n\nThe result is #t if the requested lock is acquired, #f otherwise. When a lock is acquired, it is held until either it is released with [port-file-unlock](#%28def._%28%28quote._~23~25kernel%29._port-file-unlock%29%29) or the port is closed (perhaps because the process terminates).\n\nDepending on the platform, locks may be merely advisory (i.e., locks affect only the ability of processes to acquire locks) or they may correspond to mandatory locks that prevent reads and writes to the locked file. Specifically, locks are mandatory on Windows and advisory on other platforms. Multiple tries for a 'shared lock on a single port can succeed; on Unix and Mac OS, a single [port-file-unlock](#%28def._%28%28quote._~23~25kernel%29._port-file-unlock%29%29) release the lock, while on other Windows, a [port-file-unlock](#%28def._%28%28quote._~23~25kernel%29._port-file-unlock%29%29) is needed for each successful [port-try-file-lock?](#%28def._%28%28quote._~23~25kernel%29._port-try-file-lock~3f%29%29). On Unix and Mac OS, multiple tries for a 'exclusive lock can succeed and a single [port-file-unlock](#%28def._%28%28quote._~23~25kernel%29._port-file-unlock%29%29) releases the lock, while on Windows, a try for an 'exclusive lock fails for a given port if the port already holds the lock.\n\nA lock acquired for an input port from [open-input-output-file](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._open-input-output-file%29%29) can be released through [port-file-unlock](#%28def._%28%28quote._~23~25kernel%29._port-file-unlock%29%29) on the corresponding output port, and vice versa. If the output port from [open-input-output-file](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._open-input-output-file%29%29) holds an 'exclusive lock, the corresponding input port can still acquire a 'shared lock, even multiple times; on Windows, a [port-file-unlock](#%28def._%28%28quote._~23~25kernel%29._port-file-unlock%29%29) is needed for each successful lock try, while a single [port-file-unlock](#%28def._%28%28quote._~23~25kernel%29._port-file-unlock%29%29) balances the lock tries on Unix and Mac OS. A 'shared lock on an input port can be upgraded to an 'exclusive lock through the corresponding output port on Unix and Mac OS, in which case a single [port-file-unlock](#%28def._%28%28quote._~23~25kernel%29._port-file-unlock%29%29) (on either port) releases the lock, while such upgrades are not allowed on Windows.\n\nLocking is normally supported only for file ports, and attempting to acquire a lock with other kinds of file-stream ports raises an [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) exception.\n\n> ```\n(parameter)\t→\n```"} {"text": "# 13.1.5 File Ports\nReleases a lock held by the current process on the file of port.\n> ```\n(port-file-identity port)  →  exact-positive-integer?\n  port : file-stream-port?\n```\n\n\nReturns a number that represents the identity of the device and file read or written by port. For two ports whose open times overlap, the result of [port-file-identity](#%28def._%28%28quote._~23~25kernel%29._port-file-identity%29%29) is the same for both ports if and only if the ports access the same device and file. For ports whose open times do not overlap, no guarantee can be provided for the port identities (even if the ports actually access the same file)—except as can be inferred through relationships with other ports. If port is closed, the [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) exception is raised. On Windows 95, 98, and Me, if port is connected to a pipe instead of a file, the [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) exception is raised.\n\nExamples:\n\n> ```racket\n> > ( define file1 ( open-output-file some-file ) )\n> > ( define file2 ( open-output-file some-other-file ) )\n> > ( port-file-identity file1 )\n> 358412864794394642\n> > ( port-file-identity file2 )\n> 358412869089361938\n> > ( close-output-port file1 )\n> > ( close-output-port file2 )\n> ```\n\n> ```\n(parameter)\t→\t\n(-> and/c (hash/c symbol? any/c) hash-eq?)\n```\nLike file-or-directory-stat, but returns information for an open file represented by a port, instead using of the file’s path."} {"text": "# 13.1.5 File Ports\nAdded in version 8.15.0.6 of package base.\n------------------------------------------------------------------------"} {"text": "# 13.1.6 String Ports"} {"text": "#### 13.1.6 String Ports\nA string port reads or writes from a byte string. An input string port can be created from either a byte string or a string; in the latter case, the string is effectively converted to a byte string using string → bytes/utf-8. An output string port collects output into a byte string, but get-output-string conveniently converts the accumulated bytes to a string.\nInput and output string ports do not need to be explicitly closed. The file-position procedure works for string ports in position-setting mode.\n> > > \"+\"Byte Strings also provides information on bytestrings.\n> ```\n(string-port? p) → boolean?\n  p : port?```\nReturns #t if p is a [string port](#%28tech._string._port%29), #f otherwise.\nAdded in version 6.0.1.6 of package base.\n> ```\n(open-input-bytes bstr [name) → (and/c input-port? string-port?)\n  bstr : bytes?\n  name : any/c = 'string"} {"text": "# 13.1.6 String Ports\n```\nCreates an input string port that reads characters from bstr (see Byte Strings). Modifying bstr afterward does not affect the byte stream produced by the port. The optional name argument is used as the name for the returned port.\n\nExamples:\n\n> ```racket\n> > ( define sp ( open-input-bytes #\"(apples 42 day)\" ) )\n> > ( define sexp1 ( read sp ) )\n> > ( first sexp1 )\n> 'apples\n> > ( rest sexp1 )\n> '(42 day)\n> > ( read-line ( open-input-bytes #\"the cow jumped over the moon\\nthe little dog\\n\" ) )\n> \"the cow jumped over the moon\"\n> ```\n\n> > > \"+\"Strings also provides information on strings.\n\n> ```\n(open-input-string str [name) → (and/c input-port? string-port?)\n  str : string?\n  name : any/c = 'string```\n\n\nCreates an input [string port](#%28tech._string._port%29) that reads bytes from the UTF-8 encoding (see [Encodings and Locales](encodings.html)) of str. The optional name argument is used as the name for the returned port.\n\nExamples:\n\n> ```racket\n> > ( define sp ( open-input-string \"(λ (x) x)\" ) )\n> > ( read sp )\n> '(λ (x) x)\n> > ( define names ( open-input-string \"Günter Harder\\nFrédéric Paulin\\n\" ) )\n> > ( read-line names )\n> \"Günter Harder\"\n> > ( read-line names )\n> \"Frédéric Paulin\"\n> ```\n\n> ```\n(open-output-bytes [name) → (and/c output-port? string-port?)\n  name : any/c = 'string\n```\nCreates an output string port that accumulates the output into a byte string. The optional name argument is used as the name for the returned port.\nExamples:"} {"text": "# 13.1.6 String Ports\n> ```racket\n> > ( define op1 ( open-output-bytes ) )\n> > ( write ' ( ( 1 2 3 ) ( \"Tom\" \"Dick\" ) ( ' a ' b ' c ) ) op1 )\n> > ( get-output-bytes op1 )\n> #\"((1 2 3) (\\\"Tom\\\" \\\"Dick\\\") ((quote a) (quote b) (quote c)))\"\n> > ( define op2 ( open-output-bytes ) )\n> > ( write \"Hi \" op2 )\n> > ( write \"there\" op2 )\n> > ( get-output-bytes op2 )\n> #\"\\\"Hi \\\"\\\"there\\\"\"\n> > ( define op3 ( open-output-bytes ) )\n> > ( write-bytes #\"Hi \" op3 )\n> 3\n> > ( write-bytes #\"there\" op3 )\n> 5\n> > ( get-output-bytes op3 )\n> #\"Hi there\"\n> ```\n> ```\n(open-output-string [name) → (and/c output-port? string-port?)\n  name : any/c = 'string```\nThe same as [open-output-bytes](#%28def._%28%28quote._~23~25kernel%29._open-output-bytes%29%29).\nExamples:\n> ```racket\n> > ( define op1 ( open-output-string ) )\n> > ( write ' ( ( 1 2 3 ) ( \"Tom\" \"Dick\" ) ( ' a ' b ' c ) ) op1 )\n> > ( get-output-string op1 )\n> \"((1 2 3) (\\\"Tom\\\" \\\"Dick\\\") ((quote a) (quote b) (quote c)))\"\n> > ( define op2 ( open-output-string ) )\n> > ( write \"Hi \" op2 )\n> > ( write \"there\" op2 )\n> > ( get-output-string op2 )\n> \"\\\"Hi \\\"\\\"there\\\"\"\n> > ( define op3 ( open-output-string ) )\n> > ( write-string \"Hi \" op3 )\n> 3\n> > ( write-string \"there\" op3 )\n> 5\n> > ( get-output-string op3 )\n> \"Hi there\"\n> ```\n> ```\n(get-output-bytes out\n   [ reset?        \n    start-pos        \n    end-pos)   →   bytes?\n  out : (and/c output-port? string-port?)\n  reset? : any/c = #f\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : exact-nonnegative-integer? = #f"} {"text": "# 13.1.6 String Ports\n```\nReturns the bytes accumulated in the string port out so far in a freshly allocated byte string (including any bytes written after the port’s current position, if any). The out port must be an output string port produced by open-output-bytes (or open-output-string) or a structure whose prop:output-port property refers to such an output port (transitively).\n\nIf reset? is true, then all bytes are removed from the port, and the port’s position is reset to 0; if reset? is #f, then all bytes remain in the port for further accumulation (so they are returned for later calls to get-output-bytes or get-output-string), and the port’s position is unchanged.\n\nThe start-pos and end-pos arguments specify the range of bytes in the port to return; supplying start-pos and end-pos is the same as using subbytes on the result of get-output-bytes, but supplying them to get-output-bytes can avoid an allocation. The end-pos argument can be #f, which corresponds to not passing a second argument to subbytes.\n\nExamples:\n\n> ```racket\n> > ( define op ( open-output-bytes ) )\n> > ( write ' ( ( 1 2 3 ) ( \"Tom\" \"Dick\" ) ( ' a ' b ' c ) ) op )\n> > ( get-output-bytes op )\n> #\"((1 2 3) (\\\"Tom\\\" \\\"Dick\\\") ((quote a) (quote b) (quote c)))\"\n> > ( get-output-bytes op #f 3 16 )\n> #\" 2 3) (\\\"Tom\\\" \"\n> > ( get-output-bytes op #t )\n> #\"((1 2 3) (\\\"Tom\\\" \\\"Dick\\\") ((quote a) (quote b) (quote c)))\"\n> > ( get-output-bytes op )\n> #\"\"\n> ```\n\n> ```\n(get-output-string out)  →  string?\n  out : (and/c output-port? string-port?)```\n\n\nReturns ([bytes->string/utf-8](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._bytes-~3estring%2Futf-8%29%29) ([get-output-bytes](#%28def._%28%28quote._~23~25kernel%29._get-output-bytes%29%29) out) #\\\\uFFFD).\n\nExamples:\n\n> ```racket\n> > ( define i ( open-input-string \"hello world\" ) )\n> > ( define o ( open-output-string ) )\n> > ( write ( read i ) o )\n> > ( get-output-string o )\n> \"hello\"\n> ```\n\n------------------------------------------------------------------------\n\n# 13.1.7 Pipes\n\n#### 13.1.7 Pipes\n\nA Racket pipe is internal to Racket, and not related to OS-level pipes for communicating between different processes.OS-level pipes may be created by [subprocess](subprocess.html#%28def._%28%28quote._~23~25kernel%29._subprocess%29%29), opening an existing named file on a Unix filesystem, or starting Racket with pipes for its original input, output, or error port. Such pipes are [file-stream ports](file-ports.html#%28tech._file._stream._port%29), unlike the pipes produced by [make-pipe](#%28def._%28%28quote._~23~25kernel%29._make-pipe%29%29).\n\n> ```\n(pipe-port? p)  →  boolean?\n  p : port?\n```"} {"text": "# 13.1.6 String Ports\nReturns #t if p is either end of a pipe created by make-pipe, #f otherwise.\nAdded in version 8.15.0.9 of package base.\n> ```\n(make-pipe [limit input-name output-name)\n  →   (and/c input-port? pipe-port?)\n(and/c output-port? pipe-port?)\n  limit : exact-positive-integer? = #f\n  input-name : any/c = 'pipe\n  output-name : any/c = 'pipe```\nReturns two port values: the first port is an input port and the second is an output port. Data written to the output port is read from the input port, with no intermediate buffering. Unlike some other kinds of ports, pipe ports do not need to be explicitly closed to be reclaimed by [garbage collection](eval-model.html#%28part._gc-model%29).\nIf limit is #f, the new pipe holds an unlimited number of unread bytes (i.e., limited only by the available memory). If limit is a positive number, then the pipe will hold at most limit unread/unpeeked bytes; writing to the pipe’s output port thereafter will block until a read or peek from the input port makes more space available. (Peeks effectively extend the port’s capacity until the peeked bytes are read.)\nThe optional input-name and output-name are used as the names for the returned input and output ports, respectively.\n> ```\n(pipe-content-length pipe-port)  →  exact-nonnegative-integer?\n  pipe-port : pipe-port?"} {"text": "# 13.1.6 String Ports\n```\nReturns the number of bytes contained in a pipe, where pipe-port is either of the pipe’s ports produced by make-pipe. The pipe’s content length counts all bytes that have been written to the pipe and not yet read (though possibly peeked).\n\n------------------------------------------------------------------------\n\n# 13.1.8 Structures as Ports\n\n#### 13.1.8 Structures as Ports\n\n>
\n\n

value

\n\n

prop:input-port : struct-type-property?

\n\n>
\n\n

value

\n\n

prop:output-port : struct-type-property?

\n\nThe prop:input-port and prop:output-port structure type properties identify structure types whose instances can serve as input and output ports, respectively.\n\nEach property value can be either of the following:\n\n- An input port (for prop:input-port) or output port (for prop:output-port): In this case, using the structure as port is equivalent to using the given input or output port.\n\n- An exact, non-negative integer between 0 (inclusive) and the number of non-automatic fields in the structure type (exclusive, not counting supertype fields): The integer identifies a field in the structure, and the field must be designated as immutable. If the field contains an input port (for prop:input-port) or output port (for prop:output-port), the port is used. Otherwise, an empty string input port is used for prop:input-port, and a port that discards all data is used for prop:output-port.\n\nSome procedures, such as file-position, work on both input and output ports. When given an instance of a structure type with both the prop:input-port and prop:output-port properties, the instance is used as an input port.\n\n------------------------------------------------------------------------\n\n# 13.1.9 Custom Ports\n\n#### 13.1.9 Custom Ports\n\nThe make-input-port and make-output-port procedures create custom ports with arbitrary control procedures (much like implementing a device driver). Custom ports are mainly useful to obtain fine control over the action of committing bytes as read or written.\n\n> ```\n(make-input-port name\n    read-in        \n    peek        \n    close        \n   [ get-progress-evt        \n    commit        \n    get-location        \n    count-lines!        \n    init-position        \n    buffer-mode)   →   input-port?\n\n  name : any/c\n   read-in   :   ( or/c\n> ( bytes?\n> . → . ( or/c exact-nonnegative-integer?\n> eof-object?\n> procedure?\n> evt? ) )\n> input-port? )\n\n   peek   :   ( or/c\n> ( bytes? exact-nonnegative-integer? ( or/c evt? #f )\n> . → . ( or/c exact-nonnegative-integer?\n> eof-object?\n> procedure?\n> evt?\n> #f ) )\n> input-port?\n> #f )\n\n  close : ( →  any)\n  get-progress-evt : (or/c ( →  evt?) #f) = #f\n   commit   :   ( or/c ( exact-positive-integer? evt? evt? . → . any )\n> #f )\n      =   #f\n\n   get-location   :   ( or/c\n> ( → \n> ( values ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f ) ) )\n> #f )\n      =   #f\n\n  count-lines! : ( →  any) = void\n   init-position   :   ( or/c exact-positive-integer?\n> port?\n> #f\n> ( → ( or/c exact-positive-integer? #f ) ) )\n      =   1\n\n   buffer-mode   :   ( or/c ( case → ( ( or/c ' block ' none ) . → . any )\n> ( → ( or/c ' block ' none #f ) ) )\n> #f )\n      =   #f```\n\n\nCreates an input port, which is immediately open for reading. If close procedure has no side effects, then the port need not be explicitly closed. See also [make-input-port/read-to-peek](port-lib.html#%28def._%28%28lib._racket%2Fport..rkt%29._make-input-port%2Fread-to-peek%29%29).\n\nThe arguments implement the port as follows:\n\n- name — the name for the input port.\n\n- \n\n read-in — either an input port, in which case reads are redirected to the given port, or a procedure that takes a single argument: a mutable byte string to receive read bytes. The procedure’s result is one of the following:\n\n \n\n \n\n - the number of bytes read, as an exact, non-negative integer;\n\n - [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29);\n\n - a procedure of arity four (representing a “special” result, as discussed [further below](#%28elem._special%29)), but a procedure result is allowed only when peek is not #f;\n\n - a [pipe](pipeports.html#%28tech._pipe%29) input port that supplies bytes to be used as long as the pipe has content (see [pipe-content-length](pipeports.html#%28def._%28%28quote._~23~25kernel%29._pipe-content-length%29%29)) or until read-in or peek is called again; or\n\n - a [synchronizable event](sync.html#%28tech._synchronizable._event%29) (see [Events](sync.html)) other than a pipe input port or procedure of arity four; the event becomes ready when the read is complete (roughly): the event’s value can be one of the above four results or another event like itself; in the last case, a reading process loops with [sync](sync.html#%28def._%28%28quote._~23~25kernel%29._sync%29%29) until it gets a non-event result.\n\n \n\n The read-in procedure must not block indefinitely. If no bytes are immediately available for reading, the read-in must return 0 or an event, and preferably an event (to avoid busy waits). The read-in should not return 0 (or an event whose value is 0) when data is available in the port, otherwise polling the port will behave incorrectly. An event result from an event can also break polling.\n\n If the result of a read-in call is not one of the above values, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. If a returned integer is larger than the supplied byte string’s length, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. If peek is #f and a procedure for a [special](#%28elem._special%29) result is returned, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\n The read-in procedure can report an error by raising an exception, but only if no bytes are read. Similarly, no bytes should be read if [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29), an event, or a procedure is returned. In other words, no bytes should be lost due to spurious exceptions or non-byte data.\n\n A port’s reading procedure may be called in multiple threads simultaneously (if the port is accessible in multiple threads), and the port is responsible for its own internal synchronization. Note that improper implementation of such synchronization mechanisms might cause a non-blocking read procedure to block indefinitely.\n\n If the result is a pipe input port, then previous get-progress-evt calls whose event is not yet ready must have been the pipe input port itself. Furthermore, get-progress-evt must continue to return the pipe as long as it contains data, or until the read-in or peek-in procedure is called again (instead of using the pipe, for whatever reason). If read-in or peek-in is called, any previously associated pipe (as returned by a previous call) is disassociated from the port and is not in use by any other thread as a result of the previous association.\n\n If peek, get-progress-evt, and commit are all provided and non-#f, then the following is an acceptable implementation of read-in:\n\n > ```racket\n > ( lambda ( bstr )\n > ( let* ( [ progress-evt ( get-progress-evt ) ]\n > [ v ( peek bstr 0 progress-evt ) ] )\n > ( cond\n > [ ( sync/timeout 0 progress-evt ) 0 ] ; try again\n > [ ( evt? v ) ( wrap-evt v ( lambda ( x ) 0 ) ) ] ; sync, try again\n > [ ( and ( number? v ) ( zero? v ) ) 0 ] ; try again\n > [ else\n > ( if ( commit ( if ( number? v ) v 1 )\n > progress-evt\n > always-evt )\n > v ; got a result\n > 0 ) ] ) ) ) ; try again\n > ```\n\n An implementor may choose not to implement the peek, get-progress-evt, and commit procedures, however, and even an implementor who does supply them may provide a different read-in that uses a fast path for non-blocking reads.\n\n In an input port is provided for read-in, then an input port must also be provided for peek.\n\n- peek — either #f, an input port (in which case peeks are redirected to the given port), or a procedure that takes three arguments:\n\n - a mutable byte string to receive peeked bytes;\n\n - a non-negative number of bytes (or [specials](#%28elem._special%29)) to skip before peeking; and\n\n - either #f or a progress event produced by get-progress-evt.\n\n The results and conventions for peek are mostly the same as for read-in. The main difference is in the handling of the progress event, if it is not #f. If the given progress event becomes ready, the peek must abort any skip attempts and not peek any values. In particular, peek must not peek any values if the progress event is initially ready. If the port has been closed, the progress event should be ready, in which case peek should complete (instead of failing because the port is closed).\n\n Unlike read-in, peek should produce #f (or an event whose value is #f) if no bytes were peeked because the progress event became ready. Like read-in, a 0 result indicates that another attempt is likely to succeed, so 0 is inappropriate when the progress event is ready. Also like read-in, peek must not block indefinitely. An event produced by peek is polled (in the sense of [poll-guard-evt](sync.html#%28def._%28%28quote._~23~25kernel%29._poll-guard-evt%29%29)) by an option like [byte-ready?](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._byte-ready~3f%29%29) or peek-bytes-avail\\*!.\n\n The skip count provided to peek is a number of bytes (or [specials](#%28elem._special%29)) that must remain present in the port—in addition to the peek results—when the peek results are reported. If the skip count requests reading data that is past an eof, it should not, and instead produce [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29) (until the eof is consumed).\n\n If a progress event is supplied, then the peek is effectively canceled when another process reads data before the given number can be skipped. If a progress event is not supplied and data is read, then the peek must effectively restart with the original skip count.\n\n The system does not check that multiple peeks return consistent results, or that peeking and reading produce consistent results, although they must.\n\n If peek is #f, then peeking for the port is implemented automatically in terms of reads, but with several limitations. First, the automatic implementation is not thread-safe. Second, the automatic implementation cannot handle [special](#%28elem._special%29) results (non-byte and non-eof), so read-in cannot return a procedure for a [special](#%28elem._special%29) when peek is #f. Finally, the automatic peek implementation is incompatible with progress events, so if peek is #f, then get-progress-evt and commit must be #f. See also [make-input-port/read-to-peek](port-lib.html#%28def._%28%28lib._racket%2Fport..rkt%29._make-input-port%2Fread-to-peek%29%29), which implements peeking in terms of read-in without these constraints.\n\n In an input port is provided for peek, then an input port must also be provided for read-in.\n\n- close — a procedure of zero arguments that is called to close the port. The port is not considered closed until the closing procedure returns. The port’s procedures will never be used again via the port after it is closed. However, the closing procedure can be called simultaneously in multiple threads (if the port is accessible in multiple threads), and it may be called during a call to the other procedures in another thread; in the latter case, any outstanding reads and peeks should be terminated with an error.\n\n- get-progress-evt — either #f (the default), or a procedure that takes no arguments and returns an event. The event must become ready only after data is next read from the port or the port is closed. If the port is already closed, the event must be ready. After the event becomes ready, it must remain so. See the description of read-in for information about the allowed results of this function when read-in returns a pipe input port. See also [semaphore-peek-evt](semaphore.html#%28def._%28%28quote._~23~25kernel%29._semaphore-peek-evt%29%29), which is sometimes useful for implementing get-progress-evt.\n\n If get-progress-evt is #f, then [port-provides-progress-evts?](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._port-provides-progress-evts~3f%29%29) applied to the port will produce #f, and the port will not be a valid argument to [port-progress-evt](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._port-progress-evt%29%29).\n\n The result event will not be exposed directly by [port-progress-evt](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._port-progress-evt%29%29). Instead, it will be wrapped in an event for which [progress-evt?](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._progress-evt~3f%29%29) returns true.\n\n- commit — either #f (the default), or a procedure that takes three arguments:\n\n - an exact, positive integer kr;\n\n - a progress event produced by get-progress-evt;\n\n - an event, done, that is either a channel-put event, channel, semaphore, semaphore-peek event, always event, or never event.\n\n A commit corresponds to removing data from the stream that was previously peeked, but only if no other process removed data first. (The removed data does not need to be reported, because it has been peeked already.) More precisely, assuming that kp bytes, [specials](#%28elem._special%29), and mid-stream [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29)s have been previously peeked or skipped at the start of the port’s stream, commit must satisfy the following constraints:\n\n - It must return only when the commit is complete or when the given progress event becomes ready.\n\n - It must commit only if kp is positive.\n\n - If it commits, then it must do so with either kr items or kp items, whichever is smaller, and only if kp is positive.\n\n - It must never choose done in a synchronization after the given progress event is ready, or after done has been synchronized once.\n\n - It must not treat any data as read from the port unless done is chosen in a synchronization.\n\n - It must not block indefinitely if done is ready; it must return soon after the read completes or soon after the given progress event is ready, whichever is first.\n\n - It can report an error by raising an exception, but only if no data has been committed. In other words, no data should be lost due to an exception, including a break exception.\n\n - It must return a true value if data has been committed, #f otherwise. When it returns a value, the given progress event must be ready (perhaps because data has just been committed).\n\n - It should return a byte string as a true result when line counting is enabled and get-location is #f (so that line counting is implemented the default way); the result byte string represents the data that was committed for the purposes of character and line counting. If any other true result is returned when a byte string is expected, it is treated like a byte string where each byte corresponds to a non-newline character.\n\n - It must raise an exception if no data (including [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29)) has been peeked from the beginning of the port’s stream, or if it would have to block indefinitely to wait for the given progress event to become ready.\n\n A call to commit is [parameterize-break](breakhandler.html#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._parameterize-break%29%29)ed to disable breaks.\n\n- get-location — either #f (the default), or a procedure that takes no arguments and returns three values: the line number for the next item in the port’s stream (a positive number or #f), the column number for the next item in the port’s stream (a non-negative number or #f), and the position for the next item in the port’s stream (a positive number or #f). See also [Counting Positions, Lines, and Columns](linecol.html).\n\n This procedure is called to implement [port-next-location](linecol.html#%28def._%28%28quote._~23~25kernel%29._port-next-location%29%29), but only if line counting is enabled for the port via [port-count-lines!](linecol.html#%28def._%28%28quote._~23~25kernel%29._port-count-lines%21%29%29) (in which case count-lines! is called). The [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) and [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29) procedures assume that reading a non-whitespace character increments the column and position by one.\n\n- count-lines! — a procedure of no arguments that is called if and when line counting is enabled for the port. The default procedure is [void](void.html#%28def._%28%28quote._~23~25kernel%29._void%29%29).\n\n- init-position — normally an exact, positive integer that determines the position of the port’s first item, which is used by [file-position](port-buffers.html#%28def._%28%28quote._~23~25kernel%29._file-position%29%29) or when line counting is not enabled for the port. The default is 1. If init-position is #f, the port is treated as having an unknown position. If init-position is a port, then the given port’s position is always used for the new port’s position. If init-position is a procedure, it is called as needed to obtain the port’s position.\n\n- buffer-mode — either #f (the default) or a procedure that accepts zero or one arguments. If buffer-mode is #f, then the resulting port does not support a buffer-mode setting. Otherwise, the procedure is called with one symbol argument ('block or 'none) to set the buffer mode, and it is called with zero arguments to get the current buffer mode. In the latter case, the result must be 'block, 'none, or #f (unknown). See [Port Buffers and Positions](port-buffers.html) for more information on buffer modes.\n\n“Special” results: When read-in or peek (or an event produced by one of these) returns a procedure, the procedure is used to obtain a non-byte result. (This non-byte result is not intended to return a character or [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29); in particular, [read-char](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-char%29%29) raises an exception if it encounters a special-result procedure, even if the procedure produces a byte.) A special-result procedure must accept four arguments that represent a source location. The first argument is #f when the special read is triggered by [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) or [read/recursive](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%2Frecursive%29%29).\n\nThe special-value procedure can return an arbitrary value, and it will be called zero or one times (not necessarily before further reads or peeks from the port). See [Reader-Extension Procedures](reader-procs.html) for more details on the procedure’s result.\n\nIf read-in or peek returns a special procedure when called by any reading procedure other than [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29), [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29), [read-char-or-special](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-char-or-special%29%29), [peek-char-or-special](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._peek-char-or-special%29%29), [read-byte-or-special](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-byte-or-special%29%29), or [peek-byte-or-special](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._peek-byte-or-special%29%29), then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nExamples:\n\n> ```racket\n> ; A port with no input...\n> ; Easy: ( open-input-bytes #\"\" )\n> ; Hard:\n> > ( define /dev/null-in ( make-input-port ' null ( lambda ( s ) eof ) ( lambda ( skip s progress-evt ) eof ) void ( lambda ( ) never-evt ) ( lambda ( k progress-evt done-evt ) ( error \"no successful peeks!\" ) ) ) )\n> > ( read-char /dev/null-in )\n> #\n> > ( peek-char /dev/null-in )\n> #\n> > ( read-byte-or-special /dev/null-in )\n> #\n> > ( peek-byte-or-special /dev/null-in 100 )\n> #\n> ; A port that produces a stream of 1s:\n> > ( define infinite-ones ( make-input-port ' ones ( lambda ( s ) ( bytes-set! s 0 ( char->integer #\\1 ) ) 1 ) #f void ) )\n> > ( read-string 5 infinite-ones )\n> \"11111\"\n> ; But we can ' t peek ahead arbitrarily far, because the\n> ; automatic peek must record the skipped bytes, so\n> ; we ' d run out of memory.\n> ; An infinite stream of 1s with a specific peek procedure:\n> > ( define infinite-ones ( let ( [ one! ( lambda ( s ) ( bytes-set! s 0 ( char->integer #\\1 ) ) 1 ) ] ) ( make-input-port ' ones one! ( lambda ( s skip progress-evt ) ( one! s ) ) void ) ) )\n> > ( read-string 5 infinite-ones )\n> \"11111\"\n> ; Now we can peek ahead arbitrarily far:\n> > ( peek-string 5 ( expt 2 5000 ) infinite-ones )\n> \"11111\"\n> ; The port doesn ' t supply procedures to implement progress events:\n> > ( port-provides-progress-evts? infinite-ones )\n> #f\n> > ( port-progress-evt infinite-ones )\n> port-progress-evt: port does not provide progress evts\n> port: #\n> ; Non-byte port results:\n> > ( define infinite-voids ( make-input-port ' voids ( lambda ( s ) ( lambda args ' void ) ) ( lambda ( skip s evt ) ( lambda args ' void ) ) void ) )\n> > ( read-char infinite-voids )\n> read-char: non-character in an unsupported context\n> port: #\n> > ( read-char-or-special infinite-voids )\n> 'void\n> ; This port produces 0, 1, 2, 0, 1, 2, etc., but it is not\n> ; thread-safe, because multiple threads might read and change n .\n> > ( define mod3-cycle/one-thread ( let* ( [ n 2 ] [ mod! ( lambda ( s delta ) ( bytes-set! s 0 ( + 48 ( modulo ( + n delta ) 3 ) ) ) 1 ) ] ) ( make-input-port ' mod3-cycle/not-thread-safe ( lambda ( s ) ( set! n ( modulo ( add1 n ) 3 ) ) ( mod! s 0 ) ) ( lambda ( s skip evt ) ( mod! s skip ) ) void ) ) )\n> > ( read-string 5 mod3-cycle/one-thread )\n> \"01201\"\n> > ( peek-string 5 ( expt 2 5000 ) mod3-cycle/one-thread )\n> \"20120\"\n> ; Same thing, but thread-safe and kill-safe, and with progress\n> ; events. Only the server thread touches the stateful part\n> ; directly. (See the output port examples for a simpler thread-safe\n> ; example, but this one is more general.)\n> > ( define ( make-mod3-cycle ) ( define read-req-ch ( make-channel ) ) ( define peek-req-ch ( make-channel ) ) ( define progress-req-ch ( make-channel ) ) ( define commit-req-ch ( make-channel ) ) ( define close-req-ch ( make-channel ) ) ( define closed? #f ) ( define n 0 ) ( define progress-sema #f ) ( define ( mod! s delta ) ( bytes-set! s 0 ( + 48 ( modulo ( + n delta ) 3 ) ) ) 1 ) ; — — — — — — — — — — — — — - ; The server has a list of outstanding commit requests, ; and it also must service each port operation (read, ; progress-evt, etc.) ( define ( serve commit-reqs response-evts ) ( apply sync ( handle-evt read-req-ch ( handle-read commit-reqs response-evts ) ) ( handle-evt progress-req-ch ( handle-progress commit-reqs response-evts ) ) ( handle-evt commit-req-ch ( add-commit commit-reqs response-evts ) ) ( handle-evt close-req-ch ( handle-close commit-reqs response-evts ) ) ( append ( map ( make-handle-response commit-reqs response-evts ) response-evts ) ( map ( make-handle-commit commit-reqs response-evts ) commit-reqs ) ) ) ) ; Read/peek request: fill in the string and commit ( define ( ( handle-read commit-reqs response-evts ) r ) ( let ( [ s ( car r ) ] [ skip ( cadr r ) ] [ ch ( caddr r ) ] [ nack ( cadddr r ) ] [ evt ( car ( cddddr r ) ) ] [ peek? ( cdr ( cddddr r ) ) ] ) ( let ( [ fail? ( and evt ( sync/timeout 0 evt ) ) ] ) ( unless ( or closed? fail? ) ( mod! s skip ) ( unless peek? ( commit! 1 ) ) ) ; Add an event to respond: ( serve commit-reqs ( cons ( choice-evt nack ( channel-put-evt ch ( if closed? 0 ( if fail? #f 1 ) ) ) ) response-evts ) ) ) ) ) ; Progress request: send a peek evt for the current ; progress-sema ( define ( ( handle-progress commit-reqs response-evts ) r ) ( let ( [ ch ( car r ) ] [ nack ( cdr r ) ] ) ( unless progress-sema ( set! progress-sema ( make-semaphore ( if closed? 1 0 ) ) ) ) ; Add an event to respond: ( serve commit-reqs ( cons ( choice-evt nack ( channel-put-evt ch ( semaphore-peek-evt progress-sema ) ) ) response-evts ) ) ) ) ; Commit request: add the request to the list ( define ( ( add-commit commit-reqs response-evts ) r ) ( serve ( cons r commit-reqs ) response-evts ) ) ; Commit handling: watch out for progress, in which case ; the response is a commit failure; otherwise, try ; to sync for a commit. In either event, remove the ; request from the list ( define ( ( make-handle-commit commit-reqs response-evts ) r ) ( let ( [ k ( car r ) ] [ progress-evt ( cadr r ) ] [ done-evt ( caddr r ) ] [ ch ( cadddr r ) ] [ nack ( cddddr r ) ] ) ; Note: we don ' t check that k is <= the sum of ; previous peeks, because the entire stream is actually ; known, but we could send an exception in that case. ( choice-evt ( handle-evt progress-evt ( lambda ( x ) ( sync nack ( channel-put-evt ch #f ) ) ( serve ( remq r commit-reqs ) response-evts ) ) ) ; Only create an event to satisfy done-evt if progress-evt ; isn ' t already ready. ; Afterward, if progress-evt becomes ready, then this ; event-making function will be called again, because ; the server controls all posts to progress-evt. ( if ( sync/timeout 0 progress-evt ) never-evt ( handle-evt done-evt ( lambda ( v ) ( commit! k ) ( sync nack ( channel-put-evt ch #t ) ) ( serve ( remq r commit-reqs ) response-evts ) ) ) ) ) ) ) ; Response handling: as soon as the respondee listens, ; remove the response ( define ( ( make-handle-response commit-reqs response-evts ) evt ) ( handle-evt evt ( lambda ( x ) ( serve commit-reqs ( remq evt response-evts ) ) ) ) ) ; Close handling: post the progress sema, if any, and set ; the closed? flag ( define ( ( handle-close commit-reqs response-evts ) r ) ( let ( [ ch ( car r ) ] [ nack ( cdr r ) ] ) ( set! closed? #t ) ( when progress-sema ( semaphore-post progress-sema ) ) ( serve commit-reqs ( cons ( choice-evt nack ( channel-put-evt ch ( void ) ) ) response-evts ) ) ) ) ; Helper for reads and post-peek commits: ( define ( commit! k ) ( when progress-sema ( semaphore-post progress-sema ) ( set! progress-sema #f ) ) ( set! n ( + n k ) ) ) ; Start the server thread: ( define server-thread ( thread ( lambda ( ) ( serve null null ) ) ) ) ; — — — — — — — — — — — — — - ; Client-side helpers: ( define ( req-evt f ) ( nack-guard-evt ( lambda ( nack ) ; Be sure that the server thread is running: ( thread-resume server-thread ( current-thread ) ) ; Create a channel to hold the reply: ( let ( [ ch ( make-channel ) ] ) ( f ch nack ) ch ) ) ) ) ( define ( read-or-peek-evt s skip evt peek? ) ( req-evt ( lambda ( ch nack ) ( channel-put read-req-ch ( list* s skip ch nack evt peek? ) ) ) ) ) ; Make the port: ( make-input-port ' mod3-cycle ; Each handler for the port just sends ; a request to the server ( lambda ( s ) ( read-or-peek-evt s 0 #f #f ) ) ( lambda ( s skip evt ) ( read-or-peek-evt s skip evt #t ) ) ( lambda ( ) ; close ( sync ( req-evt ( lambda ( ch nack ) ( channel-put progress-req-ch ( list* ch nack ) ) ) ) ) ) ( lambda ( ) ; progress-evt ( sync ( req-evt ( lambda ( ch nack ) ( channel-put progress-req-ch ( list* ch nack ) ) ) ) ) ) ( lambda ( k progress-evt done-evt ) ; commit ( sync ( req-evt ( lambda ( ch nack ) ( channel-put commit-req-ch ( list* k progress-evt done-evt ch nack ) ) ) ) ) ) ) )> > ( define mod3-cycle ( make-mod3-cycle ) )\n> > ( let ( [ result1 #f ] [ result2 #f ] ) ( let ( [ t1 ( thread ( lambda ( ) ( set! result1 ( read-string 5 mod3-cycle ) ) ) ) ] [ t2 ( thread ( lambda ( ) ( set! result2 ( read-string 5 mod3-cycle ) ) ) ) ] ) ( thread-wait t1 ) ( thread-wait t2 ) ( string-append result1 \",\" result2 ) ) )\n> \"11120,02020\"\n> > ( define s ( make-bytes 1 ) )\n> > ( define progress-evt ( port-progress-evt mod3-cycle ) )\n> > ( peek-bytes-avail! s 0 progress-evt mod3-cycle )\n> 1\n> > s\n> #\"1\"\n> > ( port-commit-peeked 1 progress-evt ( make-semaphore 1 ) mod3-cycle )\n> #t\n> > ( sync/timeout 0 progress-evt )\n> #\n> > ( peek-bytes-avail! s 0 progress-evt mod3-cycle )\n> 0\n> > ( port-commit-peeked 1 progress-evt ( make-semaphore 1 ) mod3-cycle )\n> #f\n> > ( close-input-port mod3-cycle )\n> ```\n\n> ```\n(make-output-port name\n    evt        \n    write-out        \n    close        \n   [ write-out-special        \n    get-write-evt        \n    get-write-special-evt        \n    get-location        \n    count-lines!        \n    init-position        \n    buffer-mode)   →   output-port?\n\n  name : any/c\n  evt : evt?\n   write-out   :   ( or/c\n> ( bytes? exact-nonnegative-integer?\n> exact-nonnegative-integer?\n> boolean?\n> boolean?\n> . → .\n> ( or/c exact-nonnegative-integer?\n> #f\n> evt? ) )\n> output-port? )\n\n  close : ( →  any)\n   write-out-special   :   ( or/c ( any/c boolean? boolean?\n> . → .\n> ( or/c any/c\n> #f\n> evt? ) )\n> output-port?\n> #f )   =   #f\n\n   get-write-evt   :   ( or/c\n> ( bytes? exact-nonnegative-integer?\n> exact-nonnegative-integer?\n> . → .\n> evt? )\n> #f )   =   #f\n\n   get-write-special-evt   :   ( or/c\n> ( any/c . → . evt? )\n> #f )   =   #f\n\n   get-location   :   ( or/c\n> ( → \n> ( values ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f ) ) )\n> #f )\n      =   #f\n\n  count-lines! : ( →  any) = void\n   init-position   :   ( or/c exact-positive-integer?\n> port?\n> #f\n> ( → ( or/c exact-positive-integer? #f ) ) )\n      =   1\n\n   buffer-mode   :   ( or/c ( case → \n> ( ( or/c ' block ' line ' none ) . → . any )\n> ( → ( or/c ' block ' line ' none #f ) ) )\n> #f )\n      =   #f\n```"} {"text": "# 13.1.6 String Ports\n(inclusive)\t→\t\n(-> bytes → list (subbytes s start end))```\nReturns a list whose elements are produced by calling r on in until it produces [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29).\nExamples:\n> ```racket\n> > ( define ( read-number input-port ) ( define char ( read-char input-port ) ) ( if ( eof-object? char ) char ( string->number ( string char ) ) ) )\n> > ( port->list read-number ( open-input-string \"12345\" ) )\n> '(1 2 3 4 5)\n> ```\n> ```\n(current-input-port)\t→\t\n(-> current-input-port)\n```\n(current-input-port)\t→\t\n(-> open-input-string \"hello world\")```\n\n\nReads all bytes from in and returns them as a [byte string](bytestrings.html#%28tech._byte._string%29). The input port is closed unless close? is #f.\n\nExample:\n\n> ```racket\n> > ( port->bytes ( open-input-string \"hello world\" ) )\n> #\"hello world\"\n> ```\n\nChanged in version 6.8.0.2 of package base: Added the #:close? argument.\n\n> ```\n(current-input-port)\t→\t\n(-> listof string?)\n```\n(current-input-port)\t→\t\n(-> open-input-string \"line 1\\nline 2\\n line 3\\nline 4\")```\nLike [port->lines](#%28def._%28%28lib._racket%2Fport..rkt%29._port-~3elines%29%29), but reading bytes and collecting them into lines like [read-bytes-line](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-bytes-line%29%29). The input port is closed unless close? is #f.\nExample:\n> ```racket\n> > ( port->bytes-lines ( open-input-string \"line 1\\nline 2\\n line 3\\nline 4\" ) )\n> '(#\"line 1\" #\"line 2\" #\" line 3\" #\"line 4\")\n> ```\nChanged in version 6.8.0.2 of package base: Added the #:close? argument.\n> ```"} {"text": "# 13.1.6 String Ports\n(current-output-port)\t→\t\n(-> current-output-port)\n```\nUses display on each element of lst to out, adding separator after each element.\n\n> ```\n(call-with-output-string proc)  →  string?\n  proc : (output-port? . → . any)```\n\n\nCalls proc with an output port that accumulates all output into a string, and returns the string.\n\nThe port passed to proc is like the one created by [open-output-string](stringport.html#%28def._%28%28quote._~23~25kernel%29._open-output-string%29%29), except that it is wrapped via [dup-output-port](#%28def._%28%28lib._racket%2Fport..rkt%29._dup-output-port%29%29), so that proc cannot access the port’s content using [get-output-string](stringport.html#%28def._%28%28quote._~23~25kernel%29._get-output-string%29%29). If control jumps back into proc, the port continues to accumulate new data, and [call-with-output-string](#%28def._%28%28lib._racket%2Fport..rkt%29._call-with-output-string%29%29) returns both the old data and newly accumulated data.\n\n> ```\n(call-with-output-bytes proc)  →  bytes?\n  proc : (output-port? . → . any)\n```\nLike call-with-output-string, but returns the accumulated result in a byte string instead of a string. Furthermore, the port’s content is emptied when call-with-output-bytes returns, so that if control jumps back into proc and returns a second time, only the newly accumulated bytes are returned.\n> ```\n(with-output-to-string proc)  →  string?\n  proc : ( →  any)```\nEquivalent to\n> ```racket\n> ( call-with-output-string\n> ( lambda ( p ) ( parameterize ( [ current-output-port p ] )\n> ( proc ) ) ) )\n> ```"} {"text": "# 13.1.6 String Ports\n> ```\n(with-output-to-bytes proc)  →  bytes?\n  proc : ( →  any)\n```\n(parameter)\t→\t\n(-> input-port? . → . any)```\n\n\nEquivalent to (proc ([open-input-string](stringport.html#%28def._%28%28quote._~23~25kernel%29._open-input-string%29%29) str)).\n\n> ```\n(call-with-input-bytes bstr proc)  →  any\n  bstr : bytes?\n  proc : (input-port? . → . any)\n```\nEquivalent to (proc (open-input-bytes bstr)).\n> ```\n(with-input-from-string str proc)  →  any\n  str : string?\n  proc : ( →  any)```\nEquivalent to\n> ```racket\n> ( parameterize ( [ current-input-port ( open-input-string str ) ] )\n> ( proc ) )\n> ```\n> ```\n(with-input-from-bytes bstr proc)  →  any\n  bstr : bytes?\n  proc : ( →  any)"} {"text": "# 13.1.6 String Ports\n```\n(parameter)\t→\t\n(-> map object-name in)```\n\n\nTakes any number of input ports and returns an input port. Reading from the input port draws bytes (and special non-byte values) from the given input ports in order. If close-at-eof? is true, then each port is closed when an end-of-file is encountered from the port, or when the result input port is closed. Otherwise, data not read from the returned input port remains available for reading in its original input port.\n\nThe name argument determines the name as reported by [object-name](inspectors.html#%28def._%28%28quote._~23~25kernel%29._object-name%29%29) for the returned input port.\n\nSee also [merge-input](#%28def._%28%28lib._racket%2Fport..rkt%29._merge-input%29%29), which interleaves data from multiple input ports as it becomes available.\n\nChanged in version 6.90.0.19 of package base: Added the name argument.\n\n> ```\n(make-input-port/read-to-peek name\n    read-in        \n    fast-peek        \n    close        \n   [ get-location        \n    count-lines!        \n    init-position        \n    buffer-mode        \n    buffering?        \n    on-consumed)   →   input-port?\n\n  name : any/c\n   read-in   :   ( bytes?\n> . → . ( or/c exact-nonnegative-integer?\n> eof-object?\n> procedure?\n> evt? ) )\n\n   fast-peek   :   ( or/c #f\n> ( bytes? exact-nonnegative-integer?\n> ( bytes? exact-nonnegative-integer?\n> . → . ( or/c exact-nonnegative-integer?\n> eof-object?\n> procedure?\n> evt?\n> #f ) )\n> . → . ( or/c exact-nonnegative-integer?\n> eof-object?\n> procedure?\n> evt?\n> #f ) ) )\n\n  close : ( →  any)\n   get-location   :   ( or/c\n> ( → \n> ( values\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f ) ) )\n> #f )   =   #f\n\n  count-lines! : ( →  any) = void\n  init-position : exact-positive-integer? = 1\n   buffer-mode   :   ( or/c ( case → ( ( or/c ' block ' none ) . → . any )\n> ( → ( or/c ' block ' none #f ) ) )\n> #f )\n      =   #f\n\n  buffering? : any/c = #f\n   on-consumed   :   ( or/c ( ( or/c exact-nonnegative-integer? eof-object?\n> procedure? evt? )\n> . → . any )\n> #f )\n      =   #f\n```"} {"text": "# 13.1.6 String Ports\nSimilar to make-input-port, but if the given read-in returns an event, the event’s value must be 0. The resulting port’s peek operation is implemented automatically (in terms of read-in) in a way that can handle special non-byte values. The progress-event and commit operations are also implemented automatically. The resulting port is thread-safe, but not kill-safe (i.e., if a thread is terminated or suspended while using the port, the port may become damaged).\nThe read-in, close, get-location, count-lines!, init-position, and buffer-mode procedures are the same as for make-input-port.\nThe fast-peek argument can be either #f or a procedure of three arguments: a byte string to receive a peek, a skip count, and a procedure of two arguments. The fast-peek procedure can either implement the requested peek, or it can dispatch to its third argument to implement the peek. The fast-peek is not used when a peek request has an associated progress event.\nThe buffering? argument determines whether read-in can be called to read more characters than are immediately demanded by the user of the new port. If buffer-mode is not #f, then buffering? determines the initial buffer mode, and buffering? is enabled after a buffering change only if the new mode is 'block.\nIf on-consumed is not #f, it is called when data is read (or committed) from the port, as opposed to merely peeked. The argument to on-consumed is the result value of the port’s reading procedure, so it can be an integer or any result from read-in.\n> ```"} {"text": "# 13.1.6 String Ports\n(make-limited-input-port in\n    limit        \n   [ close-orig?)   →   input-port?\n  in : input-port?\n  limit : exact-nonnegative-integer?\n  close-orig? : any/c = #t```\nReturns a port whose content is drawn from in, but where an end-of-file is reported after limit bytes (and non-byte special values) have been read. If close-orig? is true, then the original port is closed if the returned port is closed.\nBytes are consumed from in only when they are consumed from the returned port. In particular, peeking into the returned port peeks into the original port.\nIf in is used directly while the resulting port is also used, then the limit bytes provided by the port need not be contiguous parts of the original port’s stream.\n> ```\n(make-pipe-with-specials [limit\n    in-name        \n    out-name)   →   input-port?   output-port?\n  limit : exact-nonnegative-integer? = #f\n  in-name : any/c = 'pipe\n  out-name : any/c = 'pipe"} {"text": "# 13.1.6 String Ports\n```\nReturns two ports: an input port and an output port. The ports behave like those returned by make-pipe, except that the ports support non-byte values written with procedures such as write-special and read with procedures such as get-byte-or-special.\n\nThe limit argument determines the maximum capacity of the pipe in bytes, but this limit is disabled if special values are written to the pipe before limit is reached. The limit is re-enabled after the special value is read from the pipe.\n\nThe optional in-name and out-name arguments determine the names of the result ports.\n\n> ```\n(combine-output a-out b-out)  →  output-port?\n  a-out : output-port?\n  b-out : output-port?```\n\n\nAccepts two output ports and returns a new output port combining the original ports. When written to, the combined port first writes as many bytes as possible to a-out, and then tries to write the same number of bytes to b-out. If that doesn’t succeed, what is left over is buffered and no further writes can go through until the ports are evened out. The port is ready (for the purposes of synchronization) when each port reports being ready. However, the first port may stop being ready while waiting on the second port to sync, so it cannot be guaranteed that both ports are ready at once. Closing the combined port is done after writing all remaining bytes to b-out.\n\nAdded in version 7.7.0.10 of package base.\n\n> ```\n(merge-input a-in b-in [buffer-limit) → input-port?\n  a-in : input-port?\n  b-in : input-port?\n  buffer-limit : (or/c exact-nonnegative-integer? #f) = 4096\n```"} {"text": "# 13.1.6 String Ports\nAccepts two input ports and returns a new input port. The new port merges the data from two original ports, so data can be read from the new port whenever it is available from either of the two original ports. The data from the original ports are interleaved. When an end-of-file has been read from an original port, it no longer contributes characters to the new port. After an end-of-file has been read from both original ports, the new port returns end-of-file. Closing the merged port does not close the original ports.\nThe optional buffer-limit argument limits the number of bytes to be buffered from a-in and b-in, so that the merge process does not advance arbitrarily beyond the rate of consumption of the merged data. A #f value disables the limit. As for make-pipe-with-specials, buffer-limit does not apply when a special value is produced by one of the input ports before the limit is reached.\nSee also input-port-append, which concatenates input streams instead of interleaving them.\n> ```\n(open-output-nowhere [name special-ok?) → output-port?\n  name : any/c = 'nowhere\n  special-ok? : any/c = #t```\nCreates and returns an output port that discards all output sent to it (without blocking). The name argument is used as the port’s name. If the special-ok? argument is true, then the resulting port supports [write-special](Byte_and_String_Output.html#%28def._%28%28quote._~23~25kernel%29._write-special%29%29), otherwise it does not.\n> ```\n(open-input-nowhere [name) → input-port?\n  name : any/c = 'nowhere"} {"text": "# 13.1.6 String Ports\n```\nCreates and returns an input port that always returns eof (without blocking). The name argument is used as the port’s name.\n\nAdded in version 8.15.0.2 of package base.\n\n> ```\n(peeking-input-port in\n   [ name  \n    skip  \n    #:init-position init-position)  \n\n  →  input-port?\n  in : input-port?\n  name : any/c = (object-name in)\n  skip : exact-nonnegative-integer? = 0\n  init-position : exact-positive-integer? = 1```\n\n\nReturns an input port whose content is determined by peeking into in. In other words, the resulting port contains an internal skip count, and each read of the port peeks into in with the internal skip count, and then increments the skip count according to the amount of data successfully peeked.\n\nThe optional name argument is the name of the resulting port. The skip argument is the port initial skip count, and it defaults to 0.\n\nThe resulting port’s initial position (as reported by [file-position](port-buffers.html#%28def._%28%28quote._~23~25kernel%29._file-position%29%29)) is ([-](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._-%29%29) init-position 1), no matter the position of in.\n\nThe resulting port supports buffering, and a 'block buffer mode allows the port to peek further into in than requested. The resulting port’s initial buffer mode is 'block, unless in supports buffer mode and its mode is initially 'none (i.e., the initial buffer mode is taken from in when it supports buffering). If in supports buffering, adjusting the resulting port’s buffer mode via [file-stream-buffer-mode](port-buffers.html#%28def._%28%28quote._~23~25kernel%29._file-stream-buffer-mode%29%29) adjusts in’s buffer mode.\n\nFor example, when you read from a peeking port, you see the same answers as when you read from the original port:\n\nExamples:\n\n> ```racket\n> > ( define an-original-port ( open-input-string \"123456789\" ) )\n> > ( define a-peeking-port ( peeking-input-port an-original-port ) )\n> > ( file-stream-buffer-mode a-peeking-port ' none )\n> > ( read-string 3 a-peeking-port )\n> \"123\"\n> > ( read-string 3 an-original-port )\n> \"123\"\n> ```\n\nBeware that the read from the original port is invisible to the peeking port, which keeps its own separate internal counter, and thus interleaving reads on the two ports can produce confusing results. Continuing the example before, if we read three more characters from the peeking port, we end up skipping over the 456 in the port (but only because we disabled buffering above):\n\nExample:\n\n> ```racket\n> > ( read-string 3 a-peeking-port )\n> \"789\"\n> ```\n\nIf we had left the buffer mode of a-peeking-port alone, that last [read-string](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-string%29%29) would have likely produced \"456\" as a result of buffering bytes from an-original-port earlier.\n\nChanged in version 6.1.0.3 of package base: Enabled buffering and buffer-mode adjustments via [file-stream-buffer-mode](port-buffers.html#%28def._%28%28quote._~23~25kernel%29._file-stream-buffer-mode%29%29), and set the port’s initial buffer mode to that of in.\n\n> ```\n(reencode-input-port in\n    encoding        \n   [ error-bytes        \n    close?        \n    name        \n    convert-newlines?        \n    enc-error)   →   input-port?\n\n  in : input-port?\n  encoding : string?\n  error-bytes : (or/c #f bytes?) = #f\n  close? : any/c = #f\n  name : any/c = (object-name in)\n  convert-newlines? : any/c = #f\n   enc-error   :   (string? input-port? . → . any)\n      =   (lambda (msg port) (error ...))\n```"} {"text": "# 13.1.6 String Ports\nProduces an input port that draws bytes from in, but converts the byte stream using (bytes-open-converter encoding-str \"UTF-8\"). In addition, if convert-newlines? is true, then decoded sequences that correspond to UTF-8 encodings of \"\\\\r\\\\n\", \"\\\\r\\\\u0085\", \"\\\\r\", \"\\\\u0085\", and \"\\\\u2028\" are all converted to the UTF-8 encoding of \"\\\\n\".\nIf error-bytes is provided and not #f, then the given byte sequence is used in place of bytes from in that trigger conversion errors. Otherwise, if a conversion is encountered, enc-error is called, which must raise an exception.\nIf close? is true, then closing the result input port also closes in. The name argument is used as the name of the result input port.\nIn non-buffered mode, the resulting input port attempts to draw bytes from in only as needed to satisfy requests. Toward that end, the input port assumes that at least n bytes must be read to satisfy a request for n bytes. (This is true even if the port has already drawn some bytes, as long as those bytes form an incomplete encoding sequence.)\n> ```\n(reencode-output-port out\n    encoding        \n   [ error-bytes        \n    close?        \n    name        \n    newline-bytes        \n    enc-error)   →   output-port?\n  out : output-port?\n  encoding : string?\n  error-bytes : (or/c #f bytes?) = #f\n  close? : any/c = #f\n  name : any/c = (object-name out)\n  newline-bytes : (or/c #f bytes?) = #f\n   enc-error   :   (string? output-port? . → . any)\n      =   (lambda (msg port) (error ...))```"} {"text": "# 13.1.6 String Ports\nProduces an output port that directs bytes to out, but converts its byte stream using ([bytes-open-converter](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29) \"UTF-8\" encoding-str). In addition, if newline-bytes is not #f, then bytes written to the port that are the UTF-8 encoding of \"\\\\n\" are first converted to newline-bytes (before applying the convert from UTF-8 to encoding-str).\nIf error-bytes is provided and not #f, then the given byte sequence is used in place of bytes that have been sent to the output port and that trigger conversion errors. Otherwise, enc-error is called, which must raise an exception.\nIf close? is true, then closing the result output port also closes out. The name argument is used as the name of the result output port.\nThe resulting port supports buffering, and the initial buffer mode is ([or](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29) ([file-stream-buffer-mode](port-buffers.html#%28def._%28%28quote._~23~25kernel%29._file-stream-buffer-mode%29%29) out) 'block). In 'block mode, the port’s buffer is flushed only when it is full or a flush is requested explicitly. In 'line mode, the buffer is flushed whenever a newline or carriage-return byte is written to the port. In 'none mode, the port’s buffer is flushed after every write. Implicit flushes for 'line or 'none leave bytes in the buffer when they are part of an incomplete encoding sequence."} {"text": "# 13.1.6 String Ports\nThe resulting output port does not support atomic writes. An explicit flush or special-write to the output port can hang if the most recently written bytes form an incomplete encoding sequence.\nWhen the port is buffered, a [flush callback](plumbers.html#%28tech._flush._callback%29) is registered with the [current plumber](plumbers.html#%28tech._current._plumber%29) to flush the buffer.\n> ```\n(dup-input-port in [close?) → input-port?\n  in : input-port?\n  close? : any/c = #f\n```\nReturns an input port that draws directly from in. Closing the resulting port closes in only if close? is #t.\n\nThe new port is initialized with the port read handler of in, but setting the handler on the result port does not affect reading directly from in.\n\n> ```\n(dup-output-port out [close?) → output-port?\n  out : output-port?\n  close? : any/c = #f```\n\n\nReturns an output port that propagates data directly to out. Closing the resulting port closes out only if close? is #t.\n\nThe new port is initialized with the [port display handler](Writing.html#%28tech._port._display._handler%29) and [port write handler](Writing.html#%28tech._port._write._handler%29) of out, but setting the handlers on the result port does not affect writing directly to out.\n\n> ```\n(relocate-input-port in\n    line        \n    column        \n    position        \n   [ close?]        \n    #:name name)   →   input-port?\n\n  in : input-port?\n  line : (or/c exact-positive-integer? #f)\n  column : (or/c exact-nonnegative-integer? #f)\n  position : exact-positive-integer?\n  close? : any/c = #t\n  name : (object-name in)\n```"} {"text": "# 13.1.6 String Ports\nProduces an input port that is equivalent to in except in how it reports location information (and possibly its name). The resulting port’s content starts with the remaining content of in, and it starts at the given line, column, and position. A #f for the line or column means that the line and column will always be reported as #f.\nThe line and column values are used only if line counting is enabled for in and for the resulting port, typically through port-count-lines!. The column value determines the column for the first line (i.e., the one numbered line), and later lines start at column 0. The given position is used even if line counting is not enabled.\nWhen line counting is on for the resulting port, reading from in instead of the resulting port increments location reports from the resulting port. Otherwise, the resulting port’s position does not increment when data is read from in.\nIf close? is true, then closing the resulting port also closes in. If close? is #f, then closing the resulting port does not close in.\nThe name argument is used as the name for the resulting port; the default value keeps the same name as in.\n> ```\n(relocate-output-port out\n    line        \n    column        \n    position        \n   [ close?]        \n    #:name name)   →   output-port?\n  out : output-port?\n  line : (or/c exact-positive-integer? #f)\n  column : (or/c exact-nonnegative-integer? #f)\n  position : exact-positive-integer?\n  close? : any/c = #t\n  name : (object-name out)```"} {"text": "# 13.1.6 String Ports\nLike [relocate-input-port](#%28def._%28%28lib._racket%2Fport..rkt%29._relocate-input-port%29%29), but for output ports.\n> ```\n(transplant-input-port in\n    get-location        \n    init-pos        \n   [ close?        \n    count-lines!]        \n    #:name name)   →   input-port?\n  in : input-port?\n   get-location   :   ( or/c\n> ( → \n> ( values\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f ) ) )\n> #f )\n  init-pos : exact-positive-integer?\n  close? : any/c = #t\n  count-lines! : ( →  any) = void\n  name : (object-name in)"} {"text": "# 13.1.6 String Ports\n```\nLike relocate-input-port, except that arbitrary position information can be produced (when line counting is enabled) via get-location, which is used as for make-input-port. If get-location is #f, then the port counts lines in the usual way starting from init-pos, independent of locations reported by in.\n\nIf count-lines! is supplied, it is called when line counting is enabled for the resulting port. The default is void.\n\n> ```\n(transplant-output-port out\n    get-location        \n    init-pos        \n   [ close?        \n    count-lines!]        \n    #:name name)   →   output-port?\n\n  out : output-port?\n   get-location   :   ( or/c\n> ( → \n> ( values\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f ) ) )\n> #f )\n\n  init-pos : exact-positive-integer?\n  close? : any/c = #t\n  count-lines! : ( →  any) = void\n  name : (object-name out)```\n\n\nLike [transplant-input-port](#%28def._%28%28lib._racket%2Fport..rkt%29._transplant-input-port%29%29), but for output ports.\n\n> ```\n(filter-read-input-port in\n    read-wrap        \n    peek-wrap        \n   [ close?)   →   input-port?\n\n  in : input-port?\n   read-wrap   :   ( bytes? ( or/c exact-nonnegative-integer?\n> eof-object?\n> procedure?\n> evt? )\n> . → .\n> ( or/c exact-nonnegative-integer?\n> eof-object?\n> procedure?\n> evt? ) )\n\n   peek-wrap   :   ( bytes? exact-nonnegative-integer? ( or/c evt? #f )\n> ( or/c exact-nonnegative-integer?\n> eof-object?\n> procedure?\n> evt?\n> #f )\n> . → . ( or/c exact-nonnegative-integer?\n> eof-object?\n> procedure?\n> evt?\n> #f ) )\n\n  close? : any/c = #t\n```"} {"text": "# 13.1.6 String Ports\nCreates a port that draws from in, but each result from the port’s read and peek procedures (in the sense of make-input-port) is filtered by read-wrap and peek-wrap. The filtering procedures each receive both the arguments and results of the read and peek procedures on in for each call.\nIf close? is true, then closing the resulting port also closes in.\n> ```\n(special-filter-input-port in proc [close?) → input-port?\n  in : input-port?\n   proc   :   ( procedure? bytes? . → . ( or/c exact-nonnegative-integer?\n> eof-object?\n> procedure?\n> evt? ) )\n  close? : any/c = #t```\nProduces an input port that is equivalent to in, except that when in produces a procedure to access a special value, proc is applied to the procedure to allow the special value to be replaced with an alternative. The proc is called with the special-value procedure and the byte string that was given to the port’s read or peek function (see [make-input-port](customport.html#%28def._%28%28quote._~23~25kernel%29._make-input-port%29%29)), and the result is used as the read or peek function’s result. The proc can modify the byte string to substitute a byte for the special value, but the byte string is guaranteed only to hold at least one byte.\nIf close? is true, then closing the resulting input port also closes in."} {"text": "##### 13.1.10.3 Port Events\n> ```\n(eof-evt in)  →  evt?\n  in : input-port?\n```\nReturns a synchronizable event that is ready when in produces an eof. If in produces a mid-stream eof, the eof is consumed by the event only if the event is chosen in a synchronization.\n\nIf attempting to read from in raises an exception during a synchronization attempt, then the exception may be reported during the synchronization attempt, but it will silently discarded if some another event in the same synchronization is selected or if some other event raises an exception first.\n\nChanged in version 7.5.0.3 of package base: Changed handling of read errors so they are propagated to a synchronization attempt, instead of treated as unhandled errors in a background thread.\n\n> ```\n(read-bytes-evt k in)  →  evt?\n  k : exact-nonnegative-integer?\n  in : input-port?```\n\n\nReturns a [synchronizable event](sync.html#%28tech._synchronizable._event%29) that is ready when k bytes can be read from in, or when an end-of-file is encountered in in. If k is 0, then the event is ready immediately with \"\". For non-zero k, if no bytes are available before an end-of-file, the event’s result is [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29). Otherwise, the event’s result is a byte string of up to k bytes, which contains as many bytes as are available (up to k) before an available end-of-file. (The result is a byte string of less than k bytes only when an end-of-file is encountered.)\n\nBytes are read from the port if and only if the event is chosen in a synchronization, and the returned bytes always represent contiguous bytes in the port’s stream.\n\nThe event can be synchronized multiple times—even concurrently—and each synchronization corresponds to a distinct read request.\n\nThe in must support progress events, and it must not produce a special non-byte value during the read attempt.\n\nExceptions attempting to read from in are handled in the same way as by [eof-evt](#%28def._%28%28lib._racket%2Fport..rkt%29._eof-evt%29%29).\n\n> ```\n(read-bytes!-evt bstr in)  →  evt?\n  bstr : (and/c bytes? (not/c immutable?))\n  in : input-port?\n```"} {"text": "# 13.1.6 String Ports\nLike read-bytes-evt, except that the read bytes are placed into bstr, and the number of bytes to read corresponds to (bytes-length bstr). The event’s result is either eof or the number of read bytes.\nThe bstr may be mutated any time after the first synchronization attempt on the event and until either the event is selected, a non-#f progress-evt is ready, or the current custodian (at the time of synchronization) is shut down. Note that there is no time bound otherwise on when bstr might be mutated if the event is not selected by a synchronzation; nevertheless, multiple synchronization attempts can use the same result from read-bytes!-evt as long as there is no intervening read on in until one of the synchronization attempts selects the event.\nExceptions attempting to read from in are handled in the same way as by eof-evt.\n> ```\n(read-bytes-avail!-evt bstr in)  →  evt?\n  bstr : (and/c bytes? (not/c immutable?))\n  in : input-port?```\nLike [read-bytes!-evt](#%28def._%28%28lib._racket%2Fport..rkt%29._read-bytes%21-evt%29%29), except that the event reads only as many bytes as are immediately available, after at least one byte or one [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29) becomes available.\n> ```\n(read-string-evt k in)  →  evt?\n  k : exact-nonnegative-integer?\n  in : input-port?"} {"text": "# 13.1.6 String Ports\n```\nLike read-bytes-evt, but for character strings instead of byte strings.\n\n> ```\n(read-string!-evt str in)  →  evt?\n  str : (and/c string? (not/c immutable?))\n  in : input-port?```\n\n\nLike [read-bytes!-evt](#%28def._%28%28lib._racket%2Fport..rkt%29._read-bytes%21-evt%29%29), but for a character string instead of a byte string.\n\n> ```\n(read-line-evt in [mode) → evt?\n  in : input-port?\n   mode   :   (or/c 'linefeed 'return 'return-linefeed 'any 'any-one)\n      =   'linefeed\n```\nReturns a synchronizable event that is ready when a line of characters or end-of-file can be read from in. The meaning of mode is the same as for read-line. The event result is the read line of characters (not including the line separator).\nA line is read from the port if and only if the event is chosen in a synchronization, and the returned line always represents contiguous bytes in the port’s stream.\nExceptions attempting to read from in are handled in the same way as by eof-evt.\n> ```\n(read-bytes-line-evt in [mode) → evt?\n  in : input-port?\n   mode   :   (or/c 'linefeed 'return 'return-linefeed 'any 'any-one)\n      =   'linefeed```\nLike [read-line-evt](#%28def._%28%28lib._racket%2Fport..rkt%29._read-line-evt%29%29), but returns a byte string instead of a string.\n> ```"} {"text": "# 13.1.6 String Ports\n(peek-bytes-evt k skip progress-evt in)  →  evt?\n  k : exact-nonnegative-integer?\n  skip : exact-nonnegative-integer?\n  progress-evt : (or/c progress-evt? #f)\n  in : input-port?\n(peek-bytes!-evt bstr skip progress-evt in)  →  evt?\n  bstr : (and/c bytes? (not/c immutable?))\n  skip : exact-nonnegative-integer?\n  progress-evt : (or/c progress-evt? #f)\n  in : input-port?\n(peek-bytes-avail!-evt   bstr        \n    skip        \n    progress-evt        \n    in)   →   evt?\n  bstr : (and/c bytes? (not/c immutable?))\n  skip : exact-nonnegative-integer?\n  progress-evt : (or/c progress-evt? #f)\n  in : input-port?\n(peek-string-evt k skip progress-evt in)  →  evt?\n  k : exact-nonnegative-integer?\n  skip : exact-nonnegative-integer?\n  progress-evt : (or/c progress-evt? #f)\n  in : input-port?\n(peek-string!-evt str skip progress-evt in)  →  evt?\n  str : (and/c string? (not/c immutable?))\n  skip : exact-nonnegative-integer?\n  progress-evt : (or/c progress-evt? #f)\n  in : input-port?"} {"text": "# 13.1.6 String Ports\n```\nLike the read-bytes-evt, etc., functions, but for peeking. The skip argument indicates the number of bytes to skip, and progress-evt indicates an event that effectively cancels the peek (so that the event never becomes ready). The progress-evt argument can be #f, in which case the event is never canceled.\n\n> ```\n(regexp-match-evt pattern in)  →  any\n  pattern : (or/c string? bytes? regexp? byte-regexp?)\n  in : input-port?```\n\n\nReturns a [synchronizable event](sync.html#%28tech._synchronizable._event%29) that is ready when pattern matches the stream of bytes/characters from in; see also [regexp-match](regexp.html#%28def._%28%28quote._~23~25kernel%29._regexp-match%29%29). The event’s value is the result of the match, in the same form as the result of [regexp-match](regexp.html#%28def._%28%28quote._~23~25kernel%29._regexp-match%29%29).\n\nIf pattern does not require a start-of-stream match, then bytes skipped to complete the match are read and discarded when the event is chosen in a synchronization.\n\nBytes are read from the port if and only if the event is chosen in a synchronization, and the returned match always represents contiguous bytes in the port’s stream. If not-yet-available bytes from the port might contribute to the match, the event is not ready. Similarly, if pattern begins with a start-of-stream ^ and the pattern does not initially match, then the event cannot become ready until bytes have been read from the port.\n\nThe event can be synchronized multiple times—even concurrently—and each synchronization corresponds to a distinct match request.\n\nThe in port must support progress events. If in returns a special non-byte value during the match attempt, it is treated like [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29).\n\nExceptions attempting to read from in are handled in the same way as by [eof-evt](#%28def._%28%28lib._racket%2Fport..rkt%29._eof-evt%29%29).\n\n##### 13.1.10.4 Copying Streams\n\n> ```\n(parameter)\t→\n```"} {"text": "# 13.1.6 String Ports\n(parameter)\t→```\nReads data from in and writes it back out to out, returning when in produces [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29). The copy is efficient, and it is without significant buffer delays (i.e., a byte that becomes available on in is immediately transferred to out, even if future reads on in must block). If in produces a special non-byte value, it is transferred to out using [write-special](Byte_and_String_Output.html#%28def._%28%28quote._~23~25kernel%29._write-special%29%29).\nThis function is often called from a “background” thread to continuously pump data from one stream to another.\nIf multiple outs are provided, data from in is written to every out. The different outs block output to each other, because each block of data read from in is written completely to one out before moving to the next out. The outs are written in the provided order, so non-blocking ports (e.g., file output ports) should be placed first in the argument list.\n------------------------------------------------------------------------"} {"text": "# 13.2 Byte and String Input"} {"text": "### 13.2 Byte and String Input\n> ```\n(current-input-port)\t→\t\n(-> or/c char? eof-object?)\n```\n(current-input-port)\t→\t\n(-> or/c byte? eof-object?)```\n\n\nReads a single byte from in. If no bytes are available before an end-of-file, then [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29) is returned.\n\nExamples:\n\n> ```racket\n> > ( let ( [ ip ( open-input-string \"a\" ) ] ) ; The two values in the following list should be the same. ( list ( read-byte ip ) ( char->integer #\\a ) ) )\n> '(97 97)\n> > ( let ( [ ip ( open-input-string ( string #\\λ ) ) ] ) ; This string has a two byte-encoding. ( list ( read-byte ip ) ( read-byte ip ) ( read-byte ip ) ) )\n> '(206 187 #)\n> ```\n\n> ```\n(current-input-port)\t→\t\n(-> or/c string? eof-object?)\n```\n(s)\t→\t\n(-> or/c bytes? eof-object?)```\nLike [read-line](#%28def._%28%28quote._~23~25kernel%29._read-line%29%29), but reads bytes and produces a byte string.\n> ```\n(current-input-port)\t→\t\n(-> or/c string? eof-object?)"} {"text": "# 13.2 Byte and String Input\n```\n(current-input-port)\t→\t\n(-> A temporary string of size amt is allocated while reading the input, even if the size of the result is less than amt characters.)```\n\n\n> > > To read an entire port as bytes, use [port->bytes](port-lib.html#%28def._%28%28lib._racket%2Fport..rkt%29._port-~3ebytes%29%29).\n\nLike [read-string](#%28def._%28%28quote._~23~25kernel%29._read-string%29%29), but reads bytes and produces a byte string.\n\nExample:\n\n> ```racket\n> > ( let ( [ ip ( open-input-bytes ( bytes 6 115 101 99 114 101 116 ) ) ] ) ( define length ( read-byte ip ) ) ( bytes->string/utf-8 ( read-bytes length ip ) ) )\n> \"secret\"\n> ```\n\n> ```\n(current-input-port)\t→\t\n(-> or/c exact-nonnegative-integer? eof-object?)\n```\n(inclusive)\t→\t\n(-> or/c exact-nonnegative-integer? eof-object?)```\nLike [read-string!](#%28def._%28%28quote._~23~25kernel%29._read-string%21%29%29), but reads bytes, puts them into a byte string, and returns the number of bytes read.\nExample:\n> ```racket\n> > ( let ( [ buffer ( make-bytes 10 ( char->integer #\\_ ) ) ] [ ip ( open-input-string \"cketRa\" ) ] ) ( printf \"~s\\n\" buffer ) ( read-bytes! buffer ip 2 6 ) ( printf \"~s\\n\" buffer ) ( read-bytes! buffer ip 0 2 ) ( printf \"~s\\n\" buffer ) )\n> #\"__________\" #\"__cket____\" #\"Racket____\"\n> ```\n> ```\n(current-input-port)\t→\t\n(-> or/c exact-nonnegative-integer? eof-object? procedure?)"} {"text": "# 13.2 Byte and String Input\n```\n(current-input-port)\t→\t\n(-> or/c exact-nonnegative-integer? eof-object? procedure?)```\n\n\nLike [read-bytes-avail!](#%28def._%28%28quote._~23~25kernel%29._read-bytes-avail%21%29%29), but returns 0 immediately if no bytes (or specials) are available for reading and the end-of-file is not reached.\n\n> ```\n(current-input-port)\t→\t\n(-> or/c exact-nonnegative-integer? eof-object? procedure?)\n```\n(current-input-port)\t→\t\n(-> or/c string? eof-object?)```\nSimilar to [read-string](#%28def._%28%28quote._~23~25kernel%29._read-string%29%29), except that the returned characters are [peek](ports.html#%28tech._peek%29)ed: preserved in the port for future reads and [peeks](ports.html#%28tech._peek%29). (More precisely, undecoded bytes are left for future reads and peeks.) The skip-bytes-amt argument indicates a number of bytes (not characters) in the input stream to skip before collecting characters to return; thus, in total, the next skip-bytes-amt bytes plus amt characters are inspected.\nFor most kinds of ports, inspecting skip-bytes-amt bytes and amt characters requires at least skip-bytes-amt+amt bytes of memory overhead associated with the port, at least until the bytes/characters are read. No such overhead is required when peeking into a string port (see [String Ports](stringport.html)), a pipe port (see [Pipes](pipeports.html)), or a custom port with a specific peek procedure (depending on how the peek procedure is implemented; see [Custom Ports](customport.html))."} {"text": "# 13.2 Byte and String Input\nIf a port produces [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29) mid-stream, attempts to skip beyond the [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29) for a [peek](ports.html#%28tech._peek%29) always produce [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29) until the [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29) is read.\n> ```\n(current-input-port)\t→\t\n(-> or/c bytes? eof-object?)\n```\n(current-input-port)\t→\t\n(-> or/c exact-nonnegative-integer? eof-object?)```\n\n\nLike [read-string!](#%28def._%28%28quote._~23~25kernel%29._read-string%21%29%29), but for [peek](ports.html#%28tech._peek%29)ing, and with a skip-bytes-amt argument like [peek-string](#%28def._%28%28quote._~23~25kernel%29._peek-string%29%29).\n\n> ```\n(current-input-port)\t→\t\n(-> or/c exact-nonnegative-integer? eof-object?)\n```\n(current-input-port)\t→\t\n(-> or/c exact-nonnegative-integer? eof-object? procedure?)```\nLike [read-bytes-avail!](#%28def._%28%28quote._~23~25kernel%29._read-bytes-avail%21%29%29), but for [peek](ports.html#%28tech._peek%29)ing, and with two extra arguments. The skip-bytes-amt argument is as in [peek-bytes](#%28def._%28%28quote._~23~25kernel%29._peek-bytes%29%29). The progress argument must be either #f or an event produced by [port-progress-evt](#%28def._%28%28quote._~23~25kernel%29._port-progress-evt%29%29) for in."} {"text": "# 13.2 Byte and String Input\nTo [peek](ports.html#%28tech._peek%29), [peek-bytes-avail!](#%28def._%28%28quote._~23~25kernel%29._peek-bytes-avail%21%29%29) blocks until finding an end-of-file, at least one byte (or special) past the skipped bytes, or until a non-#f progress becomes ready. Furthermore, if progress is ready before bytes are peeked, no bytes are peeked or skipped, and progress may cut short the skipping process if it becomes available during the peek attempt. Furthermore, progress is checked even before determining whether the port is still open.\nThe result of [peek-bytes-avail!](#%28def._%28%28quote._~23~25kernel%29._peek-bytes-avail%21%29%29) is 0 only\n- when start-pos is equal to end-pos, or\n- when progress becomes ready before bytes are peeked.\n> ```\n(current-input-port)\t→\t\n(-> or/c exact-nonnegative-integer? eof-object? procedure?)\n```\n(current-input-port)\t→\t\n(-> or/c exact-nonnegative-integer? eof-object? procedure?)```\n\n\nLike [read-bytes-avail!/enable-break](#%28def._%28%28quote._~23~25kernel%29._read-bytes-avail%21%2Fenable-break%29%29), but for [peek](ports.html#%28tech._peek%29)ing, and with skip-bytes-amt and progress arguments like [peek-bytes-avail!](#%28def._%28%28quote._~23~25kernel%29._peek-bytes-avail%21%29%29).\n\n> ```\n(current-input-port)\t→\t\n(-> or/c char? eof-object? any/c)\n```\n(current-input-port)\t→\t\n(-> or/c byte? eof-object? any/c)```\nLike [read-char-or-special](#%28def._%28%28quote._~23~25kernel%29._read-char-or-special%29%29), but reads and returns a byte instead of a character."} {"text": "# 13.2 Byte and String Input\nChanged in version 6.8.0.2 of package base: Added the special-wrap and source-name arguments.\n> ```\n(current-input-port)\t→\t\n(-> or/c char? eof-object?)\n```\n(current-input-port)\t→\t\n(-> or/c byte? eof-object?)```\n\n\nLike [peek-char](#%28def._%28%28quote._~23~25kernel%29._peek-char%29%29), but [peeks](ports.html#%28tech._peek%29) and returns a byte instead of a character.\n\n> ```\n(current-input-port)\t→\t\n(-> or/c char? eof-object? any/c)\n```\n(current-input-port)\t→\t\n(-> or/c byte? eof-object? any/c)```\nLike [peek-char-or-special](#%28def._%28%28quote._~23~25kernel%29._peek-char-or-special%29%29), but [peeks](ports.html#%28tech._peek%29) and returns a byte instead of a character, and it supports a progress argument like [peek-bytes-avail!](#%28def._%28%28quote._~23~25kernel%29._peek-bytes-avail%21%29%29).\nChanged in version 6.8.0.2 of package base: Added the special-wrap and source-name arguments. \nChanged in version 6.90.0.16: Added 'special as an option for special-wrap.\n> ```\n(current-input-port)\t→\t\n(-> and/c input-port? port-provides-progress-evts?)"} {"text": "# 13.2 Byte and String Input\n```\nReturns a synchronizable event (see Events) that becomes ready for synchronization after any subsequent read from in or after in is closed. After the event becomes ready, it remains ready. The synchronization result of a progress event is the progress event itself.\n\n> ```\n(port-provides-progress-evts? in)  →  boolean\n  in : input-port?```\n\n\nReturns #t if [port-progress-evt](#%28def._%28%28quote._~23~25kernel%29._port-progress-evt%29%29) can return an event for in. All built-in kinds of ports support progress events, but ports created with [make-input-port](customport.html#%28def._%28%28quote._~23~25kernel%29._make-input-port%29%29) (see [Custom Ports](customport.html)) may not.\n\n> ```\n(current-input-port)\t→\t\n(-> current-input-port)\n```\n(current-input-port)\t→\t\n(-> current-input-port)```\nReturns #t if ([read-byte](#%28def._%28%28quote._~23~25kernel%29._read-byte%29%29) in) would not block (at the time that [byte-ready?](#%28def._%28%28quote._~23~25kernel%29._byte-ready~3f%29%29) was called, at least). Equivalent to ([and](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._and%29%29) ([sync/timeout](sync.html#%28def._%28%28quote._~23~25kernel%29._sync%2Ftimeout%29%29) 0 in) #t)."} {"text": "# 13.2 Byte and String Input\nThe [byte-ready?](#%28def._%28%28quote._~23~25kernel%29._byte-ready~3f%29%29) and [char-ready?](#%28def._%28%28quote._~23~25kernel%29._char-ready~3f%29%29) functions are appropriate for relatively few applications, because ports are meant to support streaming data among concurrent producers and consumers; the fact that a byte or character is not ready in some instant does not necessarily mean that the producer is finished supplying data. (Also, if a port has multiple consumers, data might get consumed between the time that a given process uses [byte-ready?](#%28def._%28%28quote._~23~25kernel%29._byte-ready~3f%29%29) to poll the port and the time that it reads data from the port.) Using [byte-ready?](#%28def._%28%28quote._~23~25kernel%29._byte-ready~3f%29%29) makes sense if you are implementing your own scheduler or if you know that the port’s implementation and use are particularly constrained.\n> ```\n(current-input-port)\t→\t\n(-> current-input-port)"} {"text": "# 13.2 Byte and String Input\n```\nReturns #t if (read-char in) would not block (at the time that char-ready? was called, at least). Depending on the initial bytes of the stream, multiple bytes may be needed to form a UTF-8 encoding.\n\nSee byte-ready? for a note on how byte-ready? and char-ready? are rarely the right choice.\n\n> ```\n(progress-evt? v)  →  boolean?\n  v : any/c\n(progress-evt? evt in)  →  boolean?\n  evt : progress-evt?\n  in : input-port?```\n\n\nWith one argument, returns #t is v is a progress evt for some input port, #f otherwise.\n\nWith two arguments, returns #t if evt is a progress event for in, #f otherwise.\n\n------------------------------------------------------------------------\n\n# 13.3 Byte and String Output\n\n### 13.3 Byte and String Output\n\n> ```\n(current-output-port)\t→\t\n(-> current-output-port)\n```\n(current-output-port)\t→\t\n(-> current-output-port)```\nWrites a single byte to out.\n> ```\n(current-output-port)\t→\t\n(-> current-output-port)"} {"text": "# 13.2 Byte and String Input\n```\n(current-output-port)\t→\t\n(-> current-output-port)```\n\n\nWrites characters to out from str starting from index start-pos (inclusive) up to end-pos (exclusive). Like [substring](strings.html#%28def._%28%28quote._~23~25kernel%29._substring%29%29), the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised if start-pos or end-pos is out-of-range for str.\n\nThe result is the number of characters written to out, which is always ([-](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._-%29%29) end-pos start-pos).\n\nIf str is mutable, mutations after [write-string](#%28def._%28%28quote._~23~25kernel%29._write-string%29%29) returns do not affect the characters written to out. (This independence from mutation is not a special property of [write-string](#%28def._%28%28quote._~23~25kernel%29._write-string%29%29), but instead generally true of output functions.)\n\n> ```\n(current-output-port)\t→\t\n(-> current-output-port)\n```\n(current-output-port)\t→\t\n(-> current-output-port)```"} {"text": "# 13.2 Byte and String Input\nLike [write-bytes](#%28def._%28%28quote._~23~25kernel%29._write-bytes%29%29), but returns without blocking after writing as many bytes as it can immediately flush. It blocks only if no bytes can be flushed immediately. The result is the number of bytes written and flushed to out; if start-pos is the same as end-pos, then the result can be 0 (indicating a successful flush of any buffered data), otherwise the result is between 1 and ([-](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._-%29%29) end-pos start-pos), inclusive.\nThe [write-bytes-avail](#%28def._%28%28quote._~23~25kernel%29._write-bytes-avail%29%29) procedure never drops bytes; if [write-bytes-avail](#%28def._%28%28quote._~23~25kernel%29._write-bytes-avail%29%29) successfully writes some bytes and then encounters an error, it suppresses the error and returns the number of written bytes. (The error will be triggered by future writes.) If an error is encountered before any bytes have been written, an exception is raised.\n> ```\n(current-output-port)\t→\t\n(-> or/c exact-nonnegative-integer? #f)"} {"text": "# 13.2 Byte and String Input\n```\n(current-output-port)\t→\t\n(-> current-output-port)```\n\n\nLike [write-bytes-avail](#%28def._%28%28quote._~23~25kernel%29._write-bytes-avail%29%29), except that breaks are enabled during the write. The procedure provides a guarantee about the interaction of writing and breaks: if breaking is disabled when [write-bytes-avail/enable-break](#%28def._%28%28quote._~23~25kernel%29._write-bytes-avail%2Fenable-break%29%29) is called, and if the [exn:break](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak%29%29) exception is raised as a result of the call, then no bytes will have been written to out. See also [Breaks](breakhandler.html).\n\n> ```\n(current-output-port)\t→\t\n(-> current-output-port)\n```\n(current-output-port)\t→\t\n(-> current-output-port)```\nLike [write-special](#%28def._%28%28quote._~23~25kernel%29._write-special%29%29), but without blocking. If v cannot be written immediately, the result is #f without writing v, otherwise the result is #t and v is written.\n> ```\n(current-output-port)\t→\t\n(-> current-output-port)"} {"text": "# 13.2 Byte and String Input\n```\n(unbuffered)\t→\t\n(-> current-output-port)```\n\n\nSimilar to [write-special](#%28def._%28%28quote._~23~25kernel%29._write-special%29%29), but instead of writing the special value immediately, it returns a synchronizable event (see [Events](sync.html)). The out must support atomic writes, as indicated by [port-writes-atomic?](#%28def._%28%28quote._~23~25kernel%29._port-writes-atomic~3f%29%29).\n\nSynchronizing on the object starts a write of the special value, and the event becomes ready when the value is written (unbuffered) to the port. If the event is not selected in a synchronization, then no value will have been written to out.\n\n> ```\n(port-writes-atomic? out)  →  boolean?\n  out : output-port?\n```\nReturns #t if write-bytes-avail/enable-break can provide an exclusive-or guarantee (break or write, but not both) for out, and if the port can be used with procedures like write-bytes-avail-evt. Racket’s file-stream ports, pipes, string ports, and TCP ports all support atomic writes; ports created with make-output-port (see Custom Ports) may support atomic writes.\n> ```\n(port-writes-special? out)  →  boolean?\n  out : output-port?```\nReturns #t if procedures like [write-special](#%28def._%28%28quote._~23~25kernel%29._write-special%29%29) can write arbitrary values to the port. Racket’s file-stream ports, pipes, string ports, and TCP ports all reject special values, but ports created with [make-output-port](customport.html#%28def._%28%28quote._~23~25kernel%29._make-output-port%29%29) (see [Custom Ports](customport.html)) may support them."} {"text": "# 13.2 Byte and String Input\n------------------------------------------------------------------------"} {"text": "# 13.4 Reading"} {"text": "### 13.4 Reading\n> ```\n(current-input-port)\t→\t\n(-> current-input-port)\n```\n(current-input-port)\t→\t\n(-> or/c syntax? eof-object?)```\n\n\nLike [read](#%28def._%28%28quote._~23~25kernel%29._read%29%29), but produces a [syntax object](syntax-model.html#%28tech._syntax._object%29) with source-location information. The source-name is used as the source field of the syntax object; it can be an arbitrary value, but it should generally be a path for the source file.\n\nSee [The Reader](reader.html) for information on the default reader in [read-syntax](#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29) mode and [Reading via an Extension](reader.html#%28part._parse-reader%29) for the protocol of [read-syntax](#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29).\n\nTypically, line counting should be enabled for in so that source locations in syntax objects are in characters, instead of bytes. See also [Counting Positions, Lines, and Columns](linecol.html).\n\n> > > \"+\"See also [Syntax Objects](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=stx-obj.html&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13).\n\n> ```\n(current-input-port)\t→\t\n(-> current-input-port)\n```\n(current-input-port)\t→\t\n(-> object-name in)```"} {"text": "# 13.4 Reading\nAnalogous to calling [read/recursive](#%28def._%28%28quote._~23~25kernel%29._read%2Frecursive%29%29), but the resulting value encapsulates S-expression structure with source-location information. As with [read/recursive](#%28def._%28%28quote._~23~25kernel%29._read%2Frecursive%29%29), when [read-syntax/recursive](#%28def._%28%28quote._~23~25kernel%29._read-syntax%2Frecursive%29%29) is used within the dynamic extent of [read-syntax](#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29), the result from [read-syntax/recursive](#%28def._%28%28quote._~23~25kernel%29._read-syntax%2Frecursive%29%29) is either a special-comment value, end-of-file, or opaque graph-structure placeholder (not a syntax object). The placeholder can be embedded in an S-expression or syntax object returned by a reader macro, etc., and it will be replaced with the actual syntax object before the outermost [read-syntax](#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29) returns."} {"text": "# 13.4 Reading\nUsing [read/recursive](#%28def._%28%28quote._~23~25kernel%29._read%2Frecursive%29%29) within the dynamic extent of [read-syntax](#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29) does not allow graph structure for reading to be included in the outer [read-syntax](#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29) parsing, and neither does using [read-syntax/recursive](#%28def._%28%28quote._~23~25kernel%29._read-syntax%2Frecursive%29%29) within the dynamic extent of [read](#%28def._%28%28quote._~23~25kernel%29._read%29%29). In those cases, [read/recursive](#%28def._%28%28quote._~23~25kernel%29._read%2Frecursive%29%29) and [read-syntax/recursive](#%28def._%28%28quote._~23~25kernel%29._read-syntax%2Frecursive%29%29) produce results like [read](#%28def._%28%28quote._~23~25kernel%29._read%29%29) and [read-syntax](#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29), except that a special-comment value is returned when the input stream starts with a comment (after whitespace).\nSee [Readtables](readtables.html) for an extended example that uses [read-syntax/recursive](#%28def._%28%28quote._~23~25kernel%29._read-syntax%2Frecursive%29%29).\nChanged in version 6.2 of package base: Adjusted use of readtable in the same way as for [read/recursive](#%28def._%28%28quote._~23~25kernel%29._read%2Frecursive%29%29).\n> ```\n(current-input-port)\t→\t\n(-> or/c (any/c any/c . → . any) #f)"} {"text": "# 13.4 Reading\n```\n(read-case-sensitive)\t→\t\n(-> read-case-sensitive on?)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that controls parsing and printing of symbols. When this parameter’s value is #f, the reader case-folds symbols (e.g., producing 'hi when the input is any one of hi, Hi, HI, or hI). The parameter also affects the way that [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29) prints symbols containing uppercase characters; if the parameter’s value is #f, then symbols are printed with uppercase characters quoted by a \\\\ or \\|. The parameter’s value is overridden by quoting \\\\ or \\| vertical-bar quotes and the #cs and #ci prefixes; see [Reading Symbols](reader.html#%28part._parse-symbol%29) for more information. While a module is loaded, the parameter is set to #t (see [current-load](eval.html#%28def._%28%28quote._~23~25kernel%29._current-load%29%29)).\n\n> ```\n(read-square-bracket-as-paren)\t→\t\n(-> read-square-bracket-as-paren on?)\n```\n(read-curly-brace-as-paren)\t→\t\n(-> read-curly-brace-as-paren on?)```\nA [parameter](eval-model.html#%28tech._parameter%29) that controls whether { and } are treated as parentheses. See [Reading Pairs and Lists](reader.html#%28part._parse-pair%29) for more information.\n> ```\n(read-square-bracket-with-tag)\t→\t\n(-> read-square-bracket-with-tag on?)"} {"text": "# 13.4 Reading\n```\n(read-curly-brace-with-tag)\t→\t\n(-> read-curly-brace-with-tag on?)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that controls whether { and } are treated as parentheses, but the resulting list tagged with #%braces. See [Reading Pairs and Lists](reader.html#%28part._parse-pair%29) for more information.\n\nAdded in version 6.3.0.5 of package base.\n\n> ```\n(read-accept-box)\t→\t\n(-> read-accept-box on?)\n```\n(read-accept-compiled)\t→\t\n(-> read-accept-compiled on?)```\nA [parameter](eval-model.html#%28tech._parameter%29) that controls parsing #\\~ compiled input. See [The Reader](reader.html) and [current-compile](eval.html#%28def._%28%28quote._~23~25kernel%29._current-compile%29%29) for more information.\n> ```\n(read-accept-bar-quote)\t→\t\n(-> read-accept-bar-quote on?)\n```\n(read-accept-graph)\t→\t\n(-> read-accept-graph on?)```\n\n\nA parameter value that controls parsing input with sharing in [read](#%28def._%28%28quote._~23~25kernel%29._read%29%29) mode. See [Reading Graph Structure](reader.html#%28part._parse-graph%29) for more information.\n\n> ```\n(read-syntax-accept-graph)\t→\t\n(-> read-syntax-accept-graph on?)\n```\n(read-decimal-as-inexact)\t→\t\n(-> read-decimal-as-inexact on?)```\nA [parameter](eval-model.html#%28tech._parameter%29) that controls parsing input numbers with a decimal point or exponent (but no explicit exactness tag). See [Reading Numbers](reader.html#%28part._parse-number%29) for more information.\n> ```\n(read-single-flonum)\t→\t\n(-> read-single-flonum on?)"} {"text": "# 13.4 Reading\n```\n(read-accept-dot)\t→\t\n(-> read-accept-dot on?)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that controls parsing input with a dot, which is normally used for literal cons cells. See [Reading Pairs and Lists](reader.html#%28part._parse-pair%29) for more information.\n\n> ```\n(read-accept-infix-dot)\t→\t\n(-> read-accept-infix-dot on?)\n```\n(read-cdot)\t→\t\n(-> read-cdot on?)```\nA [parameter](eval-model.html#%28tech._parameter%29) that controls parsing input with a dot, in a C structure accessor style. See [Reading with C-style Infix-Dot Notation](reader.html#%28part._parse-cdot%29) for more information.\nAdded in version 6.3.0.5 of package base.\n> ```\n(read-accept-quasiquote)\t→\t\n(-> read-accept-quasiquote on?)\n```\n(read-accept-reader)\t→\t\n(-> read-accept-reader on?)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that controls whether #reader, #lang, or #! are allowed for selecting a parser. See [Reading via an Extension](reader.html#%28part._parse-reader%29) for more information.\n\n> ```\n(read-accept-lang)\t→\t\n(-> read-accept-lang on?)\n```\n(current-readtable)\t→\t\n(-> or/c readtable? #f)\n(current-readtable readtable) → void?\n readtable\t:\t\n(-> or/c readtable? #f)```\nA parameter whose value determines a readtable that adjusts the parsing of S-expression input, where #f implies the default behavior. See [Readtables](readtables.html) for more information.\n> ```\n(parameter)\t→\t\n(-> any)"} {"text": "# 13.4 Reading\n```\n(current-reader-guard)\t→\t\n(-> any/c . → . any)\n(current-reader-guard proc) → void?\n proc\t:\t\n(-> any/c . → . any)```\n\n\nA parameter whose value converts or rejects (by raising an exception) a module-path datum following #reader. See [Reading via an Extension](reader.html#%28part._parse-reader%29) for more information.\n\n> ```\n(read-on-demand-source)\t→\t\n(-> or/c #f #t (and/c path? complete-path?))\n(read-on-demand-source mode) → void?\n mode\t:\t\n(-> or/c #f #t (and/c path? complete-path?))\n```\n(parameter)\t→\t\n(-> case →\n (input-port? . → . any)\n (input-port? any/c . → . any))```\nGets or sets the port read handler for in. The handler called to read from the port when the built-in [read](#%28def._%28%28quote._~23~25kernel%29._read%29%29) or [read-syntax](#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29) procedure is applied to the port. (The port read handler is not used for [read/recursive](#%28def._%28%28quote._~23~25kernel%29._read%2Frecursive%29%29) or [read-syntax/recursive](#%28def._%28%28quote._~23~25kernel%29._read-syntax%2Frecursive%29%29).)\nA port read handler is applied to either one argument or two arguments:\n- A single argument is supplied when the port is used with [read](#%28def._%28%28quote._~23~25kernel%29._read%29%29); the argument is the port being read. The return value is the value that was read from the port (or end-of-file)."} {"text": "# 13.4 Reading\n- Two arguments are supplied when the port is used with [read-syntax](#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29); the first argument is the port being read, and the second argument is a value indicating the source. The return value is a syntax object that was read from the port (or end-of-file).\nThe default port read handler reads standard Racket expressions with Racket’s built-in parser (see [The Reader](reader.html)). It handles a special result from a custom input port (see [make-input-port](customport.html#%28def._%28%28quote._~23~25kernel%29._make-input-port%29%29)) by treating it as a single expression, except that special-comment values (see [Special Comments](special-comments.html)) are treated as whitespace.\nThe default port read handler itself can be customized through a readtable; see [Readtables](readtables.html) for more information.\n------------------------------------------------------------------------"} {"text": "# 13.5 Writing"} {"text": "### 13.5 Writing\n> ```\n(current-output-port)\t→\t\n(-> current-output-port)\n```\n(current-output-port)\t→\t\n(-> current-output-port)```\n\n\nDisplays datum to out, similar to [write](#%28def._%28%28quote._~23~25kernel%29._write%29%29), but usually in such a way that byte- and character-based datatypes are written as raw bytes or characters. If out has a handler associated to it via [port-display-handler](#%28def._%28%28quote._~23~25kernel%29._port-display-handler%29%29), then the handler is called. Otherwise, the [default printer](printing.html) is used (in [display](#%28def._%28%28quote._~23~25kernel%29._display%29%29) mode), as configured by various parameters.\n\nSee [The Printer](printing.html) for more information about the default printer. In particular, note that [display](#%28def._%28%28quote._~23~25kernel%29._display%29%29) may require memory proportional to the depth of the value being printed, due to the initial cycle check.\n\n> ```\n(current-output-port)\t→\t\n(-> current-output-port)\n```\n(current-output-port)\t→\t\n(-> current-output-port)```\nThe same as ([write](#%28def._%28%28quote._~23~25kernel%29._write%29%29) datum out) followed by ([newline](Byte_and_String_Output.html#%28def._%28%28quote._~23~25kernel%29._newline%29%29) out).\nAdded in version 6.1.1.8 of package base.\n> ```\n(current-output-port)\t→\t\n(-> current-output-port)"} {"text": "# 13.5 Writing\n```\n(current-output-port)\t→\t\n(-> current-output-port)```\n\n\nThe same as ([print](#%28def._%28%28quote._~23~25kernel%29._print%29%29) datum out quote-depth) followed by ([newline](Byte_and_String_Output.html#%28def._%28%28quote._~23~25kernel%29._newline%29%29) out).\n\nThe [println](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._println%29%29) function is not equivalent to println in other languages, because [println](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._println%29%29) uses printing conventions that are closer to [write](#%28def._%28%28quote._~23~25kernel%29._write%29%29) than to [display](#%28def._%28%28quote._~23~25kernel%29._display%29%29). For a closer analog to println in other languages, use [displayln](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._displayln%29%29).\n\nAdded in version 6.1.1.8 of package base.\n\n> ```\n(parameter)\t→\n```\n(error-print-width)\t→\t\n(-> see char-whitespace?)```\nThe same as ([fprintf](#%28def._%28%28quote._~23~25kernel%29._fprintf%29%29) ([current-output-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._current-output-port%29%29)) form v [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)).\n> ```\n(parameter)\t→"} {"text": "# 13.5 Writing\n```\n(current-error-port)\t→```\n\n\nFormats to a string. The result is the same as\n\n> ```racket\n> ( let ( [ o ( open-output-string ) ] )\n> ( fprintf o form v ... )\n> ( get-output-string o ) )\n> ```\n\nExample:\n\n> ```racket\n> > ( format \"~a as a string is ~s.\\n\" ' ( 3 4 ) \"(3 4)\" )\n> \"(3 4) as a string is \\\"(3 4)\\\".\\n\"\n> ```\n\n> ```\n(print-pair-curly-braces)\t→\t\n(-> print-pair-curly-braces on?)\n```\n(print-mpair-curly-braces)\t→\t\n(-> print-mpair-curly-braces on?)```\nA [parameter](eval-model.html#%28tech._parameter%29) that controls pair printing. If the value is true, then mutable pairs print using { and } instead of ( and ). The default is #t.\n> ```\n(print-unreadable)\t→\t\n(-> print-unreadable on?)\n```\n(print-graph)\t→\t\n(-> print-graph on?)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that controls printing data with sharing; defaults to #f. See [The Printer](printing.html) for more information.\n\n> ```\n(print-struct)\t→\t\n(-> print-struct on?)\n```\n(print-box)\t→\t\n(-> print-box on?)```\nA [parameter](eval-model.html#%28tech._parameter%29) that controls printing box values; defaults to #t. See [Printing Boxes](printing.html#%28part._print-box%29) for more information.\n> ```\n(print-vector-length)\t→\t\n(-> print-vector-length on?)\n```\n(print-hash-table)\t→\t\n(-> print-hash-table on?)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that controls printing hash tables; defaults to #t. See [Printing Hash Tables](printing.html#%28part._print-hashtable%29) for more information.\n\n> ```\n(print-boolean-long-form)\t→\t\n(-> print-boolean-long-form on?)\n```"} {"text": "# 13.5 Writing\n(print-reader-abbreviations)\t→\t\n(-> print-reader-abbreviations on?)```\nA [parameter](eval-model.html#%28tech._parameter%29) that controls printing of two-element lists that start with [quote](quote.html#%28form._%28%28quote._~23~25kernel%29._quote%29%29), 'quasiquote, 'unquote, 'unquote-splicing, 'syntax, 'quasisyntax, 'unsyntax, or 'unsyntax-splicing; defaults to #f. See [Printing Pairs and Lists](printing.html#%28part._print-pairs%29) for more information.\n> ```\n(print-as-expression)\t→\t\n(-> print-as-expression on?)\n```\n(print-syntax-width)\t→\t\n(-> or/c +inf.0 0 (and/c exact-integer? (>/c 3)))\n(print-syntax-width width) → void?\n width\t:\t\n(-> or/c +inf.0 0 (and/c exact-integer? (>/c 3)))```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that controls printing of [syntax objects](syntax-model.html#%28tech._syntax._object%29). Up to width characters are used to show the datum form of a syntax object within #\\ (after the [syntax object](syntax-model.html#%28tech._syntax._object%29)’s source location, if any), where ... is used as the last three characters if the printed form would otherwise be longer than width characters. A value of 0 for width means that the datum is not shown at all.\n\n> ```\n(print-value-columns)\t→\t\n(-> or/c +inf.0 (and/c exact-integer? (>/c 5)))\n(print-value-columns columns) → void?\n columns\t:\t\n(-> or/c +inf.0 (and/c exact-integer? (>/c 5)))\n```"} {"text": "# 13.5 Writing\n(current-write-relative-directory)\t→\t\n(-> or/c (and/c path? complete-path?)\n (cons/c (and/c path? complete-path?)\n (and/c path? complete-path?))\n #f)\n(current-write-relative-directory path) → void?\n path\t:\t\n(-> or/c (and/c path? complete-path?)\n (cons/c (and/c path? complete-path?)\n (and/c path? complete-path?))\n #f)```\nA [parameter](eval-model.html#%28tech._parameter%29) that is used when writing compiled code (see [Printing Compiled Code](printing.html#%28part._print-compiled%29)) that contains pathname literals, including source-location pathnames for procedure names. When the parameter’s value is a path, paths that syntactically extend path are converted to relative paths; when the resulting compiled code is read, relative paths are converted back to complete paths using the [current-load-relative-directory](eval.html#%28def._%28%28quote._~23~25kernel%29._current-load-relative-directory%29%29) parameter (if it is not #f; otherwise, the path is left relative). When the parameter’s value is ([cons](pairs.html#%28def._%28%28quote._~23~25kernel%29._cons%29%29) rel-to-path base-path), then paths that syntactically extend base-path are converted as relative to rel-to-path; the rel-to-path must extend base-path, in which case 'up path elements (in the sense of [build-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._build-path%29%29)) may be used to make a path relative to rel-to-path.\n> ```\n(parameter)\t→\t\n(-> any/c output-port? . → . any)"} {"text": "# 13.5 Writing\n```\n(respectively)\t→\t\n(-> * (any/c output-port?) ((or/c 0 1)) any)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines global port print handler, which is called by the default port print handler (see [port-print-handler](#%28def._%28%28quote._~23~25kernel%29._port-print-handler%29%29)) to [print](#%28def._%28%28quote._~23~25kernel%29._print%29%29) values into a port. The default value is equivalent to [default-global-port-print-handler](#%28def._%28%28quote._~23~25kernel%29._default-global-port-print-handler%29%29).\n\nA [global port print handler](#%28tech._global._port._print._handler%29) optionally accepts a third argument, which corresponds to the optional third argument to [print](#%28def._%28%28quote._~23~25kernel%29._print%29%29). If a procedure given to [global-port-print-handler](#%28def._%28%28quote._~23~25kernel%29._global-port-print-handler%29%29) does not accept a third argument, it is wrapped with a procedure that discards the optional third argument.\n\n> ```\n(parameter)\t→\t\n(-> or/c 0 1)\n```\n(current-output-port)\t→\t\n(-> current-output-port)```"} {"text": "# 13.5 Writing\nPretty-prints the value v using the same printed form as the default [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29) mode, but with newlines and whitespace inserted to avoid lines longer than ([pretty-print-columns](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-columns%29%29)), as controlled by ([pretty-print-current-style-table](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-current-style-table%29%29)). The printed form ends in a newline by default, unless the newline? argument is supplied with false or the [pretty-print-columns](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-columns%29%29) parameter is set to 'infinity. When port has line counting enabled (see [Counting Positions, Lines, and Columns](linecol.html)), then printing is sensitive to the column when printing starts—both for determining an initial line break and indenting subsequent lines."} {"text": "# 13.5 Writing\nIn addition to the parameters defined in this section, [pretty-print](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print%29%29) conforms to the [print-graph](Writing.html#%28def._%28%28quote._~23~25kernel%29._print-graph%29%29), [print-struct](Writing.html#%28def._%28%28quote._~23~25kernel%29._print-struct%29%29), [print-hash-table](Writing.html#%28def._%28%28quote._~23~25kernel%29._print-hash-table%29%29), [print-vector-length](Writing.html#%28def._%28%28quote._~23~25kernel%29._print-vector-length%29%29), [print-box](Writing.html#%28def._%28%28quote._~23~25kernel%29._print-box%29%29), and [print-as-expression](Writing.html#%28def._%28%28quote._~23~25kernel%29._print-as-expression%29%29) parameters."} {"text": "# 13.5 Writing\nThe pretty printer detects structures that have the [prop:custom-write](Printer_Extension.html#%28def._%28%28quote._~23~25kernel%29._prop~3acustom-write%29%29) property and calls the corresponding custom-write procedure. The custom-write procedure can check the parameter [pretty-printing](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-printing%29%29) to cooperate with the pretty-printer. Recursive printing to the port automatically uses pretty printing, but if the structure has multiple recursively printed sub-expressions, a custom-write procedure may need to cooperate more to insert explicit newlines. Use [port-next-location](linecol.html#%28def._%28%28quote._~23~25kernel%29._port-next-location%29%29) to determine the current output column, use [pretty-print-columns](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-columns%29%29) to determine the target printing width, and use [pretty-print-newline](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-newline%29%29) to insert a newline (so that the function in the [pretty-print-print-line](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-print-line%29%29) parameter can be called appropriately). Use [make-tentative-pretty-print-output-port](#%28def._%28%28lib._racket%2Fpretty..rkt%29._make-tentative-pretty-print-output-port%29%29) to obtain a port for tentative recursive prints (e.g., to check the length of the output)."} {"text": "# 13.5 Writing\nIf the newline? argument is omitted or supplied with true, the [pretty-print-print-line](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-print-line%29%29) callback is called with false as the first argument to print the last newline after the printed value. If it is supplied with false, the [pretty-print-print-line](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-print-line%29%29) callback is not called after the printed value.\nChanged in version 6.6.0.3 of package base: Added newline? argument.\n> ```\n(current-output-port)\t→\t\n(-> current-output-port)\n```\n(current-output-port)\t→\t\n(-> current-output-port)```\n\n\nSame as [pretty-print](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print%29%29), but v is printed like [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29) instead of like [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29).\n\nChanged in version 6.6.0.3 of package base: Added newline? argument.\n\n> ```\n(pretty-format v [columns #:mode mode) → string?\n  v : any/c\n  columns : exact-nonnegative-integer? = (pretty-print-columns)\n  mode : (or/c 'print 'write 'display) = 'print\n```\n(parameter)\t→```"} {"text": "# 13.5 Writing\nPretty-prints v if v is not [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13), or prints nothing if v is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13). Pass this procedure to [current-print](eval.html#%28def._%28%28quote._~23~25kernel%29._current-print%29%29) to install the pretty printer into the REPL run by [read-eval-print-loop](eval.html#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._read-eval-print-loop%29%29)."} {"text": "#### 13.6.1 Basic Pretty-Print Options\n> ```\n(pretty-print-columns)\t→\t\n(-> or/c exact-positive-integer? 'infinity)\n(pretty-print-columns width) → void?\n width\t:\t\n(-> or/c exact-positive-integer? 'infinity)\n```\n(pretty-print-depth)\t→\t\n(-> or/c exact-nonnegative-integer? #f)\n(pretty-print-depth depth) → void?\n depth\t:\t\n(-> or/c exact-nonnegative-integer? #f)```\n\n\nParameter that controls the default depth for recursive pretty printing. Printing to depth means that elements nested more deeply than depth are replaced with “...”; in particular, a depth of 0 indicates that only simple values are printed. A depth of #f (the default) allows printing to arbitrary depths.\n\n> ```\n(pretty-print-exact-as-decimal)\t→\t\n(-> pretty-print-exact-as-decimal as-decimal?)\n```\n(pretty-print-.-symbol-without-bars)\t→\t\n(-> pretty-print-.-symbol-without-bars on?)```\nA [parameter](eval-model.html#%28tech._parameter%29) that controls the printing of the symbol whose print name is just a period. If set to a true value, then such a symbol is printed as only the period. If set to a false value, it is printed as a period with vertical bars surrounding it.\n> ```\n(pretty-print-show-inexactness)\t→\t\n(-> pretty-print-show-inexactness show?)"} {"text": "# 13.5 Writing\n```\n(pretty-print-abbreviate-read-macros)\t→\t\n(-> pretty-print-abbreviate-read-macros abbrev?)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that controls whether or not quote, unquote, unquote-splicing, etc., are abbreviated with ', ,, ,@, etc. By default, the abbreviations are enabled.\n\nSee also [pretty-print-remap-stylable](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-remap-stylable%29%29).\n\n> ```\n(pretty-print-style-table? v)  →  boolean?\n  v : any/c\n```\n(pretty-print-current-style-table)\t→\t\n(-> pretty-print-current-style-table style-table)\n(pretty-print-current-style-table style-table) → void?\n style-table\t:\t\n(-> pretty-print-current-style-table style-table)```\nA [parameter](eval-model.html#%28tech._parameter%29) that holds a table of style mappings. See [pretty-print-extend-style-table](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-extend-style-table%29%29).\n> ```\n(parameter)\t→\t\n(-> listof symbol?)"} {"text": "# 13.5 Writing\n```\n(pretty-print-remap-stylable)\t→\t\n(-> any/c . → . (or/c symbol? #f))\n(pretty-print-remap-stylable proc) → void?\n proc\t:\t\n(-> any/c . → . (or/c symbol? #f))```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that controls remapping for styles and for the determination of the reader shorthands.\n\nThis procedure is called with each sub-expression that appears as the first element in a sequence. If it returns a symbol, the style table is used, as if that symbol were at the head of the sequence. If it returns #f, the style table is treated normally. Similarly, when determining whether to abbreviate reader macros, this parameter is consulted.\n\n#### 13.6.3 Line-Output Hook\n\n> ```\n(parameter)\t→\n```\n(pretty-print-print-line)\t→\t\n(-> (or/c exact-nonnegative-integer? #f)\n output-port?\n exact-nonnegative-integer?\n (or/c exact-nonnegative-integer? ' infinity)\n . → .\n exact-nonnegative-integer?)\n(pretty-print-print-line proc) → void?\n proc\t:\t\n(-> (or/c exact-nonnegative-integer? #f)\n output-port?\n exact-nonnegative-integer?\n (or/c exact-nonnegative-integer? ' infinity)\n . → .\n exact-nonnegative-integer?)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines a procedure for printing the newline separator between lines of a pretty-printed value. The procedure is called with four arguments: a new line number, an output port, the old line’s length, and the number of destination columns. The return value from proc is the number of extra characters it printed at the beginning of the new line."} {"text": "# 13.5 Writing\nThe proc procedure is called before any characters are printed with 0 as the line number and 0 as the old line length. Whenever the pretty-printer starts a new line, proc is called with the new line’s number (where the first new line is numbered 1) and the just-finished line’s length. The destination-columns argument to proc is always the total width of the destination printing area, or 'infinity if pretty-printed values are not broken into lines.\nIf the #:newline? argument was omitted or supplied with a true value, proc is also called after the last character of the value has been printed, with #f as the line number and with the length of the last line.\nThe default proc procedure prints a newline whenever the line number is not 0 and the column count is not 'infinity, always returning 0. A custom proc procedure can be used to print extra text before each line of pretty-printed output; the number of characters printed before each line should be returned by proc so that the next line break can be chosen correctly.\nThe destination port supplied to proc is generally not the port supplied to [pretty-print](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print%29%29) or [pretty-display](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-display%29%29) (or the current output port), but output to this port is ultimately redirected to the port supplied to [pretty-print](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print%29%29) or [pretty-display](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-display%29%29)."} {"text": "#### 13.6.4 Value Output Hook\n> ```\n(pretty-print-size-hook)\t→\t\n(-> any/c boolean? output-port?\n . → .\n (or/c #f exact-nonnegative-integer?))\n(pretty-print-size-hook proc) → void?\n proc\t:\t\n(-> any/c boolean? output-port?\n . → .\n (or/c #f exact-nonnegative-integer?))\n```\n(pretty-print-print-hook)\t→\t\n(-> any/c boolean? output-port? . → . void?)\n(pretty-print-print-hook proc) → void?\n proc\t:\t\n(-> any/c boolean? output-port? . → . void?)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines a print hook for pretty-printing. The print-hook procedure is applied to a value for printing when the sizing hook (see [pretty-print-size-hook](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-size-hook%29%29)) returns an integer size for the value.\n\nThe print hook receives three arguments. The first argument is the value to print. The second argument is a boolean: #t for printing like [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29) and #f for printing like [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29). The third argument is the destination port; this port is generally not the port supplied to [pretty-print](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print%29%29) or [pretty-display](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-display%29%29) (or the current output port), but output to this port is ultimately redirected to the port supplied to [pretty-print](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print%29%29) or [pretty-display](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-display%29%29).\n\n> ```\n(pretty-print-pre-print-hook)\t→\t\n(-> any/c output-port? . → . void)\n(pretty-print-pre-print-hook proc) → void?\n proc\t:\t\n(-> any/c output-port? . → . void)\n```"} {"text": "# 13.5 Writing\n(pretty-print-post-print-hook)\t→\t\n(-> any/c output-port? . → . void)\n(pretty-print-post-print-hook proc) → void?\n proc\t:\t\n(-> any/c output-port? . → . void)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines a hook procedure to be called just after an object is printed. The hook receives two arguments: the object and the output port. The port is the one supplied to [pretty-print](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print%29%29) or [pretty-display](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-display%29%29) (or the current output port)."} {"text": "#### 13.6.5 Additional Custom-Output Support\n> ```\n(pretty-printing)\t→\t\n(-> pretty-printing on?)\n```\n(parameter)\t→\t\n(-> any)```\n\n\nProduces an output port that is suitable for recursive pretty printing without actually producing output. Use such a port to tentatively print when proper output depends on the size of recursive prints. After printing, determine the size of the tentative output using [file-position](port-buffers.html#%28def._%28%28quote._~23~25kernel%29._file-position%29%29).\n\nThe out argument should be a pretty-printing port, such as the one supplied to a custom-write procedure when [pretty-printing](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-printing%29%29) is set to true, or another tentative output port. The width argument should be a target column width, usually obtained from [pretty-print-columns](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-columns%29%29), possibly decremented to leave room for a terminator. The overflow-thunk procedure is called if more than width items are printed to the port or if a newline is printed to the port via [pretty-print-newline](#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print-newline%29%29); it can escape from the recursive print through a continuation as a shortcut, but overflow-thunk can also return, in which case it is called every time afterward that additional output is written to the port.\n\nAfter tentative printing, either accept the result with [tentative-pretty-print-port-transfer](#%28def._%28%28lib._racket%2Fpretty..rkt%29._tentative-pretty-print-port-transfer%29%29) or reject it with [tentative-pretty-print-port-cancel](#%28def._%28%28lib._racket%2Fpretty..rkt%29._tentative-pretty-print-port-cancel%29%29). Failure to accept or cancel properly interferes with graph-structure printing, calls to hook procedures, etc. Explicitly cancel the tentative print even when overflow-thunk escapes from a recursive print.\n\n> ```\n(parameter)\t→\n```"} {"text": "# 13.5 Writing\n(parameter)\t→```\nCancels the content of tentative-out, which was produced by [make-tentative-pretty-print-output-port](#%28def._%28%28lib._racket%2Fpretty..rkt%29._make-tentative-pretty-print-output-port%29%29). The main effect of canceling is that graph-reference definitions are undone, so that a future print of a graph-referenced object includes the defining #‹n›=.\n------------------------------------------------------------------------"} {"text": "# 13.7 Reader Extension"} {"text": "### 13.7 Reader Extension\nRacket’s reader can be extended in three ways: through a reader-macro procedure in a [readtable](readtables.html#%28tech._readtable%29) (see [Readtables](readtables.html)), through a #reader form (see [Reading via an Extension](reader.html#%28part._parse-reader%29)), or through a custom-port byte reader that returns a “special” result procedure (see [Custom Ports](customport.html)). All three kinds of reader extension procedures accept similar arguments, and their results are treated in the same way by [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) and [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29) (or, more precisely, by the default read handler; see [port-read-handler](Reading.html#%28def._%28%28quote._~23~25kernel%29._port-read-handler%29%29)).\n| |\n|----------------------------------------------------------------------------------------|\n|     [13.7.1 Readtables](readtables.html) |\n|     [13.7.2 Reader-Extension Procedures](reader-procs.html) |\n|     [13.7.3 Special Comments](special-comments.html) |\n------------------------------------------------------------------------"} {"text": "# 13.7.1 Readtables"} {"text": "#### 13.7.1 Readtables\nThe dispatch table in [Delimiters and Dispatch](reader.html#%28part._default-readtable-dispatch%29) corresponds to the default readtable. By creating a new readtable and installing it via the [current-readtable](Reading.html#%28def._%28%28quote._~23~25kernel%29._current-readtable%29%29) parameter, the reader’s behavior can be extended.\nA readtable is consulted at specific times by the reader:\n- when looking for the start of a datum;\n- when determining how to parse a datum that starts with #;\n- when looking for a delimiter to terminate a symbol or number;\n- when looking for an opener (such as (), closer (such as )), or . after the first character parsed as a sequence for a pair, list, vector, or hash table; or\n- when looking for an opener after #‹n› in a vector of specified length ‹n›.\nThe readtable is ignored at other times. In particular, after parsing a character that is mapped to the default behavior of ;, the readtable is ignored until the comment’s terminating newline is discovered. Similarly, the readtable does not affect string parsing until a closing double-quote is found. Meanwhile, if a character is mapped to the default behavior of (, then it starts a sequence that is closed by any character that is mapped to a closing parenthesis ). An apparent exception is that the default parsing of \\| quotes a symbol until a matching character is found, but the parser is simply using the character that started the quote; it does not consult the readtable."} {"text": "# 13.7.1 Readtables\nFor many contexts, #f identifies the default readtable. In particular, #f is the initial value for the [current-readtable](Reading.html#%28def._%28%28quote._~23~25kernel%29._current-readtable%29%29) parameter, which causes the reader to behave as described in [The Reader](reader.html).\n> ```\n(readtable? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a readtable, #f otherwise.\n\n> ```\n(make-readtable readtable key mode action ...) → readtable?\n  readtable : (or/c readtable? #f)\n  key : (or/c char? #f)\n   mode   :   ( or/c ' terminating-macro\n> ' non-terminating-macro\n> ' dispatch-macro\n> char? )\n\n   action   :   ( or/c procedure?\n> readtable?\n> #f )```\n\n\nCreates a new readtable that is like readtable (which can be #f to indicate the default readtable), except that the reader’s behavior is modified for each key according to the given mode and action. The [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29) for [make-readtable](#%28def._%28%28quote._~23~25kernel%29._make-readtable%29%29) applies to all three of key, mode, and action; in other words, the total number of arguments to [make-readtable](#%28def._%28%28quote._~23~25kernel%29._make-readtable%29%29) must be 1 modulo 3.\n\nThe possible combinations for key, mode, and action are as follows:\n\n- char 'terminating-macro proc — causes char to be parsed as a delimiter, and an unquoted/uncommented char in the input string triggers a call to the reader macro proc; the activity of proc is described further below. Conceptually, characters like ;, (, and ) are mapped to terminating reader macros in the default readtable.\n\n- char 'non-terminating-macro proc — like the 'terminating-macro variant, but char is not treated as a delimiter, so it can be used in the middle of an identifier or number. Conceptually, # is mapped to a non-terminating macro in the default readtable.\n\n- char 'dispatch-macro proc — like the 'non-terminating-macro variant, but for char only when it follows a # (or, more precisely, when the character follows one that has been mapped to the behavior of # in the default readtable).\n\n- char like-char readtable — causes char to be parsed in the same way that like-char is parsed in readtable, where readtable can be #f to indicate the default readtable. (The mapping of char does not apply after #, which is configured separately via 'dispatch-macro.) Mapping a character to the same actions as \\| in the default reader means that the character starts quoting for symbols, and the same character terminates the quote; in contrast, mapping a character to the same action as a \" means that the character starts a string, but the string is still terminated with a closing \". Finally, mapping a character to an action in the default readtable means that the character’s behavior is sensitive to parameters that affect the original character; for example, mapping a character to the same action as a curly brace { in the default readtable means that the character is disallowed when the [read-curly-brace-as-paren](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-curly-brace-as-paren%29%29) parameter is set to #f.\n\n- #f 'non-terminating-macro proc — replaces the macro used to parse characters with no specific mapping: i.e., the characters (other than # or \\|) that can start a symbol or number with the default readtable.\n\nIf multiple 'dispatch-macro mappings are provided for a single char, all but the last one are ignored. Similarly, if multiple non-'dispatch-macro mappings are provided for a single char, all but the last one are ignored.\n\nA reader macro proc must accept six arguments, and it can optionally accept two arguments. The first two arguments are always the character that triggered the reader macro and the input port for reading. When the reader macro is triggered by [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29) (or [read-syntax/recursive](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%2Frecursive%29%29)), the procedure is passed four additional arguments that represent a source location for already-consumed character(s): the source name, a line number or #f, a column number or #f, and a position or #f. When the reader macro is triggered by [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) (or [read/recursive](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%2Frecursive%29%29)), the procedure is passed only two arguments if it accepts two arguments, otherwise it is passed six arguments where the third is always #f. See [Reader-Extension Procedures](reader-procs.html) for information on the procedure’s results.\n\nA reader macro normally reads characters from the given input port to produce a value to be used as the “reader macro-expansion” of the consumed characters. The reader macro might produce a special-comment value (see [Special Comments](special-comments.html)) to cause the consumed character to be treated as whitespace, and it might use [read/recursive](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%2Frecursive%29%29) or [read-syntax/recursive](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%2Frecursive%29%29).\n\n> ```\n(readtable-mapping readtable char)\n  →   ( or/c char?\n> ' terminating-macro\n> ' non-terminating-macro )\n(or/c #f procedure?)\n(or/c #f procedure?)\n\n  readtable : readtable?\n  char : char?\n```"} {"text": "# 13.7.1 Readtables\n(parameter)\t→\t\n(-> wrap (parse port (lambda () (read-syntax/recursive src port #f (make-delims-table))) src))```\nCreates a special-comment value that encapsulates v. The [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29), [read-syntax](Reading.html#%28def._%28%28quote._~23~25kernel%29._read-syntax%29%29), etc., procedures treat values constructed with [make-special-comment](#%28def._%28%28quote._~23~25kernel%29._make-special-comment%29%29) as delimiting whitespace when returned by a reader-extension procedure (see [Reader-Extension Procedures](reader-procs.html)).\n> ```\n(special-comment? v)  →  boolean?\n  v : any/c"} {"text": "# 13.7.1 Readtables\n```\nReturns #t if v is the result of make-special-comment, #f otherwise.\n\n> ```\n(special-comment-value sc)  →  any\n  sc : special-comment?```\n\n\nReturns the value encapsulated by the special-comment value sc. This value is never used directly by a reader, but it might be used by the context of a [read-char-or-special](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-char-or-special%29%29), etc., call that detects a special comment.\n\n------------------------------------------------------------------------\n\n# 13.8 Printer Extension\n\n### 13.8 Printer Extension\n\n>
\n\n

value

\n\n

[gen:custom-write](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._gen~3acustom-write%29%29) : [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29)

\n\nA [generic interface](struct-generics.html#%28tech._generic._interface%29) (see [Generic Interfaces](struct-generics.html)) that supplies a method, write-proc used by the default printer to [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29), [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29), or [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29) instances of the structure type.\n\nA write-proc method takes three arguments: the structure to be printed, the target port, and an argument that is #t for [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29) mode, #f for [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29) mode, or 0 or 1 indicating the current [quoting depth](printing.html#%28tech._quoting._depth%29) for [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29) mode. The procedure should print the value to the given port using [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29), [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29), [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29), [fprintf](Writing.html#%28def._%28%28quote._~23~25kernel%29._fprintf%29%29), [write-special](Byte_and_String_Output.html#%28def._%28%28quote._~23~25kernel%29._write-special%29%29), etc.\n\nThe [port write handler](Writing.html#%28tech._port._write._handler%29), [port display handler](Writing.html#%28tech._port._display._handler%29), and [print handler](eval.html#%28tech._print._handler%29) are specially configured for a port given to a custom-write procedure. Printing to the port through [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29), [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29), or [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29) prints a value recursively with sharing annotations. To avoid a recursive print (i.e., to print without regard to sharing with a value currently being printed), print instead to a string or pipe and transfer the result to the target port using [write-string](Byte_and_String_Output.html#%28def._%28%28quote._~23~25kernel%29._write-string%29%29) or [write-special](Byte_and_String_Output.html#%28def._%28%28quote._~23~25kernel%29._write-special%29%29). To print recursively to a port other than the one given to the custom-write procedure, copy the given port’s write handler, display handler, and print handler to the other port.\n\nThe port given to write-proc is not necessarily the actual target port. In particular, to detect cycles, sharing, and quoting modes (in the case of [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29)), the printer invokes a custom-write procedure with a port that records information about recursive prints, and does not retain any other output. This information-gathering phase needs the same objects (in the [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) sense) to be printed as later, so that the recorded information can be correlated with printed values.\n\nRecursive print operations may trigger an escape from a call to write-proc. For example, printing may escape during pretty-printing where a tentative print attempt overflows the line, or it may escape while printing error output that is constrained to a limited width.\n\nThe following example definition of a tuple type includes a write-proc procedure that prints the tuple’s list content using angle brackets in [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29) and [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29) mode and no brackets in [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29) mode. Elements of the tuple are printed recursively, so that graph and cycle structure can be represented.\n\nExamples:\n\n> ```racket\n> ( define ( tuple-print tuple port mode ) ( when mode ( write-string \"<\" port ) ) ( let ( [ l ( tuple-ref tuple ) ] [ recur ( case mode [ ( #t ) write ] [ ( #f ) display ] [ else ( lambda ( p port ) ( print p port mode ) ) ] ) ] ) ( unless ( zero? ( vector-length l ) ) ( recur ( vector-ref l 0 ) port ) ( for-each ( lambda ( e ) ( write-string \", \" port ) ( recur e port ) ) ( cdr ( vector->list l ) ) ) ) ) ( when mode ( write-string \">\" port ) ) )\n> ( struct tuple ( ref ) #:methods gen:custom-write [ ( define write-proc tuple-print ) ] )\n> > ( display ( tuple # ( 1 2 \"a\" ) ) )\n> 1, 2, a\n> > ( print ( tuple # ( 1 2 \"a\" ) ) )\n> <1, 2, \"a\">\n> > ( let ( [ t ( tuple ( vector 1 2 \"a\" ) ) ] ) ( vector-set! ( tuple-ref t ) 0 t ) ( write t ) )\n> #0=<#0#, 2, \"a\">\n> ```\n\nThe [make-constructor-style-printer](structutils.html#%28def._%28%28lib._racket%2Fstruct..rkt%29._make-constructor-style-printer%29%29) function can help in the implementation of a write-proc, as in this example:\n\nExamples:\n\n> ```racket\n> ( require racket/struct )\n> ( struct point ( x y ) #:methods gen:custom-write [ ( define write-proc ( make-constructor-style-printer ( lambda ( obj ) ' point ) ( lambda ( obj ) ( list ( point-x obj ) ( point-y obj ) ) ) ) ) ] )\n> > ( print ( point 1 2 ) )\n> (point 1 2)\n> > ( write ( point 1 2 ) )\n> #\n> ```\n\nChanged in version 8.7.0.5 of package base: Added a check so that omitting write-proc is now a syntax error.\n\n>
\n\n

value

\n\n

[prop:custom-write](#%28def._%28%28quote._~23~25kernel%29._prop~3acustom-write%29%29) : [struct-type-property?](structprops.html#%28def._%28%28quote._~23~25kernel%29._struct-type-property~3f%29%29)

\n\nA [structure type property](structprops.html#%28tech._structure._type._property%29) (see [Structure Type Properties](structprops.html)) that supplies a procedure that corresponds to [gen:custom-write](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._gen~3acustom-write%29%29)’s write-proc. Using the [prop:custom-write](#%28def._%28%28quote._~23~25kernel%29._prop~3acustom-write%29%29) property is discouraged; use the [gen:custom-write](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._gen~3acustom-write%29%29) [generic interface](struct-generics.html#%28tech._generic._interface%29) instead.\n\n> ```\n(custom-write? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 13.7.1 Readtables\nReturns #t if v has the prop:custom-write property, #f otherwise.\n> ```\n(custom-write-accessor v)\n  →  (custom-write? output-port? (or/c #t #f 0 1) . → . any)\n  v : custom-write?```\nReturns the custom-write procedure associated with v.\n>
\n

value

\n

[prop:custom-print-quotable](#%28def._%28%28quote._~23~25kernel%29._prop~3acustom-print-quotable%29%29) : [struct-type-property?](structprops.html#%28def._%28%28quote._~23~25kernel%29._struct-type-property~3f%29%29)

\n

value

\n

[custom-print-quotable?](#%28def._%28%28quote._~23~25kernel%29._custom-print-quotable~3f%29%29) : [struct-type-property?](structprops.html#%28def._%28%28quote._~23~25kernel%29._struct-type-property~3f%29%29)

\n

value

"} {"text": "# 13.7.1 Readtables\n

[custom-print-quotable-accessor](#%28def._%28%28quote._~23~25kernel%29._custom-print-quotable-accessor%29%29) : [struct-type-property?](structprops.html#%28def._%28%28quote._~23~25kernel%29._struct-type-property~3f%29%29)

\nA property and associated predicate and accessor. The property value is one of 'self, 'never, 'maybe, or 'always. When a structure has this property in addition to a [prop:custom-write](#%28def._%28%28quote._~23~25kernel%29._prop~3acustom-write%29%29) property value, then the property value affects printing in [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29) mode; see [The Printer](printing.html). When a value does not have the [prop:custom-print-quotable](#%28def._%28%28quote._~23~25kernel%29._prop~3acustom-print-quotable%29%29), it is equivalent to having the 'self property value, which is suitable both for self-quoting forms and printed forms that are unreadable.\n------------------------------------------------------------------------"} {"text": "# 13.9 Serialization"} {"text": "### 13.9 Serialization\n| | |\n|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/serialize]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/serialize]() library, not [racket/base](index.html) or [racket](index.html).\n> ```\n(serializable? v)  →  boolean?\n  v : any/c"} {"text": "# 13.9 Serialization\n```\nReturns #t if v appears to be serializable, without checking the content of compound values, and #f otherwise. See serialize for an enumeration of serializable values.\n\n> ```\n(serialize\n    v  \n   [ #:relative-directory relative-to  \n    #:deserialize-relative-directory deserialize-relative-to)  \n\n  →  any\n  v : serializable?\n   relative-to   :   ( or/c ( and/c path? complete-path? )\n> ( cons/c ( and/c path? complete-path? )\n> ( and/c path? complete-path? ) )\n> #f )   =   #f\n\n   deserialize-relative-to   :   ( or/c ( and/c path? complete-path? )\n> ( cons/c ( and/c path? complete-path? )\n> ( and/c path? complete-path? ) )\n> #f )\n      =   relative-to```\n\n\nReturns a value that encapsulates the value v. This value includes only readable values, so it can be written to a stream with [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29) or [s-exp->fasl](fasl.html#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29), later read from a stream using [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) or [fasl->s-exp](fasl.html#%28def._%28%28lib._racket%2Ffasl..rkt%29._fasl-~3es-exp%29%29), and then converted to a value like the original using [deserialize](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._deserialize%29%29). Serialization followed by deserialization produces a value with the same graph structure and mutability as the original value, but the serialized value is a plain tree (i.e., no sharing).\n\nThe following kinds of values are serializable:\n\n- structures created through [serializable-struct](#%28form._%28%28lib._racket%2Fserialize..rkt%29._serializable-struct%29%29) or [serializable-struct/versions](#%28form._%28%28lib._racket%2Fserialize..rkt%29._serializable-struct%2Fversions%29%29), or more generally structures with the [prop:serializable](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._prop~3aserializable%29%29) property (see [prop:serializable](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._prop~3aserializable%29%29) for more information);\n\n- [prefab](structures.html#%28tech._prefab%29) structures;\n\n- instances of classes defined with [define-serializable-class](objectserialize.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define-serializable-class%29%29) or [define-serializable-class*](objectserialize.html#%28form._%28%28lib._racket%2Fprivate%2Fclass-internal..rkt%29._define-serializable-class%2A%29%29);\n\n- [booleans](booleans.html#%28tech._boolean%29), [numbers](numbers.html#%28tech._number%29), [characters](characters.html#%28tech._character%29), [interned](reader.html#%28tech._interned%29) symbols, [unreadable symbols](symbols.html#%28tech._unreadable._symbol%29), [keywords](keywords.html#%28tech._keyword%29), [strings](strings.html#%28tech._string%29), [byte strings](bytestrings.html#%28tech._byte._string%29), [paths](pathutils.html#%28tech._path%29) (for a specific convention), [regexp values](regexp.html#%28tech._regexp._value%29), [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13), and the empty list;\n\n- [pairs](pairs.html#%28tech._pair%29), [mutable pairs](mpairs.html#%28tech._mutable._pair%29), [vectors](vectors.html#%28tech._vector%29), [flvectors](flonums.html#%28tech._flvector%29), [fxvectors](fixnums.html#%28tech._fxvector%29), [box](boxes.html#%28tech._box%29)es, [hash tables](hashtables.html#%28tech._hash._table%29), [sets](sets.html#%28tech._set%29), and [treelists](treelist.html#%28tech._treelist%29);\n\n- [date](time.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%29%29), [date*](time.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%2A%29%29), [arity-at-least](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._arity-at-least%29%29) and [srcloc](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29) structures; and\n\n- [module path index](Module_Names_and_Loading.html#%28tech._module._path._index%29) values.\n\nSerialization succeeds for a compound value, such as a pair, only if all content of the value is serializable. If a value given to [serialize](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._serialize%29%29) is not completely serializable, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nIf v contains a cycle (i.e., a collection of objects that are all reachable from each other), then v can be serialized only if the cycle includes a mutable value, where a [prefab](structures.html#%28tech._prefab%29) structure counts as mutable only if all of its fields are mutable.\n\nIf relative-to is not #f, then paths to serialize that extend the path in relative-to are recorded in relative and platform-independent form. The possible values and treatment of relative-to are the same as for [current-write-relative-directory](Writing.html#%28def._%28%28quote._~23~25kernel%29._current-write-relative-directory%29%29).\n\nIf deserialize-relative-to is not #f, then any paths to deserializers as extracted via [prop:serializable](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._prop~3aserializable%29%29) are recorded in relative form. Note that relative-to and deserialize-relative-to are independent, but deserialize-relative-to defaults to relative-to.\n\n> > > The [serialize](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._serialize%29%29) and [deserialize](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._deserialize%29%29) functions currently do not handle certain cyclic values that [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) and [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29) can handle, such as '#0=(#0#).\n\nSee [deserialize](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._deserialize%29%29) for information on the format of serialized data.\n\nChanged in version 6.5.0.4 of package base: Added keywords and regexp values as serializable. \nChanged in version 7.0.0.6: Added the #:relative-directory and #:deserialize-relative-directory arguments.\n\n> ```\n(deserialize v)  →  any\n  v : any/c\n```"} {"text": "# 13.9 Serialization\n(1)\t→\t\n(-> as a fallback)```\nReturns #t if v1 and v2 represent the same serialization information.\nMore precisely, it returns the same value that ([equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) ([deserialize](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._deserialize%29%29) v1) ([deserialize](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._deserialize%29%29) v2)) would return if\n- all structure types whose deserializers are accessed with distinct module paths are actually distinct types;\n- all structure types are transparent; and\n- all structure instances contain only the constituent values recorded in each of v1 and v2.\n> ```\n(deserialize-module-guard)\t→\t\n(-> module-path? symbol?\n (or/c void? (cons/c module-path? symbol?)))\n(deserialize-module-guard guard) → void?\n guard\t:\t\n(-> module-path? symbol?\n (or/c void? (cons/c module-path? symbol?)))"} {"text": "# 13.9 Serialization\n```\n(parameter)\t→```\n\n\nLike [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29), but instances of the structure type are serializable with [serialize](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._serialize%29%29). This form is allowed only at the top level or in a module’s top level (so that deserialization information can be found later).\n\nSerialization supports cycles involving the created structure type only when all fields are mutable (or when the cycle can be broken through some other mutable value).\n\nIn addition to the bindings generated by [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29), [serializable-struct](#%28form._%28%28lib._racket%2Fserialize..rkt%29._serializable-struct%29%29) binds deserialize-info:id-v0 to deserialization information. Furthermore, in a module context, it automatically [provide](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29)s this binding in a deserialize-info submodule using [module+](module.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._module%2B%29%29).\n\nThe [serializable-struct](#%28form._%28%28lib._racket%2Fserialize..rkt%29._serializable-struct%29%29) form enables the construction of structure instances from places where id is not accessible, since deserialization must construct instances. Furthermore, [serializable-struct](#%28form._%28%28lib._racket%2Fserialize..rkt%29._serializable-struct%29%29) provides limited access to field mutation, but only for instances generated through the deserialization information bound to deserialize-info:id-v0. See [make-deserialize-info](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._make-deserialize-info%29%29) for more information.\n\nBeware that the previous paragraph means that if a serializable struct is exported via [contract-out](attaching-contracts-to-values.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._contract-out%29%29), for example, the contracts are not checked during deserialization. Consider using [struct-guard/c](attaching-contracts-to-values.html#%28form._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._struct-guard%2Fc%29%29) instead.\n\nThe -v0 suffix on the deserialization enables future versioning on the structure type through [serializable-struct/versions](#%28form._%28%28lib._racket%2Fserialize..rkt%29._serializable-struct%2Fversions%29%29).\n\nWhen a supertype is supplied as maybe-super, compile-time information bound to the supertype identifier must include all of the supertype’s field accessors. If any field mutator is missing, the structure type will be treated as immutable for the purposes of marshaling (so cycles involving only instances of the structure type cannot be handled by the deserializer).\n\nExamples:\n\n> ```racket\n> > ( serializable-struct point ( x y ) )\n> > ( point-x ( deserialize ( serialize ( point 1 2 ) ) ) )\n> 1\n> ```\n\n> ```\nsyntax\n\n(define-serializable-struct id-maybe-super (field ...)\n> struct-option ... )\n```"} {"text": "# 13.9 Serialization\nLike serializable-struct, but with the supertype syntax and default constructor name of define-struct.\n> ```\nsyntax\n(serializable-struct/versions id maybe-super vers (field ...)\n> ( other-version-clause ... )\n> struct-option ... )\nother-version-clause   =   ( other-vers make-proc-expr\n> cycle-make-proc-expr )```\nLike [serializable-struct](#%28form._%28%28lib._racket%2Fserialize..rkt%29._serializable-struct%29%29), but the generated deserializer binding is deserialize-info:id-vvers. In addition, deserialize-info:id-vother-vers is bound for each other-vers. The vers and each other-vers must be a literal, exact, nonnegative integer.\nEach make-proc-expr should produce a procedure, and the procedure should accept as many argument as fields in the corresponding version of the structure type, and it produces an instance of id. Each cycle-make-proc-expr should produce a procedure of no arguments; this procedure should return two values: an instance x of id (typically with #f for all fields) and a procedure that accepts another instance of id and copies its field values into x.\nExamples:"} {"text": "# 13.9 Serialization\n> ```racket\n> > ( serializable-struct point ( x y ) #:mutable #:transparent )\n> > ( define ps ( serialize ( point 1 2 ) ) )\n> > ( deserialize ps )\n> (point 1 2)\n> > ( define x ( point 1 10 ) )\n> > ( set-point-x! x x )\n> > ( define xs ( serialize x ) )\n> > ( deserialize xs )\n> #0=(point #0# 10)\n> > ( serializable-struct/versions point 1 ( x y z ) ( [ 0 ; Constructor for simple v0 instances: ( lambda ( x y ) ( point x y 0 ) ) ; Constructor for v0 instance in a cycle: ( lambda ( ) ( let ( [ p0 ( point #f #f 0 ) ] ) ( values p0 ( lambda ( p ) ( set-point-x! p0 ( point-x p ) ) ( set-point-y! p0 ( point-y p ) ) ) ) ) ) ] ) #:mutable #:transparent )\n> > ( deserialize ( serialize ( point 4 5 6 ) ) )\n> (point 4 5 6)\n> > ( deserialize ps )\n> (point 1 2 0)\n> > ( deserialize xs )\n> #0=(point #0# 10 0)\n> ```\n> ```\nsyntax\n(define-serializable-struct/versions id-maybe-super vers (field ...)\n> ( other-version-clause ... )\n> struct-option ... )"} {"text": "# 13.9 Serialization\n```\nLike serializable-struct/versions, but with the supertype syntax and default constructor name of define-struct.\n\n> ```\n(make-deserialize-info make cycle-make)  →  any\n  make : procedure?\n  cycle-make : ( →  (values any/c procedure?))```\n\n\nProduces a deserialization information record to be used by [deserialize](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._deserialize%29%29). This information is normally tied to a particular structure because the structure has a [prop:serializable](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._prop~3aserializable%29%29) property value that points to a top-level variable or module-exported variable that is bound to deserialization information.\n\nThe make procedure should accept as many arguments as the structure’s serializer put into a vector; normally, this is the number of fields in the structure. It should return an instance of the structure.\n\nThe cycle-make procedure should accept no arguments, and it should return two values: a structure instance x (with dummy field values) and an update procedure. The update procedure takes another structure instance generated by the make, and it transfers the field values of this instance into x.\n\n>
\n\n

value

\n\n

[prop:serializable](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._prop~3aserializable%29%29) : [struct-type-property?](structprops.html#%28def._%28%28quote._~23~25kernel%29._struct-type-property~3f%29%29)

\n\nThis property identifies structures and structure types that are [serializable](#%28tech._serializable%29). The property value should be constructed with [make-serialize-info](#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._make-serialize-info%29%29).\n\n> ```\n(parameter)\t→\t\n(-> any/c . → . vector?)\n```"} {"text": "# 13.9 Serialization\n(current-load-relative-directory)\t→\t\n(-> or/c (void) bytes?)```\nThe [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29) function serializes v to a byte string, printing it directly to out if out is an output port or returning the byte string otherwise. The [fasl->s-exp](#%28def._%28%28lib._racket%2Ffasl..rkt%29._fasl-~3es-exp%29%29) function decodes a value from a byte string (supplied either directly or as an input port) that was encoded with [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29).\nThe v argument must be a value that could be [quote](quote.html#%28form._%28%28quote._~23~25kernel%29._quote%29%29)d as a literal—that is, a value without syntax objects for which ([compile](eval.html#%28def._%28%28quote._~23~25kernel%29._compile%29%29) \\`',v) would work and be [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29)able after [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29)—or it can include [correlated objects](linklets.html#%28tech._correlated._object%29) mixed with those values. The byte string produced by [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29) does not use the same format as compiled code, however."} {"text": "# 13.9 Serialization\nIf a value within v is not valid as a [quote](quote.html#%28form._%28%28quote._~23~25kernel%29._quote%29%29)d literal, and if handle-fail is not #f, then handle-fail is called on the nested value, and the result of handle-fail is written in that value’s place. The handle-fail procedure might raise an exception instead of returning a replacement value. If handle-fail is #f, then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised when an invalid value is encountered.\nIf external-lift? is not #f, then it receives each value v-sub encountered in v by [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29). If the result of external-lift? on v-sub is true, then v-sub is not encoded in the result, and it instead treated as externally lifted. A deserializing [fasl->s-exp](#%28def._%28%28lib._racket%2Ffasl..rkt%29._fasl-~3es-exp%29%29) receives a external-lifts vector that has one value for each externally lifted value, in the same order as passed to external-lift? on serialization."} {"text": "# 13.9 Serialization\nLike ([compile](eval.html#%28def._%28%28quote._~23~25kernel%29._compile%29%29) \\`',v), [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29) does not preserve graph structure, support cycles, or handle non-[prefab](structures.html#%28tech._prefab%29) structures. Compose [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29) with [serialize](serialization.html#%28def._%28%28lib._racket%2Fprivate%2Fserialize..rkt%29._serialize%29%29) to preserve graph structure, handle cyclic data, and encode serializable structures. The [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29) and [fasl->s-exp](#%28def._%28%28lib._racket%2Ffasl..rkt%29._fasl-~3es-exp%29%29) functions consult [current-write-relative-directory](Writing.html#%28def._%28%28quote._~23~25kernel%29._current-write-relative-directory%29%29) and [current-load-relative-directory](eval.html#%28def._%28%28quote._~23~25kernel%29._current-load-relative-directory%29%29) (falling back to [current-directory](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29)), respectively, in the same way as bytecode saving and loading to store paths in relative form, and they similarly allow and convert constrained [srcloc](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._srcloc%29%29) values (see [Printing Compiled Code](printing.html#%28part._print-compiled%29))."} {"text": "# 13.9 Serialization\nUnless keep-mutable? is provided as true to [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29), then mutable values in v are replaced by immutable values when the result is decoded by [fasl->s-exp](#%28def._%28%28lib._racket%2Ffasl..rkt%29._fasl-~3es-exp%29%29). Unless datum-intern? is provided as #f, then any immutable value produced by [fasl->s-exp](#%28def._%28%28lib._racket%2Ffasl..rkt%29._fasl-~3es-exp%29%29) is filtered by [datum-intern-literal](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-intern-literal%29%29). The defaults make the composition of [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29) and [fasl->s-exp](#%28def._%28%28lib._racket%2Ffasl..rkt%29._fasl-~3es-exp%29%29) behave like the composition of [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29) and [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29).\nIf skip-prefix? is not #f, then a prefix that identifies the stream as a serialization is not written by [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29) or read by [fasl->s-exp](#%28def._%28%28lib._racket%2Ffasl..rkt%29._fasl-~3es-exp%29%29). Omitting a prefix can save a small amount of space, which can useful when serializing small values, but it gives up a sanity check on the [fasl->s-exp](#%28def._%28%28lib._racket%2Ffasl..rkt%29._fasl-~3es-exp%29%29) that is often useful."} {"text": "# 13.9 Serialization\nThe byte-string encoding produced by [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29) is independent of the Racket version, except as future Racket versions introduce extensions that are not currently recognized. In particular, the result of [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29) will be valid as input to any future version of [fasl->s-exp](#%28def._%28%28lib._racket%2Ffasl..rkt%29._fasl-~3es-exp%29%29) (as long as the skip-prefix? arguments are consistent).\nExamples:\n> ```racket\n> > ( define fasl ( s-exp->fasl ( list # ( \"speed\" ) ' racer #\\! ) ) )\n> > fasl\n> #\"racket/fasl:\\0\\24\\34\\3 \\1\\23\\5speed\\16\\5racer\\r!\"\n> > ( fasl->s-exp fasl )\n> '(#(\"speed\") racer #\\!)\n> ```\nChanged in version 6.90.0.21 of package base: Made [s-exp->fasl](#%28def._%28%28lib._racket%2Ffasl..rkt%29._s-exp-~3efasl%29%29) format version-independent and added the #:keep-mutable? and #:datum-intern? arguments. \nChanged in version 7.3.0.7: Added support for [correlated objects](linklets.html#%28tech._correlated._object%29). \nChanged in version 7.5.0.3: Added the #:handle-fail argument. \nChanged in version 7.5.0.9: Added the #:external-lift? and #:external-lifts arguments. \nChanged in version 8.9.0.4: Added support for [fxvectors](fixnums.html#%28tech._fxvector%29) and [flvectors](flonums.html#%28tech._flvector%29).\n------------------------------------------------------------------------"} {"text": "# 13.11 Cryptographic Hashing"} {"text": "### 13.11 Cryptographic Hashing\n> ```\n(sha1-bytes in [start end) → bytes?\n  in : (or/c bytes? input-port?)\n  start : exact-nonnegative-integer? = 0\n  end : (or/c #f exact-nonnegative-integer?) = #f\n(sha224-bytes in [start end)  →  bytes?\n  in : (or/c bytes? input-port?)\n  start : exact-nonnegative-integer? = 0\n  end : (or/c #f exact-nonnegative-integer?) = #f\n(sha256-bytes in [start end)  →  bytes?\n  in : (or/c bytes? input-port?)\n  start : exact-nonnegative-integer? = 0\n  end : (or/c #f exact-nonnegative-integer?) = #f\n```\n(parameter)\t→\t\n(-> sha1-bytes #\"abc\")```\n\n\nReturns #t if v is a namespace value, #f otherwise.\n\n> ```\n(make-empty-namespace)  →  namespace?\n```\nCreates a new namespace that is empty, and whose module registry contains only mappings for some internal, predefined modules, such as '#%kernel. The namespace’s base phase is the same as the base phase of the current namespace. Attach modules from an existing namespace to the new one with namespace-attach-module.\nThe new namespace is associated with a new root namespace, which has the same module registry as the returned namespace and has a base phase of 0. The new root namespace is the same as the returned namespace if both have base phase 0.\n> ```\n(make-base-empty-namespace)  →  namespace?```"} {"text": "# 13.11 Cryptographic Hashing\nCreates a new empty [namespace](syntax-model.html#%28tech._namespace%29) like [make-empty-namespace](#%28def._%28%28quote._~23~25kernel%29._make-empty-namespace%29%29), but with [racket/base](index.html) attached. The namespace’s [base phase](syntax-model.html#%28tech._base._phase%29) is the same as the [phase](eval-model.html#%28tech._phase%29) in which the [make-base-empty-namespace](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-base-empty-namespace%29%29) function was created.\n> ```\n(make-base-namespace)  →  namespace?\n```\nCreates a new namespace like make-empty-namespace, but with racket/base attached and required into the top-level environment. The namespace’s base phase is the same as the phase in which the make-base-namespace function was created.\n\n>
\n\n

syntax

\n\n

(define-namespace-anchor id)

\n\nBinds id to a namespace anchor that can be used with namespace-anchor → empty-namespace and namespace-anchor → namespace.\n\nThis form can be used only in a top-level context or in a module-context.\n\n> ```\n(namespace-anchor? v) → boolean?\n  v : any/c```\n\n\nReturns #t if v is a namespace-anchor value, #f otherwise.\n\n> ```\n(namespace-anchor → empty-namespace a)  →  namespace?\n  a : namespace-anchor?\n```"} {"text": "# 13.11 Cryptographic Hashing\nReturns an empty namespace that shares a module registry and root namespace with the source of the anchor, and whose base phase is the phase in which the anchor was created.\nIf the anchor is from a define-namespace-anchor form in a module context, then the source is the namespace in which the containing module is instantiated. If the anchor is from a define-namespace-anchor form in a top-level content, then the source is the namespace in which the anchor definition was evaluated.\n> ```\n(namespace-anchor → namespace a)  →  namespace?\n  a : namespace-anchor?```\nReturns a namespace corresponding to the source of the anchor.\nIf the anchor is from a [define-namespace-anchor](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-namespace-anchor%29%29) form in a module context, then the result is a namespace for the module’s body in the anchor’s phase. The result is the same as a namespace obtained via [module->namespace](#%28def._%28%28quote._~23~25kernel%29._module-~3enamespace%29%29), and the module is similarly made [available](eval-model.html#%28tech._available%29) if it is not available already.\nIf the anchor is from a [define-namespace-anchor](#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define-namespace-anchor%29%29) form in a top-level content, then the result is the namespace in which the anchor definition was evaluated.\n> ```\n(current-namespace)\t→\t\n(-> current-namespace n)\n(current-namespace n) → void?\n n\t:\t\n(-> current-namespace n)"} {"text": "# 13.11 Cryptographic Hashing\n```\n(parameter)\t→```\n\n\nSimilar to [datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29) restricted to symbols. The [lexical information](syntax-model.html#%28tech._lexical._information%29) of the resulting identifier corresponds to the top-level environment of the current namespace; the identifier has no source location or properties.\n\n> ```\n(current-namespace)\t→\t\n(-> current-namespace)\n```\n(current-namespace)\t→\t\n(-> or/c namespace? exact-integer? #f)```\nReturns an identifier whose binding is [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) in the [base phase](syntax-model.html#%28tech._base._phase%29) of where if it is a namespace, or in the where [phase level](syntax-model.html#%28tech._phase._level%29) otherwise.\nThe [lexical information](syntax-model.html#%28tech._lexical._information%29) of the identifier includes bindings (in the same [phase level](syntax-model.html#%28tech._phase._level%29)) for all syntactic forms that appear in fully expanded code (see [Fully Expanded Programs](syntax-model.html#%28part._fully-expanded%29)), but using the name reported by the second element of [identifier-binding](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._identifier-binding%29%29) for the binding; the [lexical information](syntax-model.html#%28tech._lexical._information%29) may also include other bindings.\n> ```\n(current-namespace)\t→\t\n(-> or/c (→ any) #f)"} {"text": "# 13.11 Cryptographic Hashing\n```\n(current-namespace)\t→\t\n(-> current-namespace)```\n\n\nSets the value of sym in the top-level environment of namespace in the [base phase](syntax-model.html#%28tech._base._phase%29), defining sym if it is not already defined.\n\nIf map? is supplied as true, then the namespace’s [identifier](syntax-model.html#%28tech._identifier%29) mapping is also adjusted (see [Namespaces](syntax-model.html#%28part._namespace-model%29)) in the [phase level](syntax-model.html#%28tech._phase._level%29) corresponding to the [base phase](syntax-model.html#%28tech._base._phase%29), so that sym maps to the variable.\n\nIf as-constant? is true, then the variable is made a constant (so future assignments are rejected) after v is installed as the value.\n\nChanged in version 6.90.0.14 of package base: Added the as-constant? argument.\n\n> ```\n(current-namespace)\t→\t\n(-> current-namespace)\n```\n(current-namespace)\t→\t\n(-> listof symbol?)```\nReturns a list of all symbols that are mapped to variables, syntax, and imports in namespace for the [phase level](syntax-model.html#%28tech._phase._level%29) corresponding to the [namespace](syntax-model.html#%28tech._namespace%29)’s [base phase](syntax-model.html#%28tech._base._phase%29).\n> ```\n(current-namespace)\t→\t\n(-> current-namespace)"} {"text": "# 13.11 Cryptographic Hashing\n```\n(current-namespace)\t→\t\n(-> current-namespace)```\n\n\nLike [namespace-require](#%28def._%28%28quote._~23~25kernel%29._namespace-require%29%29) for syntax exported from the module, but exported variables at the namespace’s [base phase](syntax-model.html#%28tech._base._phase%29) are treated differently: the export’s current value is copied to a top-level variable in namespace.\n\nChanged in version 6.90.0.16 of package base: Added the namespace optional argument.\n\n> ```\n(current-namespace)\t→\t\n(-> current-namespace)\n```\n(current-namespace)\t→\t\n(-> current-namespace)```\nLike [namespace-require](#%28def._%28%28quote._~23~25kernel%29._namespace-require%29%29), but only the transformer part of the module is executed relative to namespace’s [base phase](syntax-model.html#%28tech._base._phase%29); that is, the module is merely [visit](syntax-model.html#%28tech._visit%29)ed, and not [instantiate](eval-model.html#%28tech._instantiate%29)d (see [Module Expansion, Phases, and Visits](syntax-model.html#%28part._mod-parse%29)). If the required module has not been instantiated before, the module’s variables remain undefined.\nChanged in version 6.90.0.16 of package base: Added the namespace optional argument.\n> ```\n(current-namespace)\t→\t\n(-> or module-path? resolved-module-path?)"} {"text": "# 13.11 Cryptographic Hashing\n```\n(current-namespace)\t→\t\n(-> current-namespace)```\n\n\nLike [namespace-attach-module](#%28def._%28%28quote._~23~25kernel%29._namespace-attach-module%29%29), but the module specified by modname need only be declared (and not necessarily [instantiate](eval-model.html#%28tech._instantiate%29)d) in src-namespace, and the module is merely declared in dest-namespace.\n\n> ```\n(current-namespace)\t→\t\n(-> current-namespace)\n```\nChanges the inspector for the instance of the module referenced by modname in namespace’s module registry so that it is controlled by the current code inspector. The given inspector must currently control the invocation of the module in namespace’s module registry, otherwise the inspector is not changed. See also Code Inspectors.\n> ```\n(namespace-module-registry namespace)  →  any\n  namespace : namespace?```\nReturns the [module registry](syntax-model.html#%28tech._module._registry%29) of the given namespace. This value is useful only for identification via [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29).\n> ```\n(namespace-call-with-registry-lock   namespace        \n    thunk)   →   any\n  namespace : namespace?\n  thunk : ( →  any)"} {"text": "# 13.11 Cryptographic Hashing\n```\n(current-namespace)\t→\t\n(-> or/c module-path?\n resolved-module-path?\n module-path-index?)```\n\n\nReturns a namespace that corresponds to the body of an instantiated module in src-namespace’s [module registry](syntax-model.html#%28tech._module._registry%29) and in the src-namespace’s [base phase](syntax-model.html#%28tech._base._phase%29), making the module [available](eval-model.html#%28tech._available%29) for on-demand [visits](syntax-model.html#%28tech._visit%29) at src-namespace’s [base phase](syntax-model.html#%28tech._base._phase%29). The returned namespace has the same [module registry](syntax-model.html#%28tech._module._registry%29) as src-namespace. Modifying a binding in the resulting namespace changes the binding seen in modules that require the namespace’s module.\n\nModule paths in a top-level [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) expression are resolved with respect to the namespace’s module. New [provide](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._provide%29%29) declarations are not allowed.\n\nIf the current code inspector does not control the invocation of the module in src-namespace’s [module registry](syntax-model.html#%28tech._module._registry%29), the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised; see also [Code Inspectors](modprotect.html).\n\nBindings in the result namespace cannot be modified if the [compile-enforce-module-constants](eval.html#%28def._%28%28quote._~23~25kernel%29._compile-enforce-module-constants%29%29) parameter was true when the module was declared, unless the module declaration itself included assignments to the binding via [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29).\n\nChanged in version 6.90.0.16 of package base: Added the src-namespace optional argument.\n\n> ```\n(current-namespace)\t→\t\n(-> current-namespace)\n```"} {"text": "# 13.11 Cryptographic Hashing\n(parameter)\t→\t\n(-> or/c symbol? module-path-index?)```\nReturns #f if the module declaration for module-path-index defines sym and exports it unprotected, #t otherwise (which may mean that the symbol corresponds to an unexported definition, a protected export, or an identifier that is not defined at all within the module).\nThe module-path-index argument can be a symbol; see [Compiled Modules and References](Module_Names_and_Loading.html#%28part._modpathidx%29) for more information on module path indices.\nTypically, the arguments to [module-provide-protected?](#%28def._%28%28quote._~23~25kernel%29._module-provide-protected~3f%29%29) correspond to the first two elements of a list produced by [identifier-binding](stxcmp.html#%28def._%28%28quote._~23~25kernel%29._identifier-binding%29%29).\n> ```\n(variable-reference? v)  →  boolean?\n  v : any/c\n```\nReturn #t if v is a variable reference produced by #%variable-reference, #f otherwise.\n\n> ```\n(variable-reference-constant? varref)  →  boolean?\n  varref : variable-reference?```\n\n\nReturns #t if the variable represented by varref will retain its current value (i.e., varref refers to a variable that cannot be further modified by [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) or [define](define.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._define%29%29)), #f otherwise.\n\n> ```\n(variable-reference → empty-namespace varref)  →  namespace?\n  varref : variable-reference?\n```"} {"text": "# 13.11 Cryptographic Hashing\nReturns an empty namespace that shares module declarations and instances with the namespace in which varref is instantiated, and with the same phase as varref.\n> ```\n(variable-reference → namespace varref)  →  namespace?\n  varref : variable-reference?\n```\n\n\nIf varref refers to a [module-level variable](eval-model.html#%28tech._module._level._variable%29), then the result is a namespace for the module’s body in the referenced variable’s [phase](eval-model.html#%28tech._phase%29); the result is the same as a namespace obtained via [module->namespace](#%28def._%28%28quote._~23~25kernel%29._module-~3enamespace%29%29), and the module is similarly made [available](eval-model.html#%28tech._available%29) if it is not available already.\n\nIf varref refers to a [top-level variable](eval-model.html#%28tech._top._level._variable%29), then the result is the namespace in which the referenced variable is defined.\n\n> ```\n(variable-reference → resolved-module-path varref)\n  →  (or/c resolved-module-path? #f)\n  varref : variable-reference?\n```\nIf varref refers to a module-level variable, the result is a resolved module path naming the module.\nIf varref refers to a top-level variable, then the result is #f.\n> ```\n(variable-reference → module-path-index varref)\n  →  (or/c module-path-index? #f)\n  varref : variable-reference?```\nIf varref refers to a [module-level variable](eval-model.html#%28tech._module._level._variable%29), the result is a [module path index](Module_Names_and_Loading.html#%28tech._module._path._index%29) naming the module."} {"text": "# 13.11 Cryptographic Hashing\nIf varref refers to a [top-level variable](eval-model.html#%28tech._top._level._variable%29), then the result is #f.\n> ```\n(parameter)\t→\t\n(-> or/c symbol? (and/c path? complete-path?) #f)\n```\nIf varref refers to a module-level variable, the result is a path or symbol naming the module’s source (which is typically, but not always, the same as in the resolved module path). If the relevant module is a submodule, the result corresponds to the enclosing top-level module’s source.\n\nIf varref refers to a top-level variable, then the result is #f.\n\n> ```\n(variable-reference → phase varref)  →  exact-nonnegative-integer?\n  varref : variable-reference?```\n\n\nReturns the [phase](eval-model.html#%28tech._phase%29) of the variable referenced by varref.\n\n> ```\n(variable-reference → module-base-phase varref)  →  exact-integer?\n  varref : variable-reference?\n```\nReturns the phase in which the module is instantiated for the variable referenced by varref, or 0 if the variable for varref is not within a module.\nFor a variable with a module, the result is less than the result of (variable-reference → phase varref) by n when the variable is bound at phase level n within the module.\n> ```\n(variable-reference → module-declaration-inspector varref)\n  →  inspector?\n  varref : variable-reference?```"} {"text": "# 13.11 Cryptographic Hashing\nReturns the declaration [inspector](inspectors.html#%28tech._inspector%29) (see [Code Inspectors](modprotect.html)) for the module of varref, where varref must refer to an anonymous module variable as produced by ([#%variable-reference](Locations____variable-reference.html#%28form._%28%28quote._~23~25kernel%29._~23~25variable-reference%29%29)).\n> ```\n(variable-reference-from-unsafe? varref)  →  boolean?\n  varref : variable-reference?\n```\n(current-eval)\t→\t\n(-> any/c . → . any)\n(current-eval proc) → void?\n proc\t:\t\n(-> any/c . → . any)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the current evaluation handler. The evaluation handler is a procedure that takes a top-level form and evaluates it, returning the resulting values. The [evaluation handler](#%28tech._evaluation._handler%29) is called by [eval](#%28def._%28%28quote._~23~25kernel%29._eval%29%29), [eval-syntax](#%28def._%28%28quote._~23~25kernel%29._eval-syntax%29%29), the default [load handler](#%28tech._load._handler%29), and [read-eval-print-loop](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._read-eval-print-loop%29%29) to evaluate a top-level form. The handler should evaluate its argument in tail position.\n\nThe top-level-form provided to the handler can be a [syntax object](syntax-model.html#%28tech._syntax._object%29), a compiled form, a compiled form wrapped as a syntax object, or an arbitrary datum.\n\nThe default handler converts an arbitrary datum to a syntax object using [datum->syntax](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-~3esyntax%29%29), and then enriches its [lexical information](syntax-model.html#%28tech._lexical._information%29) in the same way as [eval](#%28def._%28%28quote._~23~25kernel%29._eval%29%29). (If top-level-form is a syntax object, then its [lexical information](syntax-model.html#%28tech._lexical._information%29) is not enriched.) The default evaluation handler partially expands the form to splice the body of top-level [begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) forms into the top level (see [expand-to-top-form](Expanding_Top-Level_Forms.html#%28def._%28%28quote._~23~25kernel%29._expand-to-top-form%29%29)), and then individually compiles and evaluates each spliced form before continuing to expand, compile, and evaluate later forms.\n\n> ```\n(eval top-level-form)  →  any\n  top-level-form : any/c\n(eval top-level-form namespace)  →  any\n  top-level-form : any/c\n  namespace : namespace?\n```"} {"text": "# 13.11 Cryptographic Hashing\n(parameter)\t→\t\n(-> eval-syntax stx)```\nLike [eval](#%28def._%28%28quote._~23~25kernel%29._eval%29%29), except that stx must be a syntax object, and its lexical context is not enriched before it is passed to the [evaluation handler](#%28tech._evaluation._handler%29).\n> ```\n(current-load)\t→\t\n(-> path? (or/c #f\n symbol?\n (cons/c (or/c #f symbol?)\n (non-empty-listof symbol?)))\n . → .\n any)\n(current-load proc) → void?\n proc\t:\t\n(-> path? (or/c #f\n symbol?\n (cons/c (or/c #f symbol?)\n (non-empty-listof symbol?)))\n . → .\n any)\n```\n(parameter)\t→```\n\n\n> > > \"+\"See also [Namespaces](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=eval.html%23%2528part._namespaces%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13).\n\nCalls the current [load handler](#%28tech._load._handler%29) in tail position. The call is parameterized to set [current-load-relative-directory](#%28def._%28%28quote._~23~25kernel%29._current-load-relative-directory%29%29) to the directory of file, which is resolved relative to the value of [current-directory](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29).\n\n> ```\n(load-relative file)  →  any\n  file : path-string?\n```\n(parameter)\t→```"} {"text": "# 13.11 Cryptographic Hashing\nLike [load](#%28def._%28%28quote._~23~25kernel%29._load%29%29), but [load/cd](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._load%2Fcd%29%29) sets both [current-directory](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29) and [current-load-relative-directory](#%28def._%28%28quote._~23~25kernel%29._current-load-relative-directory%29%29) before calling the [load handler](#%28tech._load._handler%29).\n> ```\n(current-load-extension)\t→\t\n(-> path? (or/c #f\n symbol?\n (cons/c (or/c #f symbol?)\n (non-empty-listof symbol?)))\n . → .\n any)\n(current-load-extension proc) → void?\n proc\t:\t\n(-> path? (or/c #f\n symbol?\n (cons/c (or/c #f symbol?)\n (non-empty-listof symbol?)))\n . → .\n any)\n```\n(Unix)\t→```\n\n\nSets [current-load-relative-directory](#%28def._%28%28quote._~23~25kernel%29._current-load-relative-directory%29%29) like [load](#%28def._%28%28quote._~23~25kernel%29._load%29%29), and calls the [extension-load handler](#%28tech._extension._load._handler%29) in tail position.\n\nExtensions are supported only when ([system-type](runtime.html#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) 'vm) returns 'racket.\n\n> ```\n(load-relative-extension file)  →  any\n  file : path-string?\n```\n(parameter)\t→\t\n(-> path? (or/c #f\n symbol?\n (cons/c (or/c #f symbol?)\n (non-empty-listof symbol?)))\n . → . any)```"} {"text": "# 13.11 Cryptographic Hashing\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the current compiled-load handler to load from a file that may have a compiled form. The [compiled-load handler](#%28tech._compiled._load._handler%29) is called by [load/use-compiled](#%28def._%28%28quote._~23~25kernel%29._load%2Fuse-compiled%29%29).\nThe protocol for a [compiled-load handler](#%28tech._compiled._load._handler%29) is the same as for the [load handler](#%28tech._load._handler%29) (see [current-load](#%28def._%28%28quote._~23~25kernel%29._current-load%29%29)), except that a [compiled-load handler](#%28tech._compiled._load._handler%29) is expected to set [current-load-relative-directory](#%28def._%28%28quote._~23~25kernel%29._current-load-relative-directory%29%29) itself. Additionally, the default [compiled-load handler](#%28tech._compiled._load._handler%29) does the following:\n- When the given path ends with \".rkt\", no \".rkt\" file exists, and when the handler’s second argument is not #f, the default [compiled-load handler](#%28tech._compiled._load._handler%29) checks for a \".ss\" file.\n- The default [compiled-load handler](#%28tech._compiled._load._handler%29) checks for the opportunity to load from \".zo\" (bytecode) files and, when ([system-type](runtime.html#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) 'vm) returns 'racket, for \".so\" (native Unix), \".dll\" (native Windows), or \".dylib\" (native Mac OS) files."} {"text": "# 13.11 Cryptographic Hashing\n- When the default [compiled-load handler](#%28tech._compiled._load._handler%29) needs to load from the given path, the given path does not exist, and when the handler’s second argument is not #f, the default [compiled-load handler](#%28tech._compiled._load._handler%29) returns without raising an exception.\nThe check for a compiled file occurs whenever the given path file ends with any extension (e.g., \".rkt\" or \".scrbl\"), and the check consults the subdirectories indicated by the [current-compiled-file-roots](#%28def._%28%28quote._~23~25kernel%29._current-compiled-file-roots%29%29) and [use-compiled-file-paths](#%28def._%28%28quote._~23~25kernel%29._use-compiled-file-paths%29%29) parameters relative to file, where the former supplies “roots” for compiled files and the latter provides subdirectories. See also [compiler/compilation-path](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=api_compile-path.html&version=8.18.0.13). A “root” can be an absolute path, in which case file’s directory is combined with [reroot-path](Manipulating_Paths.html#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._reroot-path%29%29) and the root as the second argument; if the “root” is a relative path, then the relative path is instead suffixed onto the directory of file. The roots are tried in order, and the subdirectories are checked in order within each root. A \".zo\" version of the file (whose name is formed by passing file and #\".zo\" to [path-add-extension](Manipulating_Paths.html#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._path-add-extension%29%29)) is loaded if it exists directly in one of the indicated subdirectories, or when ([system-type](runtime.html#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) 'vm) returns 'racket, then a \".so\"/\".dll\"/\".dylib\" version of the file is loaded if it exists within a \"native\" subdirectory of a [use-compiled-file-paths](#%28def._%28%28quote._~23~25kernel%29._use-compiled-file-paths%29%29) directory, in an even deeper subdirectory as named by [system-library-subpath](runtime.html#%28def._%28%28quote._~23~25kernel%29._system-library-subpath%29%29). A compiled file is loaded only if it checks out according to ([use-compiled-file-check](#%28def._%28%28quote._~23~25kernel%29._use-compiled-file-check%29%29)); with the default parameter value of 'modify-seconds, a compiled file is used only if its modification date is not older than the date for file. If both \".zo\" and \".so\"/\".dll\"/\".dylib\" files are available when ([system-type](runtime.html#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) 'vm) returns 'racket, the \".so\"/\".dll\"/\".dylib\" file is used. If file ends with \".rkt\", no such file exists, the handler’s second argument is a symbol, and a \".ss\" file exists, then \".zo\" and \".so\"/\".dll\"/\".dylib\" files are used only with names based on file with its suffixed replaced by \".ss\"."} {"text": "# 13.11 Cryptographic Hashing\nWhile a \".zo\", \".so\", \".dll\", or \".dylib\" file is loaded, the current [load-relative](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._load-relative%29%29) directory is set to the directory of the original file. If the file to be loaded has the suffix \".ss\" while the requested file has the suffix \".rkt\", then the [current-module-declare-source](Module_Names_and_Loading.html#%28def._%28%28quote._~23~25kernel%29._current-module-declare-source%29%29) parameter is set to the full path of the loaded file, otherwise the [current-module-declare-source](Module_Names_and_Loading.html#%28def._%28%28quote._~23~25kernel%29._current-module-declare-source%29%29) parameter is set to #f.\nIf the original file is loaded or a \".zo\" variant is loaded, the [load handler](#%28tech._load._handler%29) is called to load the file. If any other kind of file is loaded, the [extension-load handler](#%28tech._extension._load._handler%29) is called."} {"text": "# 13.11 Cryptographic Hashing\nWhen the default [compiled-load handler](#%28tech._compiled._load._handler%29) loads a module from a bytecode (i.e., \".zo\") file, the handler records the bytecode file path in the current namespace’s [module registry](syntax-model.html#%28tech._module._registry%29). More specifically, the handler records the path for the top-level module of the loaded module, which is an enclosing module if the loaded module is a submodule. Thereafter, loads via the default [compiled-load handler](#%28tech._compiled._load._handler%29) for modules within the same top-level module use the recorded file, independent of the file that otherwise would be selected by the [compiled-load handler](#%28tech._compiled._load._handler%29) (e.g., even if the [use-compiled-file-paths](#%28def._%28%28quote._~23~25kernel%29._use-compiled-file-paths%29%29) parameter value changes). The default [module name resolver](Module_Names_and_Loading.html#%28tech._module._name._resolver%29) transfers bytecode-file information when a module declaration is attached to a new namespace. This protocol supports independent but consistent loading of submodules from bytecode files.\n> ```\n(load/use-compiled file)  →  any\n  file : path-string?"} {"text": "# 13.11 Cryptographic Hashing\n```\n(current-load-relative-directory)\t→\t\n(-> or/c (and/c path-string? complete-path?) #f)\n(current-load-relative-directory path) → void?\n path\t:\t\n(-> or/c (and/c path-string? complete-path?) #f)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that is set by [load](#%28def._%28%28quote._~23~25kernel%29._load%29%29), [load-relative](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._load-relative%29%29), [load-extension](#%28def._%28%28quote._~23~25kernel%29._load-extension%29%29), [load-relative-extension](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._load-relative-extension%29%29), and the default [compiled-load handler](#%28tech._compiled._load._handler%29), and used by [load-relative](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._load-relative%29%29), [load-relative-extension](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._load-relative-extension%29%29), and the default [compiled-load handler](#%28tech._compiled._load._handler%29).\n\nWhen a new path or string is provided as the parameter’s value, it is immediately expanded (see [Paths](pathutils.html)) and converted to a path. (The directory need not exist.)\n\n> ```\n(use-compiled-file-paths)\t→\t\n(-> listof (and/c path? relative-path?))\n(use-compiled-file-paths paths) → void?\n paths\t:\t\n(-> listof (and/c path? relative-path?))\n```\n(current-compiled-file-roots)\t→\t\n(-> see current-load/use-compiled)\n(current-compiled-file-roots paths) → void?\n paths\t:\t\n(-> see current-load/use-compiled)```"} {"text": "# 13.11 Cryptographic Hashing\nA list of paths and 'sames that is used by the default [compiled-load handler](#%28tech._compiled._load._handler%29) (see [current-load/use-compiled](#%28def._%28%28quote._~23~25kernel%29._current-load%2Fuse-compiled%29%29)).\nThe parameter is normally initialized to ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) 'same), but the parameter’s initial value can be adjusted by the installation configuration as reported by ([find-compiled-file-roots](#%28def._%28%28quote._~23~25kernel%29._find-compiled-file-roots%29%29)), and it can be further adjusted by the PLTCOMPILEDROOTS environment variable or the --compiled or -R command-line flag for racket. If the environment variable is defined and not overridden by a command-line flag, it is parsed by first replacing any @(version) with the result of ([version](runtime.html#%28def._%28%28quote._~23~25kernel%29._version%29%29)), then using [path-list-string->path-list](Filesystem.html#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._path-list-string-~3epath-list%29%29) with a path list produced by ([find-compiled-file-roots](#%28def._%28%28quote._~23~25kernel%29._find-compiled-file-roots%29%29)) to arrive at the parameter’s initial value.\n> ```\n(find-compiled-file-roots)  →  (listof (or/c path? 'same))"} {"text": "# 13.11 Cryptographic Hashing\n```\n(find-config-dir)\t→\t\n(-> or/c 'modify-seconds 'exists)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines how a compiled file is checked against its source to enable use of the compiled file. By default, the file-check mode is 'modify-seconds, which uses a compiled file when its filesystem modification date is at least as new as the source file’s. The 'exists mode causes a compiled file to be used in place of its source as long as the compiled file exists.\n\nIf the PLT_COMPILED_FILE_CHECK environment variable is set to modify-seconds or exists, then the environment variable’s value configures the parameter when Racket starts.\n\nAdded in version 6.6.0.3 of package base.\n\n> ```\n(read-eval-print-loop)  →  any\n```\n(current-prompt-read)\t→\t\n(-> any)\n(current-prompt-read proc) → void?\n proc\t:\t\n(-> any)```"} {"text": "# 13.11 Cryptographic Hashing\nA [parameter](eval-model.html#%28tech._parameter%29) that determines a prompt read handler, which is a procedure that takes no arguments, displays a prompt string, and returns a top-level form to evaluate. The prompt read handler is called by [read-eval-print-loop](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._read-eval-print-loop%29%29), and after printing a prompt, the handler typically should call the [read interaction handler](#%28tech._read._interaction._handler%29) (as determined by the [current-read-interaction](#%28def._%28%28quote._~23~25kernel%29._current-read-interaction%29%29) parameter) with the port produced by the [interaction port handler](#%28tech._interaction._port._handler%29) (as determined by the [current-get-interaction-input-port](#%28def._%28%28quote._~23~25kernel%29._current-get-interaction-input-port%29%29) parameter).\nThe default prompt read handler prints \\>  and returns the result of\n> ```racket\n> ( let ( [ in ( ( current-get-interaction-input-port ) ) ] )\n> ( ( current-read-interaction ) ( object-name in ) in ) )\n> ```"} {"text": "# 13.11 Cryptographic Hashing\nIf the input and output ports are both terminals (in the sense of [terminal-port?](port-ops.html#%28def._%28%28quote._~23~25kernel%29._terminal-port~3f%29%29)) and if the output port appears to be counting lines (because [port-next-location](linecol.html#%28def._%28%28quote._~23~25kernel%29._port-next-location%29%29) returns a non-#f line and column), then the output port’s line is incremented and its column is reset to 0 via [set-port-next-location!](linecol.html#%28def._%28%28quote._~23~25kernel%29._set-port-next-location%21%29%29) before returning the read result.\n> ```\n(current-get-interaction-input-port)\t→\t\n(-> input-port?)\n(current-get-interaction-input-port proc) → void?\n proc\t:\t\n(-> input-port?)"} {"text": "# 13.11 Cryptographic Hashing\n```\n(current-get-interaction-evt)\t→\t\n(-> evt?)\n(current-get-interaction-evt proc) → void?\n proc\t:\t\n(-> evt?)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the interaction event handler, which returns an [synchronizable event](sync.html#%28tech._synchronizable._event%29) that should be used in combination with blocking that is similar to [read-eval-print-loop](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._read-eval-print-loop%29%29) waiting for input—but where an input port is not read directly, so [current-get-interaction-input-port](#%28def._%28%28quote._~23~25kernel%29._current-get-interaction-input-port%29%29) does not apply.\n\nWhen the interaction event handler returns an event that becomes ready, and when the event’s ready value is a procedure, then the procedure is meant to be called with zero arguments blocking resumes. The default interaction event handler returns [never-evt](sync.html#%28def._%28%28quote._~23~25kernel%29._never-evt%29%29).\n\nThe [racket/gui/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=gui&rel=index.html&version=8.18.0.13) library adjusts this parameter’s value by extending the current value. The extension combines the current value’s result with [choice-evt](sync.html#%28def._%28%28quote._~23~25kernel%29._choice-evt%29%29) and an event that becomes ready when a GUI event is available, and the event’s value is a procedure that yields to one or more available GUI events.\n\nAdded in version 8.3.0.3 of package base.\n\n> ```\n(current-read-interaction)\t→\t\n(-> any/c input-port? . → . any)\n(current-read-interaction proc) → void?\n proc\t:\t\n(-> any/c input-port? . → . any)\n```"} {"text": "# 13.11 Cryptographic Hashing\n(current-print)\t→\t\n(-> any/c . → . any)\n(current-print proc) → void?\n proc\t:\t\n(-> any/c . → . any)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the print handler that is called by [read-eval-print-loop](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._read-eval-print-loop%29%29) to print the result of an evaluation (and the result is ignored).\nThe default [print handler](#%28tech._print._handler%29) [print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29)s the value to the current output port (as determined by the [current-output-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._current-output-port%29%29) parameter) and then outputs a newline, except that it prints nothing when the value is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13).\n> ```\n(current-compile)\t→\t\n(-> any/c boolean? . → . compiled-expression?)\n(current-compile proc) → void?\n proc\t:\t\n(-> any/c boolean? . → . compiled-expression?)\n```\n(parameter)\t→```\n\n\nLike [eval](#%28def._%28%28quote._~23~25kernel%29._eval%29%29), but calls the current [compilation handler](#%28tech._compilation._handler%29) in tail position with top-level-form.\n\n> ```\n(compile-syntax stx)  →  compiled-expression?\n  stx : syntax?\n```\nLike eval-syntax, but calls the current compilation handler in tail position with stx.\n> ```\n(compiled-expression-recompile ce)  →  compiled-expression?\n  ce : compiled-expression?```"} {"text": "# 13.11 Cryptographic Hashing\nRecompiles ce. If ce was compiled as machine-independent and [current-compile-target-machine](#%28def._%28%28quote._~23~25kernel%29._current-compile-target-machine%29%29) is not set to #f, then recompiling effectively converts to the current machine format. Otherwise, recompiling effectively re-runs optimization passes to produce an equivalent compiled form with potentially different performance characteristics.\nAdded in version 6.3 of package base.\n> ```\n(compiled-expression-add-target-machine   ce  \n    other-ce)  \n  →  compiled-expression?\n  ce : compiled-expression?\n  other-ce : (or/c compiled-expression? hash?)\n```\n(parameter)\t→```\n\n\nReturns a value that has the same information as other-ce for [compiled-expression-add-target-machine](#%28def._%28%28quote._~23~25kernel%29._compiled-expression-add-target-machine%29%29), but in a form that can be portably serialized via [racket/fasl](fasl.html).\n\nAdded in version 8.17.0.3 of package base.\n\n> ```\n(compiled-expression? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a compiled form, #f otherwise.\n> ```\n(compile-enforce-module-constants)\t→\t\n(-> compile-enforce-module-constants on?)"} {"text": "# 13.11 Cryptographic Hashing\n```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines how a module declaration is compiled.\n\nWhen constants are enforced, and when the macro-expanded body of a module contains no [set!](set_.html#%28form._%28%28quote._~23~25kernel%29._set%21%29%29) assignment to a particular variable defined within the module, then the variable is marked as constant when the definition is evaluated. Afterward, the variable’s value cannot be assigned or undefined through [module->namespace](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._module-~3enamespace%29%29), and it cannot be defined by redeclaring the module.\n\nEnforcing constants allows the compiler to inline some variable values, and it allows the native-code just-in-time compiler to generate code that skips certain run-time checks.\n\n> ```\n(parameter)\t→\t\n(-> compile-allow-set!-undefined allow?)\n```\n(compile-context-preservation-enabled)\t→\t\n(-> compile-context-preservation-enabled on?)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines whether compilation should avoid function-call inlining and other optimizations that may cause information to be lost from stack traces (as reported by [continuation-mark-set->context](contmarks.html#%28def._%28%28quote._~23~25kernel%29._continuation-mark-set-~3econtext%29%29)). The default is #f, which allows such optimizations.\n> ```"} {"text": "# 13.11 Cryptographic Hashing\n(current-compile-target-machine)\t→\t\n(-> or/c #f (and/c symbol? compile-target-machine?))\n(current-compile-target-machine target) → void?\n target\t:\t\n(-> or/c #f (and/c symbol? compile-target-machine?))\n```\n(parameter)\t→```\n\n\nReports whether sym is a supported compilation target for the currently running Racket.\n\nWhen ([system-type](runtime.html#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) 'vm) reports 'racket, then the only target symbol is 'racket. When ([system-type](runtime.html#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) 'vm) reports 'chez-scheme, then a symbol corresponding to the current platform is a target, and other targets may also be supported. The 'target-machine mode of [system-type](runtime.html#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) reports the running Racket’s native target machine.\n\nAdded in version 7.1.0.6 of package base.\n\n> ```\n(current-compile-realm)\t→\t\n(-> current-compile-realm realm)\n(current-compile-realm realm) → void?\n realm\t:\t\n(-> current-compile-realm realm)\n```\nDetermines the realm that is assigned to modules and procedures when they are compiled.\nAdded in version 8.4.0.2 of package base.\n> ```\n(eval-jit-enabled)\t → \t\n( → eval-jit-enabled on?)```"} {"text": "# 13.11 Cryptographic Hashing\n> > > \"+\"See also [Bytecode, Machine Code, and Just-in-Time (JIT) Compilers](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=performance.html%23%2528part._.J.I.T%2529&version=8.18.0.13) in [The Racket Guide](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=index.html&version=8.18.0.13).\nA [parameter](eval-model.html#%28tech._parameter%29) that determines whether the native-code just-in-time compiler (JIT) is enabled for code (compiled or not) that is passed to the default evaluation handler. A true parameter value is effective only on platforms for which the JIT is supported and for Racket virtual machines that rely on a JIT.\nThe default is #t, unless the JIT is not supported by the current platform but is supported on the same virtual machine for other platforms, unless it is disabled through the -j/--no-jit command-line flag to stand-alone Racket (or GRacket), and unless it is disabled through the PLTNOMZJIT environment variable (set to any value).\n> ```\n(load-on-demand-enabled)\t→\t\n(-> load-on-demand-enabled on?)\n```\n(parameter)\t→```\n\n\nReturns #t if v is a [resolved module path](#%28tech._resolved._module._path%29), #f otherwise.\n\n> ```\n(parameter)\t→\t\n(-> or/c symbol?\n (and/c path? complete-path?)\n (cons/c (or/c symbol?\n (and/c path? complete-path?))\n (non-empty-listof symbol?)))\n```"} {"text": "# 13.11 Cryptographic Hashing\n(parameter)\t→\t\n(-> or/c symbol?\n (and/c path? complete-path?)\n (cons/c (or/c symbol?\n (and/c path? complete-path?))\n (non-empty-listof symbol?)))```\nReturns the path or symbol encapsulated by a [resolved module path](#%28tech._resolved._module._path%29). A list result corresponds to a [submodule](eval-model.html#%28tech._submodule%29) path.\n> ```\n(module-path? v)  →  boolean?\n  v : any/c\n```\n(current-module-name-resolver)\t→\t\n(-> case →\n (resolved-module-path? (or/c #f namespace?) . → . any)\n (module-path?\n (or/c #f resolved-module-path?)\n (or/c #f syntax?)\n boolean?\n . → .\n resolved-module-path?))\n(current-module-name-resolver proc) → void?\n proc\t:\t\n(-> case →\n (resolved-module-path? (or/c #f namespace?) . → . any)\n (module-path?\n (or/c #f resolved-module-path?)\n (or/c #f syntax?)\n boolean?\n . → .\n resolved-module-path?))```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the current module name resolver, which manages the conversion from other kinds of module references to a [resolved module path](#%28tech._resolved._module._path%29). For example, when the expander encounters ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) module-path) where module-path is not an identifier, then the expander passes 'module-path to the module name resolver to obtain a symbol or resolved module path. When such a [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) appears within a module, the module path resolver is also given the name of the enclosing module, so that a relative reference can be converted to an absolute symbol or [resolved module path](#%28tech._resolved._module._path%29).\n\nThe default [module name resolver](#%28tech._module._name._resolver%29) uses [collection-file-path](collects.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._collection-file-path%29%29) to convert [lib](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lib%29%29) and symbolic-shorthand module paths to filesystem paths. The [collection-file-path](collects.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._collection-file-path%29%29) function, in turn, uses the [current-library-collection-links](collects.html#%28def._%28%28quote._~23~25kernel%29._current-library-collection-links%29%29) and [current-library-collection-paths](collects.html#%28def._%28%28quote._~23~25kernel%29._current-library-collection-paths%29%29) parameters.\n\nA [module name resolver](#%28tech._module._name._resolver%29) takes two and four arguments:\n\n- When given two arguments, the first is a name for a module that is now declared in the current namespace, and the second is optionally a namespace from which the declaration was copied. The module name resolver’s result in this case is ignored.\n\n The current module name resolver is called with two arguments by [namespace-attach-module](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._namespace-attach-module%29%29) or [namespace-attach-module-declaration](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._namespace-attach-module-declaration%29%29) to notify the resolver that a module declaration was attached to the current namespace (and should not be loaded in the future for the namespace’s [module registry](syntax-model.html#%28tech._module._registry%29)). Evaluation of a module declaration also calls the current module name resolver with two arguments, where the first is the declared module and the second is #f. No other Racket operation invokes the module name resolver with two arguments, but other tools (such as DrRacket) might call this resolver in this mode to avoid redundant module loads.\n\n- When given four arguments, the first is a module path, equivalent to a quoted module-path for [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29). The second is name for the source module, if any, to which the path is relative; if the second argument is #f, the module path is relative to ([or](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29) ([current-load-relative-directory](eval.html#%28def._%28%28quote._~23~25kernel%29._current-load-relative-directory%29%29)) ([current-directory](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29))). The third argument is a [syntax object](syntax-model.html#%28tech._syntax._object%29) that can be used for error reporting, if it is not #f. If the last argument is #t, then the module declaration should be loaded (if it is not already), otherwise the module path should be simply resolved to a name. The result is the resolved name.\n\nFor the second case, the standard module name resolver keeps a table per [module registry](syntax-model.html#%28tech._module._registry%29) containing loaded module name. If a resolved module path is not in the table, and #f is not provided as the fourth argument to the [module name resolver](#%28tech._module._name._resolver%29), then the name is put into the table and the corresponding file is loaded with a variant of [load/use-compiled](eval.html#%28def._%28%28quote._~23~25kernel%29._load%2Fuse-compiled%29%29) that passes the expected module name to the [compiled-load handler](eval.html#%28tech._compiled._load._handler%29).\n\nWhile loading a file, the default [module name resolver](#%28tech._module._name._resolver%29) sets the [current-module-declare-name](#%28def._%28%28quote._~23~25kernel%29._current-module-declare-name%29%29) parameter to the resolved module name (while the [compiled-load handler](eval.html#%28tech._compiled._load._handler%29) sets [current-module-declare-source](#%28def._%28%28quote._~23~25kernel%29._current-module-declare-source%29%29)). Also, the default [module name resolver](#%28tech._module._name._resolver%29) records in a private [continuation mark](eval-model.html#%28tech._continuation._mark%29) the module being loaded, and it checks whether such a mark already exists; if such a continuation mark does exist in the current continuation, then the [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) exception is raised with a message about a dependency cycle.\n\nThe default module name resolver cooperates with the default [compiled-load handler](eval.html#%28tech._compiled._load._handler%29): on a module-attach notification, bytecode-file information recorded by the [compiled-load handler](eval.html#%28tech._compiled._load._handler%29) for the source namespace’s [module registry](syntax-model.html#%28tech._module._registry%29) is transferred to the target namespace’s [module registry](syntax-model.html#%28tech._module._registry%29).\n\nThe default module name resolver also maintains a small, [module registry](syntax-model.html#%28tech._module._registry%29)-specific cache that maps [lib](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lib%29%29) and symbolic module paths to their resolutions. This cache is consulted before checking parameters such as [current-library-collection-links](collects.html#%28def._%28%28quote._~23~25kernel%29._current-library-collection-links%29%29) and [current-library-collection-paths](collects.html#%28def._%28%28quote._~23~25kernel%29._current-library-collection-paths%29%29), so results may “stick” even if those parameter values change. An entry is added to the cache only when the fourth argument to the module name resolver is true (indicating that a module should be loaded) and only when loading succeeds.\n\nFinally, the default module name resolver potentially treats a [submod](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._submod%29%29) path specially. If the module path as the first element of the [submod](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._submod%29%29) form refers to non-existent collection, then instead of raising an exception, the default module name resolver synthesizes an uninterned symbol module name for the resulting [resolved module path](#%28tech._resolved._module._path%29). This special treatment of submodule paths is consistent with the special treatment of nonexistent submodules by the [compiled-load handler](eval.html#%28tech._compiled._load._handler%29), so that [module-declared?](#%28def._%28%28quote._~23~25kernel%29._module-declared~3f%29%29) can be used more readily to check for the existence of a submodule.\n\nModule loading is suppressed (i.e., #f is supplied as a fourth argument to the module name resolver) when resolving module paths in [syntax objects](syntax-model.html#%28tech._syntax._object%29) (see [Syntax Objects](syntax-model.html#%28part._stxobj-model%29)). When a [syntax object](syntax-model.html#%28tech._syntax._object%29) is manipulated, the current namespace might not match the original namespace for the syntax object, and the module should not necessarily be loaded in the current namespace.\n\nFor historical reasons, the default module name resolver currently accepts three arguments, in addition to two and four. Three arguments are treated the same as four arguments with the fourth argument as #t, except that an error is also logged. Support for three arguments will be removed in a future version.\n\nThe [current-module-name-resolver](#%28def._%28%28quote._~23~25kernel%29._current-module-name-resolver%29%29) binding is provided as [protected](modprotect.html#%28tech._protected%29) in the sense of [protect-out](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._protect-out%29%29).\n\nChanged in version 6.0.1.12 of package base: Added error logging to the default module name resolver when called with three arguments. \nChanged in version 7.0.0.17: Added special treatment of [submod](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._submod%29%29) forms with a nonexistent collection by the default module name resolver. \nChanged in version 8.2.0.4: Changed binding to [protected](modprotect.html#%28tech._protected%29).\n\n> ```\n(current-module-declare-name)\t→\t\n(-> or/c resolved-module-path? #f)\n(current-module-declare-name name) → void?\n name\t:\t\n(-> or/c resolved-module-path? #f)\n```"} {"text": "# 13.11 Cryptographic Hashing\n(current-module-declare-source)\t→\t\n(-> or/c symbol? (and/c path? complete-path?) #f)\n(current-module-declare-source src) → void?\n src\t:\t\n(-> or/c symbol? (and/c path? complete-path?) #f)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines source information to be associated with a module when evaluating a [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) declaration. Source information is used in error messages and reflected by [variable-reference->module-source](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._variable-reference-~3emodule-source%29%29). When the parameter value is #f, the module’s name (as determined by [current-module-declare-name](#%28def._%28%28quote._~23~25kernel%29._current-module-declare-name%29%29)) is used as the source name instead of the parameter value.\n> ```\n(current-module-path-for-load)\t→\t\n(-> or/c #f module-path?\n (and/c syntax?\n (lambda (stx)\n (module-path? (syntax → datum s)))))\n(current-module-path-for-load path) → void?\n path\t:\t\n(-> or/c #f module-path?\n (and/c syntax?\n (lambda (stx)\n (module-path? (syntax → datum s)))))\n```\n(parameter)\t→```\n\n\nReturns #t if v is a [module path index](#%28tech._module._path._index%29), #f otherwise.\n\n> ```\n(module-path-index-resolve mpi\n   [ load?        \n    src-stx)   →   resolved-module-path?\n\n  mpi : module-path-index?\n  load? : any/c = #f\n  src-stx : (or/c syntax? #f) = #f\n```\n(parameter)\t→\t\n(-> or/c module-path? #f)```"} {"text": "# 13.11 Cryptographic Hashing\nReturns two values: a module path, and a base path—either a [module path index](#%28tech._module._path._index%29), [resolved module path](#%28tech._resolved._module._path%29), or #f—to which the first path is relative.\nA #f second result means that the path is relative to an unspecified directory (i.e., its resolution depends on the value of [current-load-relative-directory](eval.html#%28def._%28%28quote._~23~25kernel%29._current-load-relative-directory%29%29) and/or [current-directory](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29)).\nA #f for the first result implies a #f for the second result, and means that mpi represents “self” (see above). Such a [module path index](#%28tech._module._path._index%29) may have a non-#f submodule path as reported by [module-path-index-submodule](#%28def._%28%28quote._~23~25kernel%29._module-path-index-submodule%29%29).\n> ```\n(parameter)\t→\t\n(-> or/c #f (non-empty-listof symbol?))\n```\n(parameter)\t→\t\n(-> or/c module-path? #f)```\n\n\nCombines path, base, and submod to create a new [module path index](#%28tech._module._path._index%29). The path argument can be #f only if base is also #f. The submod argument can be a list only when path and base are both #f.\n\n> ```\n(compiled-module-expression? v)  →  boolean?\n  v : any/c\n```\n(parameter)\t→\t\n(-> or/c symbol? (cons/c symbol? (non-empty-listof symbol?)))```\nTakes a module declaration in compiled form and either gets the module’s declared name (when name is not provided) or returns a revised module declaration with the given name."} {"text": "# 13.11 Cryptographic Hashing\nThe name is a symbol for a top-level module, or a symbol paired with a list of symbols where the list reflects the [submodule](eval-model.html#%28tech._submodule%29) path to the module starting with the top-level module’s declared name.\n> ```\n(module-compiled-submodules   compiled-module-code  \n    non-star?)  \n  →  (listof compiled-module-expression?)\n  compiled-module-code : compiled-module-expression?\n  non-star? : any/c\n(module-compiled-submodules   compiled-module-code  \n    non-star?  \n    submodules)  \n  →  compiled-module-expression?\n  compiled-module-code : compiled-module-expression?\n  non-star? : any/c\n  submodules : (listof compiled-module-expression?)"} {"text": "# 13.11 Cryptographic Hashing\n```\nTakes a module declaration in compiled form and either gets the module’s submodules (when submodules is not provided) or returns a revised module declaration with the given submodules. The non-star? argument determines whether the result or new submodule list corresponds to module declarations (when non-star? is true) or module* declarations (when non-star? is #f).\n\n> ```\n(module-compiled-imports compiled-module-code)\n  →   ( listof ( cons/c ( or/c exact-integer? #f )\n> ( listof module-path-index? ) ) )\n\n  compiled-module-code : compiled-module-expression?```\n\n\nTakes a module declaration in compiled form and returns an association list mapping [phase level](syntax-model.html#%28tech._phase._level%29) shifts (where #f corresponds to a shift into the [label phase level](syntax-model.html#%28tech._label._phase._level%29)) to module references for the module’s explicit imports.\n\n> ```\n(module-compiled-exports compiled-module-code\n   [ verbosity)  \n\n  →   (listof (cons/c phase+space? list?))\n(listof (cons/c phase+space? list?))\n\n  compiled-module-code : compiled-module-expression?\n  verbosity : (or/c #f 'defined-names) = #f\n```\n(possibly)\t→\t\n(-> listof (cons/c exact-integer? (listof symbol?)))```\nReturns an association list mapping [phase level](syntax-model.html#%28tech._phase._level%29) values to symbols that represent variables within the module. These definitions are not directly accessible from source, but they are accessible from bytecode, and the order of the symbols in each list corresponds to an order for bytecode access."} {"text": "# 13.11 Cryptographic Hashing\nAdded in version 6.5.0.5 of package base.\n> ```\n(parameter)\t→\t\n(-> or/c #f (vector/c module-path? symbol? any/c))\n```\n> > > \"+\"See also Module-Handling Configuration in The Racket Guide.\n\nReturns information intended to reflect the “language” of the module’s implementation as originally attached to the syntax of the module’s declaration though the 'module-language syntax property. See also module.\n\nIf no information is available for the module, the result is #f. Otherwise, the result is (vector mp name val) such that ((dynamic-require mp name) val) should return function that takes two arguments. The function’s arguments are a key for reflected information and a default value. Acceptable keys and the interpretation of results is up to external tools, such as DrRacket. If no information is available for a given key, the result should be the given default value.\n\nSee also module → language-info and racket/language-info.\n\n> ```\n(module-compiled-cross-phase-persistent? compiled-module-code)\n  →  boolean?\n  compiled-module-code : compiled-module-expression?```\n\n\nReturns #t if compiled-module-code represents a [cross-phase persistent](eval-model.html#%28tech._cross._phase._persistent%29) module, #f otherwise.\n\n> ```\n(parameter)\t→\n```\n(parameter)\t→\t\n(-> or/c void? any/c)```"} {"text": "# 13.11 Cryptographic Hashing\n> > > Because [dynamic-require](#%28def._%28%28quote._~23~25kernel%29._dynamic-require%29%29) is a procedure, giving a plain S-expression for mod the same way as you would for a [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) expression likely won’t give you expected results. What you need instead is something that evaluates to an S-expression; using [quote](quote.html#%28form._%28%28quote._~23~25kernel%29._quote%29%29) is one way to do it.\nDynamically [instantiates](eval-model.html#%28tech._instantiate%29) the module specified by mod in the current namespace’s registry at the namespace’s [base phase](syntax-model.html#%28tech._base._phase%29), if it is not yet [instantiate](eval-model.html#%28tech._instantiate%29)d. The current [module name resolver](#%28tech._module._name._resolver%29) may load a module declaration to resolve mod (see [current-module-name-resolver](#%28def._%28%28quote._~23~25kernel%29._current-module-name-resolver%29%29)); the path is resolved relative to [current-load-relative-directory](eval.html#%28def._%28%28quote._~23~25kernel%29._current-load-relative-directory%29%29) and/or [current-directory](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29). Beware that concurrent [dynamic-require](#%28def._%28%28quote._~23~25kernel%29._dynamic-require%29%29)s in namespaces that share a [module registry](syntax-model.html#%28tech._module._registry%29) can create race conditions; see also [namespace-call-with-registry-lock](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._namespace-call-with-registry-lock%29%29)."} {"text": "# 13.11 Cryptographic Hashing\nIf provided is #f, then the result is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13), and the module is not [visit](syntax-model.html#%28tech._visit%29)ed (see [Module Expansion, Phases, and Visits](syntax-model.html#%28part._mod-parse%29)) or even made [available](eval-model.html#%28tech._available%29) (for on-demand [visits](syntax-model.html#%28tech._visit%29)) in phases above the [base phase](syntax-model.html#%28tech._base._phase%29).\nExamples:\n> ```racket\n> > ( module a racket/base ( displayln \"hello\" ) )\n> > ( dynamic-require ' ' a #f )\n> hello\n> ```\n> > > The double quoted ''a evaluates to the root-module-path 'a (see the grammar for [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29)). Using 'a for mod won’t work, because that evaluates to root-module-path a, and the example is not a module installed in a collection. Using a won’t work, because a is an undefined variable.\n> > >\n> > > Declaring ([module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) a ....) within another module, instead of in the read-eval-print loop, would create a submodule. In that case, ([dynamic-require](#%28def._%28%28quote._~23~25kernel%29._dynamic-require%29%29) ''a #f) would not access the module, because ''a does not refer to a submodule."} {"text": "# 13.11 Cryptographic Hashing\nWhen provided is a symbol, the value of the module’s export with the given name is returned, and still the module is not [visit](syntax-model.html#%28tech._visit%29)ed or made [available](eval-model.html#%28tech._available%29) in higher phases.\nExamples:\n> ```racket\n> > ( module b racket/base ( provide dessert ) ( define dessert \"gulab jamun\" ) )\n> > ( dynamic-require ' ' b ' dessert )\n> \"gulab jamun\"\n> ```\nIf the module exports provided as syntax, then syntax-thunk is called if it is a procedure, and its result is the result of the [dynamic-require](#%28def._%28%28quote._~23~25kernel%29._dynamic-require%29%29) call. If syntax-thunk is 'eval, a use of the binding is expanded and evaluated in a fresh namespace to which the module is attached, which means that the module is [visit](syntax-model.html#%28tech._visit%29)ed in the fresh namespace. The expanded syntax must return a single value.\nExamples:\n> ```racket\n> > ( module c racket/base ( require ( for-syntax racket/base ) ) ( provide dessert2 ) ( define dessert \"nanaimo bar\" ) ( define-syntax dessert2 ( make-rename-transformer #' dessert ) ) )\n> > ( dynamic-require ' ' c ' dessert2 )\n> \"nanaimo bar\"\n> ```"} {"text": "# 13.11 Cryptographic Hashing\nIf the module has no such exported variable or syntax, then fail-thunk is called, or the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised if fail-thunk is 'error. If the variable named by provided is exported protected (see [Code Inspectors](modprotect.html)), then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nIf provided is 0, then the module is [instantiate](eval-model.html#%28tech._instantiate%29)d but not [visit](syntax-model.html#%28tech._visit%29)ed, the same as when provided is #f. With 0, however, the module is made [available](eval-model.html#%28tech._available%29) in higher phases.\nIf provided is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13), then the module is [visit](syntax-model.html#%28tech._visit%29)ed but not [instantiate](eval-model.html#%28tech._instantiate%29)d (see [Module Expansion, Phases, and Visits](syntax-model.html#%28part._mod-parse%29)), and the result is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13).\nMore examples using different module-path grammar expressions are given below:\nExample:\n> ```racket\n> > ( dynamic-require ' racket/base #f )\n> ```\nExample:\n> ```racket\n> > ( dynamic-require ( list ' lib \"racket/base\" ) #f )\n> ```\nExamples:"} {"text": "# 13.11 Cryptographic Hashing\n> ```racket\n> > ( module a racket/base ( module b racket/base ( provide inner-dessert ) ( define inner-dessert \"tiramisu\" ) ) )\n> > ( dynamic-require ' ( submod ' a b ) ' inner-dessert )\n> \"tiramisu\"\n> ```\nThe last line in the above example could instead have been written as\nExample:\n> ```racket\n> > ( dynamic-require ( ( lambda ( ) ( list ' submod ' ' a ' b ) ) ) ' inner-dessert )\n> \"tiramisu\"\n> ```\nwhich is equivalent.\nChanged in version 8.16.0.3 of package base: Added the syntax-thunk argument and changed to allow 'error for fail-thunk.\n> ```\n(parameter)\t→\t\n(-> or/c symbol? #f)"} {"text": "# 13.11 Cryptographic Hashing\n```\nLike dynamic-require, but in a phase that is 1 more than the namespace’s base phase.\n\nChanged in version 8.16.0.3 of package base: Added the syntax-thunk argument and changed to allow 'error for fail-thunk.\n\n> ```\n(module-declared? mod [load?) → boolean?\n   mod   :   ( or/c module-path? module-path-index?\n> resolved-module-path? )\n\n  load? : any/c = #f```\n\n\nReturns #t if the module indicated by mod is [declare](eval-model.html#%28tech._declare%29)d (but not necessarily [instantiate](eval-model.html#%28tech._instantiate%29)d or [visit](syntax-model.html#%28tech._visit%29)ed) in the current namespace, #f otherwise.\n\nIf load? is #t and mod is not a [resolved module path](#%28tech._resolved._module._path%29), the module is loaded in the process of resolving mod (as for [dynamic-require](#%28def._%28%28quote._~23~25kernel%29._dynamic-require%29%29) and other functions). Checking for the declaration of a [submodule](eval-model.html#%28tech._submodule%29) does not trigger an exception if the submodule cannot be loaded because it does not exist, either within a root module that does exist or because the root module does not exist.\n\n> ```\n(parameter)\t→\t\n(-> or/c #f (vector/c module-path? symbol? any/c))\n```"} {"text": "# 13.11 Cryptographic Hashing\nReturns information intended to reflect the “language” of the implementation of mod. If mod is a resolved module path or load? is #f, the module named by mod must be declared (but not necessarily instantiated or visited) in the current namespace; otherwise, mod may be loaded (as for dynamic-require and other functions). The information returned by module → language-info is the same as would have been returned by module-compiled-language-info applied to the module’s implementation as compiled code.\nA module can be declared by using dynamic-require.\nExamples:\n> ```racket\n> > ( dynamic-require ' racket/dict ( void ) )\n> > ( module → language-info ' racket/dict )\n> #f\n> ```\n> ```\n(module → imports mod)\n  →   ( listof ( cons/c ( or/c exact-integer? #f )\n> ( listof module-path-index? ) ) )\n   mod   :   ( or/c module-path? module-path-index?\n> resolved-module-path? )```\nLike [module-compiled-imports](#%28def._%28%28quote._~23~25kernel%29._module-compiled-imports%29%29), but produces the imports of mod, which must be [declare](eval-model.html#%28tech._declare%29)d (but not necessarily [instantiate](eval-model.html#%28tech._instantiate%29)d or [visit](syntax-model.html#%28tech._visit%29)ed) in the current namespace. See [module->language-info](#%28def._%28%28quote._~23~25kernel%29._module-~3elanguage-info%29%29) for an example of declaring an existing module.\nExamples:"} {"text": "# 13.11 Cryptographic Hashing\n> ```racket\n> > ( module banana racket/base ( require ( only-in racket/math pi ) ) ( provide peel ) ( define peel pi ) ( define bush ( * 2 pi ) ) )\n> > ( module->imports ' ' banana )\n> '((0 # #))\n> ```\n> ```\n(module → exports mod [verbosity)\n  →   (listof (cons/c phase+space? list?))\n(listof (cons/c phase+space? list?))\n   mod   :   ( or/c module-path? module-path-index?\n> resolved-module-path? )\n  verbosity : (or/c #f 'defined-names) = #f\n```\n(parameter)\t→\t\n(-> module banana racket/base (require (only-in racket/math pi)) (provide (rename-out [ peel wrapper ])) (define peel pi) (define bush (* 2 pi)))```\n\n\nLike [module-compiled-indirect-exports](#%28def._%28%28quote._~23~25kernel%29._module-compiled-indirect-exports%29%29), but produces the indirect exports of mod, which must be [declare](eval-model.html#%28tech._declare%29)d (but not necessarily [instantiate](eval-model.html#%28tech._instantiate%29)d or [visit](syntax-model.html#%28tech._visit%29)ed) in the current namespace. See [module->language-info](#%28def._%28%28quote._~23~25kernel%29._module-~3elanguage-info%29%29) for an example of declaring an existing module.\n\nExamples:\n\n> ```racket\n> > ( module banana racket/base ( require ( only-in racket/math pi ) ) ( provide peel ) ( define peel pi ) ( define bush ( * 2 pi ) ) )\n> > ( module->indirect-exports ' ' banana )\n> '((0 bush))\n> ```\n\nAdded in version 6.5.0.5 of package base.\n\n> ```\n(parameter)\t→\t\n(-> or/c module-path? module-path-index?\n resolved-module-path?)\n```"} {"text": "# 13.11 Cryptographic Hashing\nLike module-compiled-realm, but produces the realm of mod, which must be declared (but not necessarily instantiated or visited) in the current namespace.\nAdded in version 8.4.0.2 of package base.\n> ```\n(module-predefined? mod)  →  boolean?\n   mod   :   ( or/c module-path? module-path-index?\n> resolved-module-path? )```\nReports whether mod refers to a module that is predefined for the running Racket instance. Predefined modules always have a symbolic resolved module path, and they may be predefined always or specifically within a particular executable (such as one created by raco exe or [create-embedding-executable](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=exe.html%23%2528def._%2528%2528lib._compiler%252Fembed..rkt%2529._create-embedding-executable%2529%2529&version=8.18.0.13))."} {"text": "#### 14.4.4 Module Cache\nThe expander keeps a place-local module cache in order to save time while loading modules that have been previously declared.\n> ```\n(parameter)\t→\n```\n(parameter)\t→```\n\n\nReturns #t if v is an [impersonator](#%28tech._impersonator%29) created by procedures like [impersonate-procedure](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%29%29) or [impersonate-struct](#%28def._%28%28quote._~23~25kernel%29._impersonate-struct%29%29), #f otherwise.\n\nPrograms and libraries generally should avoid [impersonator?](#%28def._%28%28quote._~23~25kernel%29._impersonator~3f%29%29) and treat impersonators the same as non-impersonator values. In rare cases, [impersonator?](#%28def._%28%28quote._~23~25kernel%29._impersonator~3f%29%29) may be needed to guard against redirection by an impersonator of an operation to an arbitrary procedure.\n\nA limitation of [impersonator?](#%28def._%28%28quote._~23~25kernel%29._impersonator~3f%29%29) is that it does not recognize an [impersonator](#%28tech._impersonator%29) that is created by instantiating a structure type with the [prop:impersonator-of](#%28def._%28%28quote._~23~25kernel%29._prop~3aimpersonator-of%29%29) property. The limitation reflects how those impersonators cannot redirect structure access and mutation operations to arbitrary procedures.\n\n> ```\n(chaperone? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a chaperone, #f otherwise."} {"text": "# 13.11 Cryptographic Hashing\nPrograms and libraries generally should avoid chaperone? for the same reason that they should avoid impersonator?. A true value for chaperone? implies a true value of impersonator?.\n> ```\n(impersonator-of? v1 v2)  →  boolean?\n  v1 : any/c\n  v2 : any/c```\nIndicates whether v1 can be considered equivalent modulo impersonators to v2.\nAny two values that are [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to one another are also [impersonator-of?](#%28def._%28%28quote._~23~25kernel%29._impersonator-of~3f%29%29). For values that include no impersonators, v1 and v2 are considered impersonators of each other if they are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29).\nIf at least one of v1 or v2 is an impersonator:\n- If v1 impersonates v1\\* then ([impersonator-of?](#%28def._%28%28quote._~23~25kernel%29._impersonator-of~3f%29%29) v1 v2) is #t if and only if ([impersonator-of?](#%28def._%28%28quote._~23~25kernel%29._impersonator-of~3f%29%29) v1\\* v2) is #t.\n- If v2 is a non-interposing impersonator that impersonates v2\\*, i.e., all of its interposition procedures are #f, then ([impersonator-of?](#%28def._%28%28quote._~23~25kernel%29._impersonator-of~3f%29%29) v1 v2) is #t if and only if ([impersonator-of?](#%28def._%28%28quote._~23~25kernel%29._impersonator-of~3f%29%29) v1 v2\\*) is #t."} {"text": "# 13.11 Cryptographic Hashing\n- When v2 is an impersonator constructed with at least one non-#f interposition procedure, but v1 is not an impersonator then ([impersonator-of?](#%28def._%28%28quote._~23~25kernel%29._impersonator-of~3f%29%29) v1 v2) is #f.\nOtherwise, if neither v1 or v2 is an impersonator, but either of them contains an impersonator as a subpart (e.g., v1 is a list with an impersonator as one of its elements), then ([impersonator-of?](#%28def._%28%28quote._~23~25kernel%29._impersonator-of~3f%29%29) v1 v2) proceeds by comparing v1 and v2 recursively (as with [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29)), returning true if all subparts are [impersonator-of?](#%28def._%28%28quote._~23~25kernel%29._impersonator-of~3f%29%29).\nExamples:\n> ```racket\n> > ( impersonator-of? ( impersonate-procedure add1 ( λ ( x ) x ) ) add1 )\n> #t\n> > ( impersonator-of? ( impersonate-procedure add1 ( λ ( x ) x ) ) sub1 )\n> #f\n> > ( impersonator-of? ( impersonate-procedure ( impersonate-procedure add1 ( λ ( x ) x ) ) ( λ ( x ) x ) ) add1 )\n> #t\n> > ( impersonator-of? ( impersonate-procedure add1 ( λ ( x ) x ) ) ( impersonate-procedure add1 #f ) )\n> #t\n> > ( impersonator-of? ( impersonate-procedure add1 ( λ ( x ) x ) ) ( impersonate-procedure add1 ( λ ( x ) x ) ) )\n> #f\n> > ( impersonator-of? ( list 1 2 ) ( list 1 2 ) )\n> #t\n> > ( impersonator-of? ( list ( impersonate-procedure add1 ( λ ( x ) x ) ) sub1 ) ( list add1 sub1 ) )\n> #t\n> ```\n> ```\n(chaperone-of? v1 v2)  →  boolean?\n  v1 : any/c\n  v2 : any/c"} {"text": "# 13.11 Cryptographic Hashing\n```\nIndicates whether v1 can be considered equivalent modulo chaperones to v2.\n\nFor values that include no chaperones or other impersonators, v1 and v2 can be considered chaperones of each other if they are equal-always?, which requires that they are equal? except that corresponding mutable vectors, boxes, hash tables, strings, byte strings, mutable pairs, and mutable structures within v1 and v2 must be eq?.\n\nOtherwise, chaperones and other impersonators within v2 must be intact within v1 analogous to way that impersonator-of? requires that impersonators are preserved. Furthermore, v1 must not have any non-chaperone impersonators whose corresponding value in v2 is not the same impersonator. Note that chaperone-of? implies impersonator-of?, but not vice-versa.\n\n> ```\n(impersonator-ephemeron v)  →  ephemeron?\n  v : any/c```\n\n\nProduces an [ephemeron](ephemerons.html#%28tech._ephemeron%29) that can be used to connect the reachability of v (in the sense of garbage collection; see [Garbage Collection](eval-model.html#%28part._gc-model%29)) with the reachability of any value for which v is an [impersonator](#%28tech._impersonator%29). That is, the value v will be considered reachable as long as the result ephemeron is reachable in addition to any value that v impersonates (including itself).\n\nIn the terminology of [ephemerons](ephemerons.html#%28tech._ephemeron%29), v is the value of the ephemeron and all of the values that v impersonates are keys.\n\n> ```\n(procedure-impersonator*? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 13.11 Cryptographic Hashing\nReturns #t for any procedure impersonator that either was produced by impersonate-procedure* or chaperone-procedure*, or is an impersonator/chaperone of a value that was created with impersonate-procedure* or chaperone-procedure* (possibly transitively)."} {"text": "#### 14.5.1 Impersonator Constructors\n> ```\n(impersonate-procedure proc\n    wrapper-proc  \n    prop  \n    prop-val ...  \n    ...)  \n  →  (and/c procedure? impersonator?)\n  proc : procedure?\n  wrapper-proc : (or/c procedure? #f)\n  prop : impersonator-property?\n  prop-val : any/c```\nReturns an impersonator procedure that has the same arity, name, and other attributes as proc. When the impersonator procedure is applied, the arguments are first passed to wrapper-proc (when it is not #f), and then the results from wrapper-proc are passed to proc. The wrapper-proc can also supply a procedure that processes the results of proc.\nThe arity of wrapper-proc must include the arity of proc. The allowed keyword arguments of wrapper-proc must be a superset of the allowed keywords of proc. The required keyword arguments of wrapper-proc must be a subset of the required keywords of proc.\nFor applications without keywords, the result of wrapper-proc must be at least the same number of values as supplied to it. Additional results can be supplied—before the values that correspond to the supplied values—in the following pattern:\n- An optional procedure, result-wrapper-proc, which will be applied to the results of proc; followed by\n- any number of repetitions of 'mark key val (i.e., three values), where the call proc is wrapped to install a [continuation mark](eval-model.html#%28tech._continuation._mark%29) key and val."} {"text": "# 13.11 Cryptographic Hashing\nIf result-wrapper-proc is produced, it must be a procedure that accepts as many results as produced by proc; it must return the same number of results. If result-wrapper-proc is not supplied, then proc is called in [tail position](eval-model.html#%28tech._tail._position%29) with respect to the call to the impersonator.\nFor applications that include keyword arguments, wrapper-proc must return an additional value before any other values but after result-wrapper-proc and 'mark key val sequences (if any). The additional value must be a list of replacements for the keyword arguments that were supplied to the impersonator (i.e., not counting optional arguments that were not supplied). The arguments must be ordered according to the sorted order of the supplied arguments’ keywords.\nIf wrapper-proc is #f, then applying the resulting impersonator is the same as applying proc. If wrapper-proc is #f and no prop is provided, then proc is returned and is not impersonated.\nPairs of prop and prop-val (the number of arguments to [impersonate-procedure](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%29%29) must be even) add impersonator properties or override impersonator-property values of proc."} {"text": "# 13.11 Cryptographic Hashing\nIf any prop is [impersonator-prop:application-mark](#%28def._%28%28quote._~23~25kernel%29._impersonator-prop~3aapplication-mark%29%29) and if the associated prop-val is a pair, then the call to proc is wrapped with [with-continuation-mark](wcm.html#%28form._%28%28quote._~23~25kernel%29._with-continuation-mark%29%29) using ([car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) prop-val) as the mark key and ([cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29) prop-val) as the mark value. In addition, if the immediate continuation frame of the call to the impersonated procedure includes a value for ([car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) prop-val)—that is, if [call-with-immediate-continuation-mark](contmarks.html#%28def._%28%28quote._~23~25kernel%29._call-with-immediate-continuation-mark%29%29) would produce a value for ([car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) prop-val) in the call’s continuation—then the value is also installed as an immediate value for ([car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) prop-val) as a mark during the call to wrapper-proc (which allows tail-calls of impersonators with respect to wrapping impersonators to be detected within wrapper-proc).\nChanged in version 6.3.0.5 of package base: Added support for 'mark key val results from wrapper-proc.\nExamples:"} {"text": "# 13.11 Cryptographic Hashing\n> ```racket\n> > ( define ( add15 x ) ( + x 15 ) )\n> > ( define add15+print ( impersonate-procedure add15 ( λ ( x ) ( printf \"called with ~s\\n\" x ) ( values ( λ ( res ) ( printf \"returned ~s\\n\" res ) res ) x ) ) ) )\n> > ( add15 27 )\n> 42\n> > ( add15+print 27 )\n> called with 27 returned 42\n> 42\n> > ( define-values ( imp-prop:p1 imp-prop:p1? imp-prop:p1-get ) ( make-impersonator-property ' imp-prop:p1 ) )\n> > ( define-values ( imp-prop:p2 imp-prop:p2? imp-prop:p2-get ) ( make-impersonator-property ' imp-prop:p2 ) )\n> > ( define add15.2 ( impersonate-procedure add15 #f imp-prop:p1 11 ) )\n> > ( add15.2 2 )\n> 17\n> > ( imp-prop:p1? add15.2 )\n> #t\n> > ( imp-prop:p1-get add15.2 )\n> 11\n> > ( imp-prop:p2? add15.2 )\n> #f\n> > ( define add15.3 ( impersonate-procedure add15.2 #f imp-prop:p2 13 ) )\n> > ( add15.3 3 )\n> 18\n> > ( imp-prop:p1? add15.3 )\n> #t\n> > ( imp-prop:p1-get add15.3 )\n> 11\n> > ( imp-prop:p2? add15.3 )\n> #t\n> > ( imp-prop:p2-get add15.3 )\n> 13\n> > ( define add15.4 ( impersonate-procedure add15.3 #f imp-prop:p1 101 ) )\n> > ( add15.4 4 )\n> 19\n> > ( imp-prop:p1? add15.4 )\n> #t\n> > ( imp-prop:p1-get add15.4 )\n> 101\n> > ( imp-prop:p2? add15.4 )\n> #t\n> > ( imp-prop:p2-get add15.4 )\n> 13\n> ```\n> ```\n(impersonate-procedure* proc\n    wrapper-proc  \n    prop  \n    prop-val ...  \n    ...)  \n  →  (and/c procedure? impersonator?)\n  proc : procedure?\n  wrapper-proc : (or/c procedure? #f)\n  prop : impersonator-property?\n  prop-val : any/c"} {"text": "# 13.11 Cryptographic Hashing\n```\nLike impersonate-procedure, except that wrapper-proc receives an additional argument before all other arguments. The additional argument is the procedure orig-proc that was originally applied.\n\nIf the result of impersonate-procedure* is applied directly, then orig-proc is that result. If the result is further impersonated before being applied, however, orig-proc is the further impersonator.\n\nAn orig-proc argument might be useful so that wrapper-proc can extract impersonator properties that are overridden by further impersonators, for example.\n\nAdded in version 6.1.1.5 of package base.\n\n> ```\n(impersonate-struct v\n   [ struct-type]        \n    orig-proc        \n    redirect-proc ...        \n    ...        \n    prop        \n    prop-val ...        \n    ...)   →   any/c\n\n  v : any/c\n  struct-type : struct-type? = unspecified\n   orig-proc   :   ( or/c struct-accessor-procedure?\n> struct-mutator-procedure?\n> struct-type-property-accessor-procedure? )\n\n  redirect-proc : (or/c procedure? #f)\n  prop : impersonator-property?\n  prop-val : any/c```\n\n\nReturns an impersonator of v, which redirects certain operations on the impersonated value. The orig-procs indicate the operations to redirect, and the corresponding redirect-procs supply the redirections. The optional struct-type argument, when provided, acts as a witness for the representation of v, which must be an instance of struct-type.\n\nThe protocol for a redirect-proc depends on the corresponding orig-proc, where self refers to the value to which orig-proc is originally applied:\n\n- A structure-field accessor: redirect-proc must accept two arguments, self and the value field-v that orig-proc produces for v; it must return a replacement for field-v. The corresponding field must not be immutable, and either the field’s structure type must be accessible via the current [inspector](inspectors.html#%28tech._inspector%29) or one of the other orig-procs must be a structure-field mutator for the same field.\n\n- A structure-field mutator: redirect-proc must accept two arguments, self and the value field-v supplied to the mutator; it must return a replacement for field-v to be propagated to orig-proc and v.\n\n- A property accessor: redirect-proc uses the same protocol as for a structure-field accessor. The accessor’s property must have been created with 'can-impersonate as the second argument to [make-struct-type-property](structprops.html#%28def._%28%28quote._~23~25kernel%29._make-struct-type-property%29%29).\n\nWhen a redirect-proc is #f, the corresponding orig-proc is unaffected. Supplying #f for a redirect-proc is useful to allow its orig-proc to act as a “witness” of v’s representation and enable the addition of props.\n\nPairs of prop and prop-val (the number of arguments to [impersonate-struct](#%28def._%28%28quote._~23~25kernel%29._impersonate-struct%29%29) must be even if struct-type is provided, odd otherwise) add impersonator properties or override impersonator-property values of v.\n\nEach orig-proc must indicate a distinct operation. If no struct-type and no orig-procs are supplied, then no props must be supplied. If orig-procs are supplied only with #f redirect-procs and no props are supplied, then v is returned and is not impersonated.\n\nIf any orig-proc is itself an impersonator, then a use of the accessor or mutator that orig-proc impersonates is redirected for the resulting impersonated structure to use orig-proc on v before redirect-proc (in the case of accessor) or after redirect-proc (in the case of a mutator).\n\nChanged in version 6.1.1.2 of package base: Changed first argument to an accessor or mutator redirect-proc from v to self. \nChanged in version 6.1.1.8: Added optional struct-type argument.\n\n> ```\n(impersonate-vector vec\n    ref-proc  \n    set-proc  \n    prop  \n    prop-val ...  \n    ...)  \n\n  →  (and/c vector? impersonator?)\n  vec : (and/c vector? (not/c immutable?))\n  ref-proc : (or/c (vector? exact-nonnegative-integer? any/c . → . any/c) #f)\n  set-proc : (or/c (vector? exact-nonnegative-integer? any/c . → . any/c) #f)\n  prop : impersonator-property?\n  prop-val : any/c\n```"} {"text": "# 13.11 Cryptographic Hashing\nReturns an impersonator of vec, which redirects the vector-ref and vector-set! operations.\nThe ref-proc and set-proc arguments must either both be procedures or both be #f. If they are #f then impersonate-vector does not interpose on vec, but still allows attaching impersonator properties.\nIf ref-proc is a procedure it must accept vec, an index passed to vector-ref, and the value that vector-ref on vec produces for the given index; it must produce a replacement for the value, which is the result of vector-ref on the impersonator.\nIf set-proc is a procedure it must accept vec, an index passed to vector-set!, and the value passed to vector-set!; it must produce a replacement for the value, which is used with vector-set! on the original vec to install the value.\nPairs of prop and prop-val (the number of arguments to impersonate-vector must be odd) add impersonator properties or override impersonator-property values of vec.\nChanged in version 6.9.0.2 of package base: Added non-interposing vector impersonators.\n> ```\n(impersonate-vector* vec\n    ref-proc  \n    set-proc  \n    prop  \n    prop-val ...  \n    ...)  \n  →  (and/c vector? impersonator?)\n  vec : (and/c vector? (not/c immutable?))\n  ref-proc : (or/c (vector? vector? exact-nonnegative-integer? any/c . → . any/c) #f)\n  set-proc : (or/c (vector? vector? exact-nonnegative-integer? any/c . → . any/c) #f)\n  prop : impersonator-property?\n  prop-val : any/c```"} {"text": "# 13.11 Cryptographic Hashing\nLike [impersonate-vector](#%28def._%28%28quote._~23~25kernel%29._impersonate-vector%29%29), except that ref-proc and set-proc each receive an additional vector as argument before other arguments. The additional argument is the original impersonated vector, access to which triggered interposition in the first place.\nThe additional vector argument might be useful so that ref-proc or set-proc can extract impersonator properties that are overridden by further impersonators, for example.\nAdded in version 6.9.0.2 of package base.\n> ```\n(impersonate-box box\n    unbox-proc        \n    set-proc        \n    prop        \n    prop-val ...        \n    ...)   →   (and/c box? impersonator?)\n  box : (and/c box? (not/c immutable?))\n  unbox-proc : (box? any/c . → . any/c)\n  set-proc : (box? any/c . → . any/c)\n  prop : impersonator-property?\n  prop-val : any/c"} {"text": "# 13.11 Cryptographic Hashing\n```\nReturns an impersonator of box, which redirects the unbox and set-box! operations.\n\nThe unbox-proc must accept box and the value that unbox produces on box; it must produce a replacement value, which is the result of unbox on the impersonator.\n\nThe set-proc must accept box and the value passed to set-box!; it must produce a replacement value, which is used with set-box! on the original box to install the value.\n\nPairs of prop and prop-val (the number of arguments to impersonate-box must be odd) add impersonator properties or override impersonator-property values of box.\n\n> ```\n(impersonate-hash hash\n    ref-proc        \n    set-proc        \n    remove-proc        \n    key-proc        \n   [ clear-proc        \n    equal-key-proc]        \n    prop        \n    prop-val ...        \n    ...)   →   (and/c hash? impersonator?)\n\n  hash : (and/c hash? (not/c immutable?))\n   ref-proc   :   ( hash? any/c . → . ( values\n> any/c\n> ( hash? any/c any/c . → . any/c ) ) )\n\n  set-proc : (hash? any/c any/c . → . (values any/c any/c))\n  remove-proc : (hash? any/c . → . any/c)\n  key-proc : (hash? any/c . → . any/c)\n  clear-proc : (or/c #f (hash? . → . any)) = #f\n  equal-key-proc : (or/c #f (hash? any/c . → . any/c)) = #f\n  prop : impersonator-property?\n  prop-val : any/c```\n\n\nReturns an impersonator of hash, which redirects the [hash-ref](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29), [hash-set!](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-set%21%29%29) or [hash-set](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-set%29%29) (as applicable), [hash-remove](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-remove%29%29) or [hash-remove!](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-remove%21%29%29) (as applicable), [hash-clear](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-clear%29%29) or [hash-clear!](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-clear%21%29%29) (as applicable and if clear-proc is not #f) operations. When [hash-set](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-set%29%29), [hash-remove](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-remove%29%29) or [hash-clear](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-clear%29%29) is used on an impersonator of a hash table, the result is an impersonator with the same redirecting procedures. In addition, operations like [hash-iterate-key](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-iterate-key%29%29) or [hash-map](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-map%29%29), which extract keys from the table, use key-proc to replace keys extracted from the table. Operations like [hash-iterate-value](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-iterate-value%29%29) or [hash-values](hashtables.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._hash-values%29%29) implicitly use [hash-ref](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29) and therefore redirect through ref-proc. The [hash-ref-key](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-ref-key%29%29) operation uses both ref-proc and key-proc, the former to lookup the requested key and the latter to extract it.\n\nThe ref-proc must accept hash and a key passed to [hash-ref](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29). It must return a replacement key as well as a procedure. The returned procedure is called only if the returned key is found in hash via [hash-ref](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29), in which case the procedure is called with hash, the previously returned key, and the found value. The returned procedure must itself return a replacement for the found value. The returned procedure is ignored by [hash-ref-key](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-ref-key%29%29).\n\nThe set-proc must accept hash, a key passed to [hash-set!](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-set%21%29%29) or [hash-set](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-set%29%29), and the value passed to [hash-set!](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-set%21%29%29) or [hash-set](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-set%29%29); it must produce two values: a replacement for the key and a replacement for the value. The returned key and value are used with [hash-set!](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-set%21%29%29) or [hash-set](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-set%29%29) on the original hash to install the value.\n\nThe remove-proc must accept hash and a key passed to [hash-remove!](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-remove%21%29%29) or [hash-remove](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-remove%29%29); it must produce a replacement for the key, which is used with [hash-remove!](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-remove%21%29%29) or [hash-remove](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-remove%29%29) on the original hash to remove any mapping using the (impersonator-replaced) key.\n\nThe key-proc must accept hash and a key that has been extracted from hash (by [hash-ref-key](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-ref-key%29%29), [hash-iterate-key](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-iterate-key%29%29), or other operations that use [hash-iterate-key](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-iterate-key%29%29) internally); it must produce a replacement for the key, which is then reported as a key extracted from the table.\n\nIf clear-proc is not #f, it must accept hash as an argument, and its result is ignored. The fact that clear-proc returns (as opposed to raising an exception or otherwise escaping) grants the capability to remove all keys from hash. If clear-proc is #f, then [hash-clear](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-clear%29%29) or [hash-clear!](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-clear%21%29%29) on the impersonator is implemented using [hash-iterate-key](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-iterate-key%29%29) and [hash-remove](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-remove%29%29) or [hash-remove!](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-remove%21%29%29).\n\nIf equal-key-proc is not #f, it effectively interposes on calls to [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-hash-code](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-hash-code%29%29), and [equal-secondary-hash-code](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-secondary-hash-code%29%29) for the keys of hash. The equal-key-proc must accept as its arguments hash and a key that is either mapped by hash or passed to [hash-ref](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29), etc., where the latter has potentially been adjusted by the corresponding ref-proc, etc. The result is a value that is passed to [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29), [equal-hash-code](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-hash-code%29%29), and [equal-secondary-hash-code](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal-secondary-hash-code%29%29) as needed to hash and compare keys. In the case of [hash-set!](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-set%21%29%29) or [hash-set](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-set%29%29), the key that is passed to equal-key-proc is the one stored in the hash table for future lookup.\n\nThe [hash-iterate-value](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-iterate-value%29%29), [hash-map](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-map%29%29), or [hash-for-each](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-for-each%29%29) functions use a combination of [hash-iterate-key](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-iterate-key%29%29) and [hash-ref](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29). If a key produced by key-proc does not yield a value through [hash-ref](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29), then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nPairs of prop and prop-val add impersonator properties or override impersonator-property values of hash.\n\nIn the case of an immutable hash table, two impersonated hash tables count as “the same value” (for purposes of [impersonator-of?](#%28def._%28%28quote._~23~25kernel%29._impersonator-of~3f%29%29)) when their redirection procedures were originally attached to a hash table by the same call to [impersonate-hash](#%28def._%28%28quote._~23~25kernel%29._impersonate-hash%29%29) or [chaperone-hash](#%28def._%28%28quote._~23~25kernel%29._chaperone-hash%29%29) (and potentially propagated by [hash-set](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-set%29%29), [hash-remove](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-remove%29%29), or [hash-clear](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-clear%29%29)), as long as the content of the first hash table is [impersonator-of?](#%28def._%28%28quote._~23~25kernel%29._impersonator-of~3f%29%29) of the second hash table.\n\nChanged in version 6.3.0.11 of package base: Added the equal-key-proc argument.\n\n> ```\n(impersonate-channel channel\n    get-proc  \n    put-proc  \n    prop  \n    prop-val ...  \n    ...)  \n\n  →  (and/c channel? impersonator?)\n  channel : channel?\n  get-proc : (channel? . → . (values channel? (any/c . → . any/c)))\n  put-proc : (channel? any/c . → . any/c)\n  prop : impersonator-property?\n  prop-val : any/c\n```"} {"text": "# 13.11 Cryptographic Hashing\nReturns an impersonator of channel, which redirects the channel-get and channel-put operations.\nThe get-proc generator is called on channel-get or any other operation that fetches results from the channel (such as a sync on the channel). The get-proc must return two values: a channel that is an impersonator of channel, and a procedure that is used to check the channel’s contents.\nThe put-proc must accept channel and the value passed to channel-put; it must produce a replacement value, which is used with channel-put on the original channel to send the value over the channel.\nPairs of prop and prop-val (the number of arguments to impersonate-channel must be odd) add impersonator properties or override impersonator-property values of channel.\n> ```\n(impersonate-prompt-tag prompt-tag\n    handle-proc  \n    abort-proc  \n   [ cc-guard-proc  \n    callcc-impersonate-proc]  \n    prop  \n    prop-val ...  \n    ...)  \n  →  (and/c continuation-prompt-tag? impersonator?)\n  prompt-tag : continuation-prompt-tag?\n  handle-proc : procedure?\n  abort-proc : procedure?\n  cc-guard-proc : procedure? = values\n   callcc-impersonate-proc   :   (procedure? . → . procedure?)\n      =   (lambda (p) p)\n  prop : impersonator-property?\n  prop-val : any/c```\nReturns an impersonator of prompt-tag, which redirects the [call-with-continuation-prompt](cont.html#%28def._%28%28quote._~23~25kernel%29._call-with-continuation-prompt%29%29) and [abort-current-continuation](cont.html#%28def._%28%28quote._~23~25kernel%29._abort-current-continuation%29%29) operations."} {"text": "# 13.11 Cryptographic Hashing\nThe handle-proc must accept the values that the handler of a continuation prompt would take and it must produce replacement values, which will be passed to the handler.\nThe abort-proc must accept the values passed to [abort-current-continuation](cont.html#%28def._%28%28quote._~23~25kernel%29._abort-current-continuation%29%29); it must produce replacement values, which are aborted to the appropriate prompt.\nThe cc-guard-proc must accept the values produced by [call-with-continuation-prompt](cont.html#%28def._%28%28quote._~23~25kernel%29._call-with-continuation-prompt%29%29) in the case that a non-composable continuation is applied to replace the continuation that is delimited by the prompt, but only if [abort-current-continuation](cont.html#%28def._%28%28quote._~23~25kernel%29._abort-current-continuation%29%29) is not later used to abort the continuation delimited by the prompt (in which case abort-proc is used)."} {"text": "# 13.11 Cryptographic Hashing\nThe callcc-impersonate-proc must accept a procedure that guards the result of a continuation captured by [call-with-current-continuation](cont.html#%28def._%28%28quote._~23~25kernel%29._call-with-current-continuation%29%29) with the impersonated prompt tag. The callcc-impersonate-proc is applied (under a [continuation barrier](eval-model.html#%28tech._continuation._barrier%29)) when the captured continuation is applied to refine a guard function (initially [values](values.html#%28def._%28%28quote._~23~25kernel%29._values%29%29)) that is specific to the delimiting prompt; this prompt-specific guard is ultimately composed with any cc-guard-proc that is in effect at the delimiting prompt, and it is not used in the same case that a cc-guard-proc is not used (i.e., when [abort-current-continuation](cont.html#%28def._%28%28quote._~23~25kernel%29._abort-current-continuation%29%29) is used to abort to the prompt). In the special case where the delimiting prompt at application time is a thread’s built-in initial prompt, callcc-impersonate-proc is ignored (partly on the grounds that the initial prompt’s result is ignored).\nPairs of prop and prop-val (the number of arguments to [impersonate-prompt-tag](#%28def._%28%28quote._~23~25kernel%29._impersonate-prompt-tag%29%29) must be odd) add impersonator properties or override impersonator-property values of prompt-tag.\nExamples:"} {"text": "# 13.11 Cryptographic Hashing\n> ```racket\n> > ( define tag ( impersonate-prompt-tag ( make-continuation-prompt-tag ) ( lambda ( n ) ( * n 2 ) ) ( lambda ( n ) ( + n 1 ) ) ) )\n> > ( call-with-continuation-prompt ( lambda ( ) ( abort-current-continuation tag 5 ) ) tag ( lambda ( n ) n ) )\n> 12\n> ```\n> ```\n(impersonate-continuation-mark-key key\n    get-proc  \n    set-proc  \n    prop  \n    prop-val ...  \n    ...)  \n  →  (and/c continuation-mark? impersonator?)\n  key : continuation-mark-key?\n  get-proc : procedure?\n  set-proc : procedure?\n  prop : impersonator-property?\n  prop-val : any/c\n```\n(recursively)\t→\t\n(-> the number of arguments to impersonate-continuation-mark-key must be odd)```\n\n\nLike [impersonate-procedure](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%29%29), but for each value supplied to wrapper-proc, the corresponding result must be the same or a chaperone of (in the sense of [chaperone-of?](#%28def._%28%28quote._~23~25kernel%29._chaperone-of~3f%29%29)) the supplied value. The additional result, if any, that precedes the chaperoned values must be a procedure that accepts as many results as produced by proc; it must return the same number of results, each of which is the same or a chaperone of the corresponding original result.\n\nFor applications that include keyword arguments, wrapper-proc must return an additional value before any other values but after the result-chaperoning procedure (if any). The additional value must be a list of chaperones of the keyword arguments that were supplied to the chaperone procedure (i.e., not counting optional arguments that were not supplied). The arguments must be ordered according to the sorted order of the supplied arguments’ keywords.\n\n> ```\n(chaperone-procedure* proc\n    wrapper-proc  \n    prop  \n    prop-val ...  \n    ...)  \n\n  →  (and/c procedure? chaperone?)\n  proc : procedure?\n  wrapper-proc : (or/c procedure? #f)\n  prop : impersonator-property?\n  prop-val : any/c\n```"} {"text": "# 13.11 Cryptographic Hashing\nLike chaperone-procedure, but wrapper-proc receives an extra argument as with impersonate-procedure*.\nAdded in version 6.1.1.5 of package base.\n> ```\n(chaperone-struct v\n   [ struct-type]        \n    orig-proc        \n    redirect-proc ...        \n    ...        \n    prop        \n    prop-val ...        \n    ...)   →   any/c\n  v : any/c\n  struct-type : struct-type? = unspecified\n   orig-proc   :   ( or/c struct-accessor-procedure?\n> struct-mutator-procedure?\n> struct-type-property-accessor-procedure?\n> ( lambda ( proc )\n> ( eq? proc struct-info ) ) )\n  redirect-proc : (or/c procedure? #f)\n  prop : impersonator-property?\n  prop-val : any/c```\nLike [impersonate-struct](#%28def._%28%28quote._~23~25kernel%29._impersonate-struct%29%29), but with the following refinements, where self refers to the value to which a orig-proc is originally applied:\n- With a structure-field accessor as orig-proc, redirect-proc must accept two arguments, self and the value field-v that orig-proc produces for v; it must return a chaperone of field-v. The corresponding field may be immutable.\n- With structure-field mutator as orig-proc, redirect-proc must accept two arguments, self and the value field-v supplied to the mutator; it must return a chaperone of field-v to be propagated to orig-proc and v.\n- A property accessor can be supplied as orig-proc, and the property need not have been created with 'can-impersonate. The corresponding redirect-proc uses the same protocol as for a structure-field accessor."} {"text": "# 13.11 Cryptographic Hashing\n- With [struct-info](inspectors.html#%28def._%28%28quote._~23~25kernel%29._struct-info%29%29) as orig-proc, the corresponding redirect-proc must accept two values, which are the results of [struct-info](inspectors.html#%28def._%28%28quote._~23~25kernel%29._struct-info%29%29) on v; it must return each values or a chaperone of each value. The redirect-proc is not called if [struct-info](inspectors.html#%28def._%28%28quote._~23~25kernel%29._struct-info%29%29) would return #f as its first argument. An orig-proc can be [struct-info](inspectors.html#%28def._%28%28quote._~23~25kernel%29._struct-info%29%29) only if struct-type or some other orig-proc is supplied.\n- Any accessor or mutator orig-proc that is an [impersonator](#%28tech._impersonator%29) must be specifically a [chaperone](#%28tech._chaperone%29).\nSupplying a property accessor for orig-proc enables prop arguments, the same as supplying an accessor, mutator, or structure type.\nChanged in version 6.1.1.2 of package base: Changed first argument to an accessor or mutator redirect-proc from v to self. \nChanged in version 6.1.1.8: Added optional struct-type argument.\n> ```\n(chaperone-vector vec\n    ref-proc        \n    set-proc        \n    prop        \n    prop-val ...        \n    ...)   →   (and/c vector? chaperone?)\n  vec : vector?\n  ref-proc : (or/c (vector? exact-nonnegative-integer? any/c . → . any/c) #f)\n  set-proc : (or/c (vector? exact-nonnegative-integer? any/c . → . any/c) #f)\n  prop : impersonator-property?\n  prop-val : any/c"} {"text": "# 13.11 Cryptographic Hashing\n```\nLike impersonate-vector, but with support for immutable vectors. The ref-proc procedure must produce the same value or a chaperone of the original value, and set-proc must produce the value that is given or a chaperone of the value. The set-proc will not be used if vec is immutable.\n\n> ```\n(chaperone-vector* vec\n    ref-proc        \n    set-proc        \n    prop        \n    prop-val ...        \n    ...)   →   (and/c vector? chaperone?)\n\n  vec : vector?\n  ref-proc : (or/c (vector? vector? exact-nonnegative-integer? any/c . → . any/c) #f)\n  set-proc : (or/c (vector? vector? exact-nonnegative-integer? any/c . → . any/c) #f)\n  prop : impersonator-property?\n  prop-val : any/c```\n\n\nLike [chaperone-vector](#%28def._%28%28quote._~23~25kernel%29._chaperone-vector%29%29), but ref-proc and set-proc receive an extra argument as with [impersonate-vector*](#%28def._%28%28quote._~23~25kernel%29._impersonate-vector%2A%29%29).\n\nAdded in version 6.9.0.2 of package base.\n\n> ```\n(chaperone-box box\n    unbox-proc        \n    set-proc        \n    prop        \n    prop-val ...        \n    ...)   →   (and/c box? chaperone?)\n\n  box : box?\n  unbox-proc : (box? any/c . → . any/c)\n  set-proc : (box? any/c . → . any/c)\n  prop : impersonator-property?\n  prop-val : any/c\n```\nLike impersonate-box, but with support for immutable boxes. The unbox-proc procedure must produce the same value or a chaperone of the original value, and set-proc must produce the same value or a chaperone of the value that it is given. The set-proc will not be used if box is immutable."} {"text": "# 13.11 Cryptographic Hashing\n> ```\n(chaperone-hash hash\n    ref-proc        \n    set-proc        \n    remove-proc        \n    key-proc        \n   [ clear-proc        \n    equal-key-proc]        \n    prop        \n    prop-val ...        \n    ...)   →   (and/c hash? chaperone?)\n  hash : hash?\n   ref-proc   :   ( hash? any/c . → . ( values\n> any/c\n> ( hash? any/c any/c . → . any/c ) ) )\n  set-proc : (hash? any/c any/c . → . (values any/c any/c))\n  remove-proc : (hash? any/c . → . any/c)\n  key-proc : (hash? any/c . → . any/c)\n  clear-proc : (or/c #f (hash? . → . any)) = #f\n  equal-key-proc : (or/c #f (hash? any/c . → . any/c)) = #f\n  prop : impersonator-property?\n  prop-val : any/c```\nLike [impersonate-hash](#%28def._%28%28quote._~23~25kernel%29._impersonate-hash%29%29), but with constraints on the given functions and support for immutable hashes. The ref-proc procedure must return a found value or a chaperone of the value. The set-proc procedure must produce two values: the key that it is given or a chaperone of the key and the value that it is given or a chaperone of the value. The remove-proc, key-proc, and equal-key-proc procedures must produce the given key or a chaperone of the key.\nChanged in version 6.3.0.11 of package base: Added the equal-key-proc argument.\n> ```\n(chaperone-struct-type struct-type\n    struct-info-proc  \n    make-constructor-proc  \n    guard-proc  \n    prop  \n    prop-val ...  \n    ...)  "} {"text": "# 13.11 Cryptographic Hashing\n  →  (and/c struct-type? chaperone?)\n  struct-type : struct-type?\n  struct-info-proc : procedure?\n  make-constructor-proc : (procedure? . → . procedure?)\n  guard-proc : procedure?\n  prop : impersonator-property?\n  prop-val : any/c\n```\nReturns a chaperoned value like struct-type, but with struct-type-info and struct-type-make-constructor operations on the chaperoned structure type redirected. In addition, when a new structure type is created as a subtype of the chaperoned structure type, guard-proc is interposed as an extra guard on creation of instances of the subtype.\n\nThe struct-info-proc must accept 8 arguments—the result of struct-type-info on struct-type. It must return 8 values, where each is the same or a chaperone of the corresponding argument. The 8 values are used as the results of struct-type-info for the chaperoned structure type.\n\nThe make-constructor-proc must accept a single procedure argument, which is a constructor produced by struct-type-make-constructor on struct-type. It must return the same or a chaperone of the procedure, which is used as the result of struct-type-make-constructor on the chaperoned structure type.\n\nThe guard-proc is like a guard argument to make-struct-type: it must accept one more argument than a constructor for struct-type, where the last argument is the name the name of the instantiated structure type. It must return the number of values needed by the constructor (i.e. one value for each argument but the last), and each returned value must be the same as or a chaperone of the corresponding argument. The guard-proc is added as a constructor guard when a subtype is created of the chaperoned structure type.\n\nPairs of prop and prop-val (the number of arguments to chaperone-struct-type must be even) add impersonator properties or override impersonator-property values of struct-type.\n\n> ```\n(chaperone-evt evt proc prop prop-val ... ...)\n  →  (and/c evt? chaperone?)\n  evt : evt?\n  proc : (evt? . → . (values evt? (any/c . → . any/c)))\n  prop : impersonator-property?\n  prop-val : any/c```\n\n\nReturns a chaperoned value like evt, but with proc as an event generator when the result is synchronized with functions like [sync](sync.html#%28def._%28%28quote._~23~25kernel%29._sync%29%29).\n\nThe proc generator is called on synchronization, much like the procedure passed to [guard-evt](sync.html#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._guard-evt%29%29), except that proc is given evt. The proc must return two values: a [synchronizable event](sync.html#%28tech._synchronizable._event%29) that is a chaperone of evt, and a procedure that is used to check the event’s result if it is chosen in a selection. The latter procedure accepts the result of evt, and it must return a chaperone of that value.\n\nPairs of prop and prop-val (the number of arguments to [chaperone-evt](#%28def._%28%28quote._~23~25kernel%29._chaperone-evt%29%29) must be even) add impersonator properties or override impersonator-property values of evt.\n\nThe result is [chaperone-of?](#%28def._%28%28quote._~23~25kernel%29._chaperone-of~3f%29%29) the argument evt. However, if evt is a [thread](eval-model.html#%28tech._thread%29), [semaphore](semaphore.html#%28tech._semaphore%29), [input port](ports.html#%28tech._input._port%29), [output port](ports.html#%28tech._output._port%29), or [will executor](willexecutor.html#%28tech._will._executor%29), the result is not recognized as such. For example, [thread?](threads.html#%28def._%28%28quote._~23~25kernel%29._thread~3f%29%29) applied to the result of [chaperone-evt](#%28def._%28%28quote._~23~25kernel%29._chaperone-evt%29%29) will always produce #f.\n\n> ```\n(chaperone-channel channel\n    get-proc        \n    put-proc        \n    prop        \n    prop-val ...        \n    ...)   →   (and/c channel? chaperone?)\n\n  channel : channel?\n  get-proc : (channel? . → . (values channel? (any/c . → . any/c)))\n  put-proc : (channel? any/c . → . any/c)\n  prop : impersonator-property?\n  prop-val : any/c\n```"} {"text": "# 13.11 Cryptographic Hashing\nLike impersonate-channel, but with restrictions on the get-proc and put-proc procedures.\nThe get-proc must return two values: a channel that is a chaperone of channel, and a procedure that is used to check the channel’s contents. The latter procedure must return the original value or a chaperone of that value.\nThe put-proc must produce a replacement value that is either the original value communicated on the channel or a chaperone of that value.\nPairs of prop and prop-val (the number of arguments to chaperone-channel must be odd) add impersonator properties or override impersonator-property values of channel.\n> ```\n(chaperone-prompt-tag prompt-tag\n    handle-proc  \n    abort-proc  \n   [ cc-guard-proc  \n    callcc-chaperone-proc]  \n    prop  \n    prop-val ...  \n    ...)  \n  →  (and/c continuation-prompt-tag? chaperone?)\n  prompt-tag : continuation-prompt-tag?\n  handle-proc : procedure?\n  abort-proc : procedure?\n  cc-guard-proc : procedure? = values\n   callcc-chaperone-proc   :   (procedure? . → . procedure?)\n      =   (lambda (p) p)\n  prop : impersonator-property?\n  prop-val : any/c```"} {"text": "# 13.11 Cryptographic Hashing\nLike [impersonate-prompt-tag](#%28def._%28%28quote._~23~25kernel%29._impersonate-prompt-tag%29%29), but produces a chaperoned value. The handle-proc procedure must produce the same values or chaperones of the original values, abort-proc must produce the same values or chaperones of the values that it is given, and cc-guard-proc must produce the same values or chaperones of the original result values, and callcc-chaperone-proc must produce a procedure that is a chaperone or the same as the given procedure.\nExamples:\n> ```racket\n> > ( define bad-chaperone ( chaperone-prompt-tag ( make-continuation-prompt-tag ) ( lambda ( n ) ( * n 2 ) ) ( lambda ( n ) ( + n 1 ) ) ) )\n> > ( call-with-continuation-prompt ( lambda ( ) ( abort-current-continuation bad-chaperone 5 ) ) bad-chaperone ( lambda ( n ) n ) )\n> abort-current-continuation: non-chaperone result; received a\n> prompt-abort argument that is not a chaperone of the\n> original prompt-abort argument\n> original: 5\n> received: 6\n> > ( define good-chaperone ( chaperone-prompt-tag ( make-continuation-prompt-tag ) ( lambda ( n ) ( if ( even? n ) n ( error \"not even\" ) ) ) ( lambda ( n ) ( if ( even? n ) n ( error \"not even\" ) ) ) ) )\n> > ( call-with-continuation-prompt ( lambda ( ) ( abort-current-continuation good-chaperone 2 ) ) good-chaperone ( lambda ( n ) n ) )\n> 2\n> ```\n> ```\n(chaperone-continuation-mark-key key\n    get-proc  \n    set-proc  \n    prop  \n    prop-val ...  \n    ...)  "} {"text": "# 13.11 Cryptographic Hashing\n  →  (and/c continuation-mark-key? chaperone?)\n  key : continuation-mark-key?\n  get-proc : procedure?\n  set-proc : procedure?\n  prop : impersonator-property?\n  prop-val : any/c\n```\n(parameter)\t→\t\n(-> with-continuation-mark bad-chaperone \"timballo\" (continuation-mark-set-first (current-continuation-marks) bad-chaperone))```\n\n\nCreates a new [impersonator property](#%28tech._impersonator._property%29) and returns three values:\n\n- an impersonator property descriptor, for use with [impersonate-procedure](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%29%29), [chaperone-procedure](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._chaperone-procedure%29%29), and other impersonator constructors;\n\n- an impersonator property predicate procedure, which takes an arbitrary value and returns #t if the value is an impersonator with a value for the property, #f otherwise;\n\n- an impersonator property accessor procedure, which returns the value associated with an impersonator for the property; if a value given to the accessor is not an impersonator or does not have a value for the property (i.e. if the corresponding impersonator property predicate returns #f), then a second optional argument to the selector determines its response: the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised if a second argument is not provided, the second argument is tail-called with zero arguments if it is a procedure, and the second argument is returned otherwise.\n\n> ```\n(impersonator-property? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 13.11 Cryptographic Hashing\nReturns #t if v is a impersonator property descriptor value, #f otherwise.\n> ```\n(impersonator-property-accessor-procedure? v)  →  boolean?\n  v : any/c```\nReturns #t if v is an accessor procedure produced by [make-impersonator-property](#%28def._%28%28quote._~23~25kernel%29._make-impersonator-property%29%29), #f otherwise.\n>
\n

value

\n

[impersonator-prop:application-mark](#%28def._%28%28quote._~23~25kernel%29._impersonator-prop~3aapplication-mark%29%29) : [impersonator-property?](#%28def._%28%28quote._~23~25kernel%29._impersonator-property~3f%29%29)

\nAn [impersonator property](#%28tech._impersonator._property%29) that is recognized by [impersonate-procedure](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%29%29) and [chaperone-procedure](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._chaperone-procedure%29%29).\n------------------------------------------------------------------------"} {"text": "# 14.6 Security Guards"} {"text": "### 14.6 Security Guards\n> ```\n(security-guard? v)  →  boolean?\n  v : any/c\n```\n(parameter)\t→\t\n(-> symbol?\n (or/c path? #f)\n (listof symbol?)\n . → . any)```\n\n\nCreates a new security guard as child of parent.\n\nThe file-guard procedure must accept three arguments:\n\n- a symbol for the primitive procedure that triggered the access check, which is useful for raising an exception to deny access.\n\n- a path (see [Paths](pathutils.html)) or #f for pathless queries, such as ([current-directory](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29)), ([filesystem-root-list](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._filesystem-root-list%29%29)), and ([find-system-path](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._find-system-path%29%29) symbol). A path provided to file-guard is not expanded or otherwise normalized before checking access; it may be a relative path, for example.\n\n- a list containing one or more of the following symbols:\n\n - 'read — read a file or directory\n\n - 'write — modify or create a file or directory\n\n - 'execute — execute a file\n\n - 'delete — delete a file or directory\n\n - 'exists — determine whether a file or directory exists, or that a path string is well-formed\n\n The 'exists symbol is never combined with other symbols in the last argument to file-guard, but any other combination is possible. When the second argument to file-guard is #f, the last argument always contains only 'exists.\n\nThe network-guard procedure must accept four arguments:\n\n- a symbol for the primitive operation that triggered the access check, which is useful for raising an exception to deny access.\n\n- an immutable string representing the target hostname for a client connection or the accepting hostname for a listening server; #f for a listening server or UDP socket that accepts connections at all of the host’s address; or #f an unbound UDP socket.\n\n- an exact integer between 1 and 65535 (inclusive) representing the port number, or #f for an unbound UDP socket. In the case of a client connection, the port number is the target port on the server. For a listening server, the port number is the local port number.\n\n- a symbol, either 'client or 'server, indicating whether the check is for the creation of a client connection or a listening server. The opening of an unbound UDP socket is identified as a 'client connection; explicitly binding the socket is identified as a 'server action.\n\nThe link-guard argument can be #f or a procedure of three arguments:\n\n- a symbol for the primitive procedure that triggered the access check, which is useful for raising an exception to deny access.\n\n- a complete path (see [Paths](pathutils.html)) representing the file to create as link.\n\n- a path representing the content of the link, which may be relative the second-argument path; this path is not expanded or otherwise normalized before checking access.\n\nIf link-guard is #f, then a default procedure is used that always raises [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29).\n\nThe return value of file-guard, network-guard, or link-guard is ignored. To deny access, the procedure must raise an exception or otherwise escape from the context of the primitive call. If the procedure returns, the parent’s corresponding procedure is called on the same inputs, and so on up the chain of security guards.\n\nThe file-guard, network-guard, and link-guard procedures are invoked in the thread that called the access-checked primitive. Breaks may or may not be enabled (see [Breaks](breakhandler.html)). Full continuation jumps are blocked going into or out of the file-guard or network-guard call (see [Prompts, Delimited Continuations, and Barriers](eval-model.html#%28part._prompt-model%29)).\n\n> ```\n(current-security-guard)\t→\t\n(-> current-security-guard guard)\n(current-security-guard guard) → void?\n guard\t:\t\n(-> current-security-guard guard)\n```"} {"text": "# 14.6 Security Guards\nA parameter that determines the current security guard that controls access to the filesystem and network.\n------------------------------------------------------------------------"} {"text": "# 14.7 Custodians"} {"text": "### 14.7 Custodians\nSee Custodians for basic information on the Racket custodian model.\n> ```\n(custodian? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a [custodian](eval-model.html#%28tech._custodian%29) value, #f otherwise.\n> ```\n(current-custodian)\t→\t\n(-> and/c custodian? (not/c custodian-shut-down?))\n```\n(parameter)\t→```\n\n\n> > > In [racket/gui/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=gui&rel=index.html&version=8.18.0.13), [eventspaces](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=gui&rel=windowing-overview.html%23%2528tech._eventspace%2529&version=8.18.0.13) managed by cust are also shut down.\n\nCloses all [file-stream ports](file-ports.html#%28tech._file._stream._port%29), [TCP ports](tcp.html#%28tech._tcp._port%29), [TCP listeners](tcp.html#%28tech._tcp._listener%29), and [UDP sockets](udp.html#%28tech._udp._socket%29) that are managed by cust (and its subordinates), and empties all [custodian box](eval-model.html#%28tech._custodian._box%29)es associated with cust (and its subordinates). It also removes cust (and its subordinates) as managers of all threads; when a thread has no managers, it is killed (or suspended; see [thread/suspend-to-kill](threads.html#%28def._%28%28quote._~23~25kernel%29._thread%2Fsuspend-to-kill%29%29)) If the current thread is to be killed, all other shut-down actions take place before killing the thread.\n\nIf cust is already shut down, then [custodian-shutdown-all](#%28def._%28%28quote._~23~25kernel%29._custodian-shutdown-all%29%29) has no effect. When a custodian is shut down and it has subordinate custodians, the subordinates are not only shut down, they no longer count as subordinates.\n\n> ```\n(custodian-shut-down? cust)  →  boolean?\n  cust : custodian?\n```"} {"text": "# 14.7 Custodians\n(current-custodian)\t→\t\n(-> current-custodian cust)\n(current-custodian cust) → void?\n cust\t:\t\n(-> current-custodian cust)```\n> > > Custodians also manage [eventspaces](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=gui&rel=windowing-overview.html%23%2528tech._eventspace%2529&version=8.18.0.13) from [racket/gui/base](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=gui&rel=index.html&version=8.18.0.13).\nA [parameter](eval-model.html#%28tech._parameter%29) that determines a custodian that assumes responsibility for newly created threads, [file-stream ports](file-ports.html#%28tech._file._stream._port%29), TCP ports, [TCP listeners](tcp.html#%28tech._tcp._listener%29), [UDP sockets](udp.html#%28tech._udp._socket%29), and [byte converters](bytestrings.html#%28tech._byte._converter%29).\n> ```\n(custodian-managed-list cust super)  →  list?\n  cust : custodian?\n  super : custodian?"} {"text": "# 14.7 Custodians\n```\nReturns a list of immediately managed objects (not including custodian boxes) and subordinate custodians for cust, where cust is itself subordinate to super (directly or indirectly). If cust is not strictly subordinate to super, the exn:fail:contract exception is raised.\n\nIf cust has been shut down, the result is '(). If cust was a subordinate of a custodian that was shut down, then it cannot be a subordinate of super.\n\n> ```\n(custodian-memory-accounting-available?)  →  boolean?```\n\n\n> > > Memory accounting is normally available, but not in the [CGC](implementations.html#%28tech._cgc%29) implementation.\n\nReturns #t if Racket is compiled with support for per-custodian memory accounting, #f otherwise.\n\n> ```\n(parameter)\t→\n```\n(parameter)\t→```\nRegisters a limited-memory check if Racket is compiled with support for per-custodian memory accounting, otherwise the [exn:fail:unsupported](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aunsupported%29%29) exception is raised.\nIf a check is registered, and if Racket later reaches a state after garbage collection (see [Garbage Collection](eval-model.html#%28part._gc-model%29)) where limit-cust owns more than limit-amt bytes, then stop-cust is shut down."} {"text": "# 14.7 Custodians\n> > > A custodian’s limit is checked only after a garbage collection, except that it may also be checked during certain large allocations that are individually larger than the custodian’s limit. A single garbage collection may shut down multiple custodians, even if shutting down only one of the custodians would have reduced memory use for other custodians.\nFor reliable shutdown, limit-amt for [custodian-limit-memory](#%28def._%28%28quote._~23~25kernel%29._custodian-limit-memory%29%29) must be much lower than the total amount of memory available (minus the size of memory that is potentially used and not charged to limit-cust). Moreover, if individual allocations that are initially charged to limit-cust can be arbitrarily large, then stop-cust must be the same as limit-cust, so that excessively large immediate allocations can be rejected with an [exn:fail:out-of-memory](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aout-of-memory%29%29) exception.\n> > > New memory allocation will be accounted to the running [thread](threads.html)’s managing custodian. In other words, a custodian’s limit applies only to the allocation made by the threads that it manages. See also [call-in-nested-thread](threads.html#%28def._%28%28quote._~23~25kernel%29._call-in-nested-thread%29%29) for a simpler setup.\nExamples:"} {"text": "# 14.7 Custodians\n> ```racket\n> > ( require racket/async-channel )\n> > ( define ch ( make-async-channel ) )\n> > ( parameterize ( [ current-custodian ( make-custodian ) ] ) ( thread-wait ( thread ( λ ( ) ( with-handlers ( [ exn:fail:out-of-memory? ( λ ( e ) ( async-channel-put ch e ) ) ] ) ( custodian-limit-memory ( current-custodian ) ( * 1024 1024 ) ) ( make-bytes ( * 4 1024 1024 ) ) ( async-channel-put ch \"Not OK\" ) ) ) ) ) ( async-channel-get ch ) )\n> (exn:fail:out-of-memory \"out of memory\" #)\n> > ( define cust ( make-custodian ) )\n> > ( with-handlers ( [ exn:fail:out-of-memory? ( λ ( e ) ( error \"Caught OOM exn\" ) ) ] ) ( call-in-nested-thread ( λ ( ) ( custodian-limit-memory cust ( * 1024 1024 ) ) ( make-bytes ( * 4 1024 1024 ) ) \"Not OK\" ) cust ) )\n> Caught OOM exn\n> ```\nNon-examples:\n> ```racket\n> > ( parameterize ( [ current-custodian ( make-custodian ) ] ) ( custodian-limit-memory ( current-custodian ) ( * 1024 1024 ) ) ; Allocation of make-bytes is charged to the current thread’s ; managing custodian, not the new custodian. ( make-bytes ( * 4 1024 1024 ) ) \"Not OK\" )\n> \"Not OK\"\n> ```\n> ```\n(make-custodian-box cust v)  →  custodian-box?\n  cust : custodian?\n  v : any/c"} {"text": "# 14.7 Custodians\n```\nReturns a custodian box that contains v as long as cust has not been shut down. If cust is already shut down, the custodian box’s value is immediately removed.\n\nA custodian box is a synchronizable event (see Events). The custodian box becomes ready when its custodian is shut down; the synchronization result of a custodian box is the custodian box itself.\n\n> ```\n(custodian-box? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a [custodian box](eval-model.html#%28tech._custodian._box%29) produced by [make-custodian-box](#%28def._%28%28quote._~23~25kernel%29._make-custodian-box%29%29), #f otherwise.\n\n> ```\n(custodian-box-value cb)  →  any\n  cb : custodian-box?\n```\n(current-thread-group)\t→\t\n(-> current-thread-group)```\nCreates a new thread group that belongs to group.\n> ```\n(thread-group? v)  →  boolean?\n  v : any/c"} {"text": "# 14.7 Custodians\n```\n(current-thread-group)\t→\t\n(-> current-thread-group group)\n(current-thread-group group) → void?\n group\t:\t\n(-> current-thread-group group)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the thread group for newly created threads.\n\n------------------------------------------------------------------------\n\n# 14.9 Structure Inspectors\n\n### 14.9 Structure Inspectors\n\nAn inspector provides access to structure fields and structure type information without the normal field accessors and mutators. (Inspectors are also used to control access to module bindings; see [Code Inspectors](modprotect.html).) Inspectors are primarily intended for use by debuggers.\n\nWhen a structure type is created, an inspector can be supplied. The given inspector is not the one that will control the new structure type; instead, the given inspector’s parent will control the type. By using the parent of the given inspector, the structure type remains opaque to “peer” code that cannot access the parent inspector.\n\nThe [current-inspector](#%28def._%28%28quote._~23~25kernel%29._current-inspector%29%29) [parameter](eval-model.html#%28tech._parameter%29) determines a default inspector argument for new structure types. An alternate inspector can be provided though the #:inspector option of the [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) form (see [Defining Structure Types: struct](define-struct.html)), or through an optional inspector argument to [make-struct-type](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._make-struct-type%29%29).\n\n> ```\n(inspector? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 14.7 Custodians\n(current-inspector)\t→\t\n(-> current-inspector)```\nReturns a new inspector that is a subinspector of inspector. Any structure type controlled by the new inspector is also controlled by its ancestor inspectors, but no other inspectors.\n> ```\n(current-inspector)\t→\t\n(-> current-inspector)\n```\n\n\nReturns a new inspector that is a subinspector of the same inspector as inspector. That is, inspector and the result inspector control mutually disjoint sets of structure types.\n\n> ```\n(inspector-superior?   inspector        \n    maybe-subinspector)   →   boolean?\n\n  inspector : inspector?\n  maybe-subinspector : inspector?\n```\nReturns #t if inspector is an ancestor of maybe-subinspector (and not equal to maybe-subinspector), #f otherwise.\nAdded in version 6.5.0.6 of package base.\n> ```\n(current-inspector)\t→\t\n(-> current-inspector insp)\n(current-inspector insp) → void?\n insp\t:\t\n(-> current-inspector insp)\n```\n(parameter)\t→\t\n(-> or/c struct-type? #f)```\n\n\nReturns two values:\n\n- struct-type: a structure type descriptor or #f; the result is a structure type descriptor of the most specific type for which v is an instance, and for which the current inspector has control, or the result is #f if the current inspector does not control any structure type for which the [struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) is an instance.\n\n- skipped?: #f if the first result corresponds to the most specific structure type of v, #t otherwise.\n\n> ```\n(parameter)\t→\t\n(-> listof exact-nonnegative-integer?)\n```"} {"text": "# 14.7 Custodians\nReturns eight values that provide information about the structure type descriptor struct-type, assuming that the type is controlled by the current inspector:\n- name: the structure type’s name as a symbol;\n- init-field-cnt: the number of fields defined by the structure type provided to the constructor procedure (not counting fields created by its ancestor types);\n- auto-field-cnt: the number of fields defined by the structure type without a counterpart in the constructor procedure (not counting fields created by its ancestor types);\n- accessor-proc: an accessor procedure for the structure type, like the one returned by make-struct-type;\n- mutator-proc: a mutator procedure for the structure type, like the one returned by make-struct-type;\n- immutable-k-list: an immutable list of exact non-negative integers that correspond to immutable fields for the structure type;\n- super-type: a structure type descriptor for the most specific ancestor of the type that is controlled by the current inspector, or #f if no ancestor is controlled by the current inspector;\n- skipped?: #f if the seventh result is the most specific ancestor type or if the type has no supertype, #t otherwise.\nIf the type for struct-type is not controlled by the current inspector, the exn:fail:contract exception is raised.\n> ```\n(struct-type-sealed? struct-type)  →  boolean?\n  struct-type : struct-type?```\nReports whether struct-type has the [prop:sealed](creatingmorestructs.html#%28def._%28%28quote._~23~25kernel%29._prop~3asealed%29%29) structure type property."} {"text": "# 14.7 Custodians\nAdded in version 8.0.0.7 of package base.\n> ```\n(struct-type-authentic? struct-type)  →  boolean?\n  struct-type : struct-type?\n```\n(parameter)\t→\t\n(-> or/c symbol? #f)```\n\n\nReturns a [constructor](define-struct.html#%28tech._constructor%29) procedure to create instances of the type for struct-type. If constructor-name is not #f, it is used as the name of the generated [constructor](define-struct.html#%28tech._constructor%29) procedure. If the type for struct-type is not controlled by the current inspector, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\n> ```\n(struct-type-make-predicate struct-type)  →  any\n  struct-type : any/c\n```\nReturns a predicate procedure to recognize instances of the type for struct-type. If the type for struct-type is not controlled by the current inspector, the exn:fail:contract exception is raised.\n> ```\n(object-name v)  →  any\n  v : any/c```"} {"text": "# 14.7 Custodians\nReturns a value for the name of v if v has a name, #f otherwise. The argument v can be any value, but only (some) procedures, [structures](structures.html#%28tech._structure%29), [structure types](structures.html#%28tech._structure._type%29), [structure type properties](structprops.html#%28tech._structure._type._property%29), [regexp values](regexp.html#%28tech._regexp._value%29), [ports](ports.html#%28tech._port%29), [loggers](logging.html#%28tech._logger%29), and [prompt tags](eval-model.html#%28tech._prompt._tag%29) have names. See also [Inferred Value Names](syntax-model.html#%28part._infernames%29)."} {"text": "# 14.7 Custodians\nIf a [structure](structures.html#%28tech._structure%29)’s type implements the [prop:object-name](#%28def._%28%28quote._~23~25kernel%29._prop~3aobject-name%29%29) property, and the value of the [prop:object-name](#%28def._%28%28quote._~23~25kernel%29._prop~3aobject-name%29%29) property is an integer, then the corresponding field of the structure is the name of the structure. Otherwise, the property value must be a procedure, which is called with the structure as argument, and the result is the name of the structure. If a [structure](structures.html#%28tech._structure%29) is a procedure as implemented by one of its fields (i.e., the [prop:procedure](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._prop~3aprocedure%29%29) property value for the structure’s type is an integer), then its name is the implementing procedure’s name. Otherwise, its name matches the name of the [structure type](structures.html#%28tech._structure._type%29) that it instantiates.\nThe name (if any) of a procedure is a symbol, unless the procedure is also a structure whose type has the [prop:object-name](#%28def._%28%28quote._~23~25kernel%29._prop~3aobject-name%29%29) property, in which case [prop:object-name](#%28def._%28%28quote._~23~25kernel%29._prop~3aobject-name%29%29) takes precedence. The [procedure-rename](procedures.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._procedure-rename%29%29) function creates a procedure with a specific name."} {"text": "# 14.7 Custodians\nThe name of a [regexp value](regexp.html#%28tech._regexp._value%29) is a string or byte string. Passing the string or byte string to [regexp](regexp.html#%28def._%28%28quote._~23~25kernel%29._regexp%29%29), [byte-regexp](regexp.html#%28def._%28%28quote._~23~25kernel%29._byte-regexp%29%29), [pregexp](regexp.html#%28def._%28%28quote._~23~25kernel%29._pregexp%29%29), or [byte-pregexp](regexp.html#%28def._%28%28quote._~23~25kernel%29._byte-pregexp%29%29) (depending on the kind of regexp whose name was extracted) produces a value that matches the same inputs.\nThe name of a port can be any value, but many tools use a path or string name as the port’s for (to report source locations, for example).\nThe name of a [logger](logging.html#%28tech._logger%29) is either a symbol or #f.\nThe name of a [prompt tag](eval-model.html#%28tech._prompt._tag%29) is either the optional symbol given to [make-continuation-prompt-tag](cont.html#%28def._%28%28quote._~23~25kernel%29._make-continuation-prompt-tag%29%29) or #f.\nChanged in version 7.9.0.13 of package base: Recognize the name of continuation prompt tags.\n>
\n

value

\n

[prop:object-name](#%28def._%28%28quote._~23~25kernel%29._prop~3aobject-name%29%29) : [struct-type-property?](structprops.html#%28def._%28%28quote._~23~25kernel%29._struct-type-property~3f%29%29)

"} {"text": "# 14.7 Custodians\nA [structure type property](structprops.html#%28tech._structure._type._property%29) that allows structure types to customize the result of [object-name](#%28def._%28%28quote._~23~25kernel%29._object-name%29%29) applied to their instances. The property value can be any of the following:\n- A procedure proc of one argument: In this case, procedure proc receives the structure as an argument, and the result of proc is the [object-name](#%28def._%28%28quote._~23~25kernel%29._object-name%29%29) of the structure.\n- An exact, non-negative integer between 0 (inclusive) and the number of non-automatic fields in the structure type (exclusive, not counting supertype fields): The integer identifies a field in the structure, and the field must be designated as immutable. The value of the field is used as the [object-name](#%28def._%28%28quote._~23~25kernel%29._object-name%29%29) of the structure.\nAdded in version 6.2 of package base.\n------------------------------------------------------------------------"} {"text": "# 14.10 Code Inspectors"} {"text": "### 14.10 Code Inspectors\nIn the same way that inspectors control access to structure fields (see [Structure Inspectors](inspectors.html)), inspectors also control access to [module bindings](syntax-model.html#%28tech._module._binding%29). Inspectors used this way are code inspectors. The default code inspector for [module bindings](syntax-model.html#%28tech._module._binding%29) is determined by the [current-code-inspector](#%28def._%28%28quote._~23~25kernel%29._current-code-inspector%29%29) parameter, instead of the [current-inspector](inspectors.html#%28def._%28%28quote._~23~25kernel%29._current-inspector%29%29) parameter."} {"text": "# 14.10 Code Inspectors\nWhen a [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) declaration is evaluated, the value of the [current-code-inspector](#%28def._%28%28quote._~23~25kernel%29._current-code-inspector%29%29) parameter is associated with the module declaration. When the module is invoked via [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) or [dynamic-require](Module_Names_and_Loading.html#%28def._%28%28quote._~23~25kernel%29._dynamic-require%29%29), a sub-inspector of the module’s declaration-time inspector is created, and this sub-inspector is associated with the module invocation. Any inspector that controls the sub-inspector (including the declaration-time inspector and its superior) controls the module invocation. In particular, if the value of [current-code-inspector](#%28def._%28%28quote._~23~25kernel%29._current-code-inspector%29%29) never changes, then no control is lost for any module invocation, since the module’s invocation is associated with a sub-inspector of [current-code-inspector](#%28def._%28%28quote._~23~25kernel%29._current-code-inspector%29%29)."} {"text": "# 14.10 Code Inspectors\nWhen an inspector that controls a module invocation is installed with [current-code-inspector](#%28def._%28%28quote._~23~25kernel%29._current-code-inspector%29%29), it enables using [module->namespace](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._module-~3enamespace%29%29) on the module, and it enables access to the module’s protected exports (i.e., those identifiers exported from the module with [protect-out](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._protect-out%29%29)) via [dynamic-require](Module_Names_and_Loading.html#%28def._%28%28quote._~23~25kernel%29._dynamic-require%29%29). A module cannot [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) a module that has a weaker declaration-time code inspector."} {"text": "# 14.10 Code Inspectors\nWhen a [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29) form is expanded or a [namespace](syntax-model.html#%28tech._namespace%29) is created, the value of [current-code-inspector](#%28def._%28%28quote._~23~25kernel%29._current-code-inspector%29%29) is associated with the module or namespace’s top-level [lexical information](syntax-model.html#%28tech._lexical._information%29). Syntax objects with that [lexical information](syntax-model.html#%28tech._lexical._information%29) gain access to the protected and unexported bindings of any module that the inspector controls. In the case of a [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29), the inspector sticks with such syntax objects even the syntax object is used in the expansion of code in a less powerful context; furthermore, if the syntax object is an identifier that is compiled as a variable reference, the inspector sticks with the variable reference even if it appears in a module form that is evaluated (i.e., declared) with a weaker inspector. When a syntax object or variable reference is within compiled code that is printed (see [Printing Compiled Code](printing.html#%28part._print-compiled%29)), the associated inspector is not preserved."} {"text": "# 14.10 Code Inspectors\nWhen compiled code in printed form is [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29) back in, no inspectors are associated with the code. When the code is [eval](eval.html#%28def._%28%28quote._~23~25kernel%29._eval%29%29)uated, the instantiated syntax-object literals and module-variable references acquire value of [current-code-inspector](#%28def._%28%28quote._~23~25kernel%29._current-code-inspector%29%29) as their inspector.\nWhen a module instantiation is attached to multiple [namespaces](syntax-model.html#%28tech._namespace%29), each with its own [module registry](syntax-model.html#%28tech._module._registry%29), the inspector for the module invocation can be registry-specific. The invocation inspector in a particular module registry can be changed via [namespace-unprotect-module](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._namespace-unprotect-module%29%29) (but changing the inspector requires control over the old one).\nChanged in version 8.1.0.8 of package base: Added constraint against [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) of a module with a weaker code inspector.\n> ```\n(current-code-inspector)\t→\t\n(-> current-code-inspector insp)\n(current-code-inspector insp) → void?\n insp\t:\t\n(-> current-code-inspector insp)"} {"text": "# 14.10 Code Inspectors\n```\nA parameter that determines an inspector to control access to module bindings and redefinitions.\n\nIf the code inspector is changed from its original value, then bytecode loaded by the default compiled-load handler is marked as non-runnable.\n\n------------------------------------------------------------------------\n\n# 14.11 Plumbers\n\n### 14.11 Plumbers\n\nA plumber supports flush callbacks, which are normally triggered just before a Racket process or place exits. For example, a flush callback might flush an output port’s buffer.\n\n> > > Flush callbacks are roughly analogous to the standard C library’s atexit, but flush callback can also be used in other, similar scenarios.\n\nThere is no guarantee that a flush callback will be called before a process terminates—either because the plumber is not the original plumber that is flushed by the default exit handler, or because the process is terminated forcibly (e.g., through a custodian shutdown).\n\n> ```\n(plumber? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a [plumber](#%28tech._plumber%29) value, #f otherwise.\n\nAdded in version 6.0.1.8 of package base.\n\n> ```\n(make-plumber)  →  plumber?\n```\n(current-plumber)\t→\t\n(-> current-plumber plumber)\n(current-plumber plumber) → void?\n plumber\t:\t\n(-> current-plumber plumber)```"} {"text": "# 14.10 Code Inspectors\nA [parameter](eval-model.html#%28tech._parameter%29) that determines a current plumber for [flush callbacks](#%28tech._flush._callback%29). For example, creating an output [file stream port](file-ports.html#%28tech._file._stream._port%29) registers a [flush callback](#%28tech._flush._callback%29) with the [current plumber](#%28tech._current._plumber%29) to flush the port as long as the port is opened.\nAdded in version 6.0.1.8 of package base.\n> ```\n(parameter)\t→\n```\nCalls all flush callbacks that are registered with plumber.\n\nThe flush callbacks to call are collected from plumber before the first one is called. If a flush callback registers a new flush callback, the new one is not called. If a flush callback raises an exception or otherwise escapes, then the remaining flush callbacks are not called.\n\nAdded in version 6.0.1.8 of package base.\n\n> ```\n(plumber-flush-handle? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a flush handle represents the registration of a [flush callback](#%28tech._flush._callback%29), #f otherwise.\n\nAdded in version 6.0.1.8 of package base.\n\n> ```\n(plumber-add-flush! plumber proc [weak?) → plumber-flush-handle?\n  plumber : plumber?\n  proc : (plumber-flush-handle? . → . any)\n  weak? : any/c = #f\n```\n(parameter)\t→```\nUnregisters the [flush callback](#%28tech._flush._callback%29) that was registered by the [plumber-add-flush!](#%28def._%28%28quote._~23~25kernel%29._plumber-add-flush%21%29%29) call that produced handle."} {"text": "# 14.10 Code Inspectors\nIf the registration represented by handle has been removed already, then [plumber-flush-handle-remove!](#%28def._%28%28quote._~23~25kernel%29._plumber-flush-handle-remove%21%29%29) has no effect.\nAdded in version 6.0.1.8 of package base.\n------------------------------------------------------------------------"} {"text": "# 14.12 Sandboxed Evaluation"} {"text": "### 14.12 Sandboxed Evaluation\n| | |\n|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/sandbox]()) |  package: [sandbox-lib](https://pkgs.racket-lang.org/package/sandbox-lib \"Install this package using `raco pkg install sandbox-lib`\") |\nThe bindings documented in this section are provided by the [racket/sandbox]() library, not [racket/base](index.html) or [racket](index.html).\nThe [racket/sandbox]() module provides utilities for creating “sandboxed” evaluators, which are configured in a particular way and can have restricted resources (memory and time), filesystem and network access, and much more. Sandboxed evaluators can be configured through numerous parameters — and the defaults are set for the common use case where sandboxes are very limited.\n> ```\n(parameter)\t→\t\n(-> any/c . → . any)"} {"text": "# 14.12 Sandboxed Evaluation\n```\n(transitively)\t→\t\n(-> exn:fail:sandbox-terminated-reason exn)```\n\n\nA predicate and accessor for exceptions that are raised when a sandbox is terminated. Once a sandbox raises such an exception, it will continue to raise it on further evaluation attempts.\n\n#### 14.12.1 Security Considerations\n\nAlthough the sandbox is designed to provide a safe environment for executing Racket programs with restricted access to system resources, executing untrusted programs in a sandbox still carries some risk. Because a malicious program can exercise arbitrary functionality from the Racket runtime and installed collections, an attacker who identifies a vulnerability in Racket or an installed collection may be able to escape the sandbox.\n\nTo mitigate this risk, programs that use the sandbox should employ additional precautions when possible. Suggested measures include:\n\n- Supplying a custom module language to [make-evaluator](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._make-evaluator%29%29) or [make-module-evaluator](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._make-module-evaluator%29%29) that gives untrusted code access to only the language constructs it absolutely requires.\n\n- If untrusted code needs access to installed collections, installing only the collections required by your program.\n\n- Using operating-system-level security features to provide defense-in-depth in case the process running the sandbox is compromised.\n\n- Making sure your Racket installation and installed packages are up-to-date with the latest release.\n\n#### 14.12.2 Customizing Evaluators\n\nThe sandboxed evaluators that [make-evaluator](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._make-evaluator%29%29) creates can be customized via many parameters. Most of the configuration parameters affect newly created evaluators; changing them has no effect on already-running evaluators.\n\nThe default configuration options are set for a very restricted sandboxed environment — one that is safe to make publicly available. Further customizations might be needed in case more privileges are needed, or if you want tighter restrictions. Another useful approach for customizing an evaluator is to begin with a relatively unrestricted configuration and add the desired restrictions. This approach is made possible by the [call-with-trusted-sandbox-configuration](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._call-with-trusted-sandbox-configuration%29%29) function.\n\nThe sandbox environment uses two notions of restricting the time that evaluations takes: [shallow time](#%28tech._shallow._time%29) and [deep time](#%28tech._deep._time%29). Shallow time refers to the immediate execution of an expression. For example, a [shallow time](#%28tech._shallow._time%29) limit of five seconds would restrict ([sleep](threads.html#%28def._%28%28quote._~23~25kernel%29._sleep%29%29) 6) and other computations that take longer than five seconds. Deep time refers to the total execution of the expression and all threads and sub-processes that the expression creates. For example, a [deep time](#%28tech._deep._time%29) limit of five seconds would restrict ([thread](threads.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._thread%29%29) ([λ](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~ce~bb%29%29) () ([sleep](threads.html#%28def._%28%28quote._~23~25kernel%29._sleep%29%29) 6))), which [shallow time](#%28tech._shallow._time%29) would not, as well as all expressions that [shallow time](#%28tech._shallow._time%29) would restrict. By default, most sandboxes only restrict [shallow time](#%28tech._shallow._time%29) to facilitate expressions that use threads.\n\n> ```\n(call-with-trusted-sandbox-configuration thunk)  →  any\n  thunk : ( →  any)\n```"} {"text": "# 14.12 Sandboxed Evaluation\n(sandbox-init-hook)\t→\t\n(-> any)\n(sandbox-init-hook thunk) → void?\n thunk\t:\t\n(-> any)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines a thunk to be called for initializing a new evaluator. The hook is called just before the program is evaluated in a newly-created evaluator context. It can be used to setup environment parameters related to reading, writing, evaluation, and so on. Certain languages ('(special r5rs) and the teaching languages) have initializations specific to the language; the hook is used after that initialization, so it can override settings.\n> ```\n(sandbox-reader)\t→\t\n(-> any/c . → . any)\n(sandbox-reader proc) → void?\n proc\t:\t\n(-> any/c . → . any)"} {"text": "# 14.12 Sandboxed Evaluation\n```\n(current-input-port)\t→\t\n(-> or/c #f\n string? bytes?\n input-port?\n ' pipe\n (→ input-port?))```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the initial [current-input-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._current-input-port%29%29) setting for a newly created evaluator. It defaults to #f, which creates an empty port. The following other values are allowed:\n\n- a string or byte string, which is converted to a port using [open-input-string](stringport.html#%28def._%28%28quote._~23~25kernel%29._open-input-string%29%29) or [open-input-bytes](stringport.html#%28def._%28%28quote._~23~25kernel%29._open-input-bytes%29%29);\n\n- an input port;\n\n- the symbol 'pipe, which triggers the creation of a pipe, where [put-input](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._put-input%29%29) can return the output end of the pipe or write directly to it;\n\n- a thunk, which is called to obtain a port (e.g., using [current-input-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._current-input-port%29%29) means that the evaluator input is the same as the calling context’s input).\n\n> ```\n(sandbox-output)\t→\t\n(-> or/c #f\n output-port?\n ' pipe\n ' bytes\n ' string\n (→ output-port?))\n(sandbox-output in) → void?\n in\t:\t\n(-> or/c #f\n output-port?\n ' pipe\n ' bytes\n ' string\n (→ output-port?))\n```"} {"text": "# 14.12 Sandboxed Evaluation\n(sandbox-error-output)\t→\t\n(-> or/c #f\n output-port?\n ' pipe\n ' bytes\n ' string\n (→ output-port?))\n(sandbox-error-output in) → void?\n in\t:\t\n(-> or/c #f\n output-port?\n ' pipe\n ' bytes\n ' string\n (→ output-port?))```\nLike [sandbox-output](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._sandbox-output%29%29), but for the initial [current-error-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._current-error-port%29%29) value. An evaluator’s error output is set after its output, so using [current-output-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._current-output-port%29%29) (the parameter itself, not its value) for this parameter value means that the error port is the same as the evaluator’s initial output port.\nThe default is ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) () ([dup-output-port](port-lib.html#%28def._%28%28lib._racket%2Fport..rkt%29._dup-output-port%29%29) ([current-error-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._current-error-port%29%29)))), which means that the error output of the generated evaluator goes to the calling context’s error port.\n> ```\n(sandbox-coverage-enabled)\t→\t\n(-> sandbox-coverage-enabled enabled?)"} {"text": "# 14.12 Sandboxed Evaluation\n```\n(sandbox-propagate-breaks)\t→\t\n(-> sandbox-propagate-breaks propagate?)```\n\n\nWhen both this boolean parameter and ([break-enabled](breakhandler.html#%28def._%28%28quote._~23~25kernel%29._break-enabled%29%29)) are true, breaking while an evaluator is running propagates the break signal to the sandboxed context. This makes the sandboxed evaluator break, typically, but beware that sandboxed evaluation can capture and avoid the breaks (so if safe execution of code is your goal, make sure you use it with a time limit). Also, beware that a break may be received after the evaluator’s result, in which case the evaluation result is lost. Finally, beware that a break may be propagated after an evaluator has produced a result, so that the break is visible on the next interaction with the evaluator (or the break is lost if the evaluator is not used further). The default is #t.\n\n> ```\n(sandbox-propagate-exceptions)\t→\t\n(-> sandbox-propagate-exceptions propagate?)\n```\n(sandbox-namespace-specs)\t→\t\n(-> cons/c (→ namespace?)\n (listof module-path?))\n(sandbox-namespace-specs spec) → void?\n spec\t:\t\n(-> cons/c (→ namespace?)\n (listof module-path?))```"} {"text": "# 14.12 Sandboxed Evaluation\nA [parameter](eval-model.html#%28tech._parameter%29) that holds a list of values that specify how to create a namespace for evaluation in [make-evaluator](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._make-evaluator%29%29) or [make-module-evaluator](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._make-module-evaluator%29%29). The first item in the list is a thunk that creates the namespace, and the rest are module paths for modules to be attached to the created namespace using [namespace-attach-module](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._namespace-attach-module%29%29).\nThe default is ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) [sandbox-make-namespace](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._sandbox-make-namespace%29%29)).\nThe module paths are needed for sharing module instantiations between the sandbox and the caller. For example, sandbox code that returns posn values (from the lang/posn module) will not be recognized as such by your own code by default, since the sandbox will have its own instance of lang/posn and thus its own struct type for posns. To be able to use such values, include 'lang/posn in the list of module paths.\nWhen testing code that uses a teaching language, the following piece of code can be helpful:\n> ```racket\n> ( sandbox-namespace-specs\n> ( let ( [ specs ( sandbox-namespace-specs ) ] )\n> ` ( , ( car specs )\n> ,@ ( cdr specs )\n> lang/posn\n> ,@ ( if ( gui-available? ) ' ( mrlib/cache-image-snip ) ' ( ) ) ) ) )\n> ```\n> ```\n(sandbox-make-namespace)  →  namespace?"} {"text": "# 14.12 Sandboxed Evaluation\n```\nCalls make-gui-namespace when (sandbox-gui-available) produces true, make-base-namespace otherwise.\n\n> ```\n(sandbox-gui-available)\t → \t\n( → sandbox-gui-available avail?)```\n\n\nDetermines whether the [racket/gui](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=gui&rel=index.html&version=8.18.0.13) module can be used when a sandbox evaluator is created. If [gui-available?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=gui&rel=Dynamic_Loading.html%23%2528def._%2528%2528lib._racket%252Fgui%252Fdynamic..rkt%2529._gui-available%7E3f%2529%2529&version=8.18.0.13) produces #f during the creation of a sandbox evaluator, this parameter is forced to #f during initialization of the sandbox. The default value of the parameter is #t.\n\nVarious aspects of the library change when the GUI library is available, such as using a new eventspace for each evaluator.\n\n> ```\n(sandbox-override-collection-paths)\t→\t\n(-> listof path-string?)\n(sandbox-override-collection-paths paths) → void?\n paths\t:\t\n(-> listof path-string?)\n```\n(sandbox-security-guard)\t→\t\n(-> or/c security-guard? (→ security-guard?))\n(sandbox-security-guard guard) → void?\n guard\t:\t\n(-> or/c security-guard? (→ security-guard?))```"} {"text": "# 14.12 Sandboxed Evaluation\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the initial ([current-security-guard](securityguards.html#%28def._%28%28quote._~23~25kernel%29._current-security-guard%29%29)) for sandboxed evaluations. It can be either a security guard, or a function to construct one. The default is a function that restricts the access of the current security guard by forbidding all filesystem I/O except for specifications in [sandbox-path-permissions](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._sandbox-path-permissions%29%29), and it uses [sandbox-network-guard](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._sandbox-network-guard%29%29) for network connections.\n> ```\n(sandbox-path-permissions)\t→\t\n(-> listof (list/c (or/c ' execute ' write ' delete\n ' read-bytecode ' read ' exists)\n (or/c byte-regexp? bytes? string? path?)))\n(sandbox-path-permissions perms) → void?\n perms\t:\t\n(-> listof (list/c (or/c ' execute ' write ' delete\n ' read-bytecode ' read ' exists)\n (or/c byte-regexp? bytes? string? path?)))"} {"text": "# 14.12 Sandboxed Evaluation\n```\n(sandbox-network-guard)\t→\t\n(-> symbol?\n (or/c (and/c string? immutable?) #f)\n (or/c (integer-in 1 65535) #f)\n (or/c ' server ' client)\n . → . any)\n(sandbox-network-guard proc) → void?\n proc\t:\t\n(-> symbol?\n (or/c (and/c string? immutable?) #f)\n (or/c (integer-in 1 65535) #f)\n (or/c ' server ' client)\n . → . any)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that specifies a procedure to be used (as is) by the default [sandbox-security-guard](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._sandbox-security-guard%29%29). The default forbids all network connection.\n\n> ```\n(sandbox-exit-handler)\t→\t\n(-> any/c . → . any)\n(sandbox-exit-handler handler) → void?\n handler\t:\t\n(-> any/c . → . any)\n```\n(exit-handler)\t→\t\n(-> or/c (>=/c 0) #f)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the total memory limit on the sandbox in megabytes (it can hold a rational or a floating point number). When this limit is exceeded, the sandbox is terminated. This value is used when the sandbox is created and the limit cannot be changed afterwards. It defaults to 30mb. See [sandbox-eval-limits](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._sandbox-eval-limits%29%29) for per-evaluation limits and a description of how the two limits work together."} {"text": "# 14.12 Sandboxed Evaluation\nNote that (when memory accounting is enabled) memory is attributed to the highest custodian that refers to it. This means that if you inspect a value that sandboxed evaluation returns outside of the sandbox, your own custodian will be charged for it. To ensure that it is charged back to the sandbox, you should remove references to such values when the code is done inspecting it.\nThis policy has an impact on how the sandbox memory limit interacts with the per-expression limit specified by [sandbox-eval-limits](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._sandbox-eval-limits%29%29): values that are reachable from the sandbox, as well as from the interaction will count against the sandbox limit. For example, in the last interaction of this code,\n> ```racket\n> ( define e ( make-evaluator ' racket/base ) )\n> ( e ' ( define a 1 ) )\n> ( e ' ( for ( [ i ( in-range 20 ) ] ) ( set! a ( cons ( make-bytes 500000 ) a ) ) ) )\n> ```\nthe memory blocks are allocated within the interaction limit, but since they’re chained to the defined variable, they’re also reachable from the sandbox — so they will count against the sandbox memory limit but not against the interaction limit (more precisely, no more than one block counts against the interaction limit).\n> ```\n(sandbox-eval-limits)\t→\t\n(-> or/c (list/c (or/c (>=/c 0) #f)\n (or/c (>=/c 0) #f))\n #f)\n(sandbox-eval-limits limits) → void?\n limits\t:\t\n(-> or/c (list/c (or/c (>=/c 0) #f)\n (or/c (>=/c 0) #f))\n #f)"} {"text": "# 14.12 Sandboxed Evaluation\n```\n(sandbox-eval-handlers)\t→\t\n(-> list/c (or/c #f ((→ any) . → . any))\n (or/c #f ((→ any) . → . any)))\n(sandbox-eval-handlers handlers) → void?\n handlers\t:\t\n(-> list/c (or/c #f ((→ any) . → . any))\n (or/c #f ((→ any) . → . any)))```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines two (optional) handlers that wrap sandboxed evaluations. The first one is used when evaluating the initial program when the sandbox is being set-up, and the second is used for each interaction. Each of these handlers should expect a thunk as an argument, and they should execute these thunks — possibly imposing further restrictions. The default values are #f and [call-with-custodian-shutdown](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._call-with-custodian-shutdown%29%29), meaning no additional restrictions on initial sandbox code (e.g., it can start background threads), and a custodian-shutdown around each interaction that follows. Another useful function for this is [call-with-killing-threads](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._call-with-killing-threads%29%29) which kills all threads, but leaves other resources intact.\n\n> ```\n(sandbox-run-submodules)\t→\t\n(-> list/c symbol?)\n(sandbox-run-submodules submod-syms) → void?\n submod-syms\t:\t\n(-> list/c symbol?)\n```\n(sandbox-make-inspector)\t→\t\n(-> inspector?)\n(sandbox-make-inspector make) → void?\n make\t:\t\n(-> inspector?)```"} {"text": "# 14.12 Sandboxed Evaluation\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the (nullary) procedure that is used to create the inspector for sandboxed evaluation. The procedure is called when initializing an evaluator. The default parameter value is ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) () ([make-inspector](inspectors.html#%28def._%28%28quote._~23~25kernel%29._make-inspector%29%29) ([current-inspector](inspectors.html#%28def._%28%28quote._~23~25kernel%29._current-inspector%29%29)))).\n> ```\n(sandbox-make-code-inspector)\t→\t\n(-> inspector?)\n(sandbox-make-code-inspector make) → void?\n make\t:\t\n(-> inspector?)\n```\n(nullary)\t→\t\n(-> logger?)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the procedure used to create the logger for sandboxed evaluation. The procedure is called when initializing an evaluator, and the default parameter value is [current-logger](logging.html#%28def._%28%28quote._~23~25kernel%29._current-logger%29%29). This means that it is not creating a new logger (this might change in the future).\n\n> ```\n(sandbox-make-plumber)\t→\t\n(-> or/c (→ plumber?) 'propagate)\n(sandbox-make-plumber make) → void?\n make\t:\t\n(-> or/c (→ plumber?) 'propagate)\n```\n(sandbox-make-environment-variables)\t→\t\n(-> environment-variables?)\n(sandbox-make-environment-variables make) → void?\n make\t:\t\n(-> environment-variables?)```"} {"text": "# 14.12 Sandboxed Evaluation\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the procedure used to create the [environment variable set](envvars.html#%28tech._environment._variable._set%29) for sandboxed evaluation. The procedure is called when initializing an evaluator, and the default parameter value constructs a new [environment variable set](envvars.html#%28tech._environment._variable._set%29) using ([environment-variables-copy](envvars.html#%28def._%28%28quote._~23~25kernel%29._environment-variables-copy%29%29) ([current-environment-variables](envvars.html#%28def._%28%28quote._~23~25kernel%29._current-environment-variables%29%29))).\n> ```\n(default-language-readers lang)  →  (listof module-path?)\n  lang : module-path?\n```\n\n\nCreates a default list of readers that should be allowed to produce a module that uses lang as the language.\n\nThis default list includes the following (and more paths may be added in the future):\n\n- \\`(submod ,lang reader)\n\n- ’lang/lang/reader if lang is a symbol\n\n- the module path producing by adding the relative path \"lang/reader.rkt\" to lang if lang is not a symbol\n\n- '(submod at-exp reader)\n\n- 'at-exp/lang/reader\n\nAdded in version 1.2 of package sandbox-lib.\n\n#### 14.12.3 Interacting with Evaluators\n\nThe following functions are used to interact with a sandboxed evaluator in addition to using it to evaluate code.\n\n> ```\n(evaluator-alive? evaluator)  →  boolean?\n  evaluator : (any/c . → . any)\n```\nDetermines whether the evaluator is still alive.\n> ```\n(parameter)\t→\t\n(-> any/c . → . any)"} {"text": "# 14.12 Sandboxed Evaluation\n```\n(parameter)\t→\t\n(-> any/c . → . any)```\n\n\nSends a break to the running evaluator. The effect of this is as if Ctrl-C was typed when the evaluator is currently executing, which propagates the break to the evaluator’s context.\n\n> ```\n(parameter)\t→\t\n(-> any/c . → . any)\n```\n(current-custodian)\t→\t\n(-> any/c . → . any)```\nChanges the per-expression limits that evaluator uses to secs seconds of [shallow time](#%28tech._shallow._time%29) and mb megabytes (either one can be #f, indicating no limit).\nThis procedure should be used to modify an existing evaluator limits, because changing the [sandbox-eval-limits](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._sandbox-eval-limits%29%29) parameter does not affect existing evaluators. See also [call-with-limits](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._call-with-limits%29%29).\n> ```\n(parameter)\t→\t\n(-> any/c . → . any)\n```\n(parameter)\t→\t\n(-> any)```\n\n\nThese functions are useful for use as an evaluation handler. [call-with-custodian-shutdown](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._call-with-custodian-shutdown%29%29) will execute the thunk in a fresh custodian, then shutdown that custodian, making sure that thunk could not have left behind any resources. [call-with-killing-threads](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._call-with-killing-threads%29%29) is similar, except that it kills threads that were left, but leaves other resources as is.\n\n> ```\n(parameter)\t→\t\n(-> any/c . → . any)\n```"} {"text": "# 14.12 Sandboxed Evaluation\nIf (sandbox-input) is 'pipe when an evaluator is created, then this procedure can be used to retrieve the output port end of the pipe (when used with no arguments), or to add a string or a byte string into the pipe. It can also be used with eof, which closes the pipe.\n> ```\n(get-output evaluator)  →  (or/c #f input-port? bytes? string?)\n  evaluator : (any/c . → . any)\n(get-error-output evaluator)\n  →  (or/c #f input-port? bytes? string?)\n  evaluator : (any/c . → . any)```\nReturns the output or error-output of the evaluator, in a way that depends on the setting of ([sandbox-output](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._sandbox-output%29%29)) or ([sandbox-error-output](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._sandbox-error-output%29%29)) when the evaluator was created:\n- if it was 'pipe, then [get-output](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._get-output%29%29) returns the input port end of the created pipe;\n- if it was 'bytes or 'string, then the result is the accumulated output, and the output port is reset so each call returns a different piece of the evaluator’s output (note that results are available only until the evaluator has terminated, and any allocations of the output are subject to the sandbox memory limit);\n- otherwise, it returns #f.\n> ```\n(get-uncovered-expressions evaluator\n   [ prog?        \n    src)   →   (listof syntax?)\n  evaluator : (any/c . → . any)\n  prog? : any/c = #t\n  src : any/c = default-src"} {"text": "# 14.12 Sandboxed Evaluation\n```\nRetrieves uncovered expression from an evaluator, as longs as the sandbox-coverage-enabled parameter had a true value when the evaluator was created. Otherwise, an exception is raised to indicate that no coverage information is available.\n\nThe prog? argument specifies whether to obtain expressions that were uncovered after only the original input program was evaluated (#t) or after all later uses of the evaluator (#f). Using #t retrieves a list that is saved after the input program is evaluated, and before the evaluator is used, so the result is always the same.\n\nA #t value of prog? is useful for testing student programs to find out whether a submission has sufficient test coverage built in. A #f value is useful for writing test suites for a program to ensure that your tests cover the whole code.\n\nThe second optional argument, src, specifies that the result should be filtered to hold only syntax objects whose source matches src. The default is the source that was used in the program code, if there was one. Note that 'program is used as the source value if the input program was given as S-expressions or as a string (and in these cases it will be the default for filtering). If given #f, the result is the unfiltered list of expressions.\n\nThe resulting list of syntax objects has at most one expression for each position and span. Thus, the contents may be unreliable, but the position information is reliable (i.e., it always indicates source code that would be painted red in DrRacket when coverage information is used).\n\nNote that if the input program is a sequence of syntax values, either make sure that they have 'program as the source field, or use the src argument. Using a sequence of S-expressions (not syntax objects) for an input program leads to unreliable coverage results, since each expression may be assigned a single source location.\n\n> ```\n(call-in-sandbox-context evaluator\n    thunk        \n   [ unrestricted?)   →   any\n\n  evaluator : (any/c . → . any)\n  thunk : ( →  any)\n  unrestricted? : boolean? = #f```\n\n\nCalls the given thunk in the context of a sandboxed evaluator. The call is performed under the resource limits and evaluation handler that are used for evaluating expressions, unless unrestricted? is specified as true.\n\nThis process is usually similar to (evaluator ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) thunk)), except that it does not rely on the common meaning of a sexpr-based syntax with list expressions as function application (which is not true in all languages). Note that this is more useful for meta-level operations such as namespace manipulation, it is not intended to be used as a safe-evaluation replacement (i.e., using the sandbox evaluator as usual).\n\nIn addition, you can avoid some of the sandboxed restrictions by using your own permissions, for example,\n\n> ```racket\n> ( let ( [ guard ( current-security-guard ) ] )\n> ( call-in-sandbox-context\n> ev\n> ( lambda ( )\n> ( parameterize ( [ current-security-guard guard ] )\n> ; can access anything you want here\n> ( delete-file \"/some/file\" ) ) ) ) )\n> ```\n\n#### 14.12.4 Miscellaneous\n\n>
\n\n

value

\n\n

[gui?](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._gui~3f%29%29) : [boolean?](booleans.html#%28def._%28%28quote._~23~25kernel%29._boolean~3f%29%29)

\n\nFor backward compatibility, only: the result of [gui-available?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=gui&rel=Dynamic_Loading.html%23%2528def._%2528%2528lib._racket%252Fgui%252Fdynamic..rkt%2529._gui-available%7E3f%2529%2529&version=8.18.0.13) at the time that [racket/sandbox]() was instantiated.\n\nThe value of [gui?](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._gui~3f%29%29) is no longer used by [racket/sandbox]() itself. Instead, [gui-available?](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=gui&rel=Dynamic_Loading.html%23%2528def._%2528%2528lib._racket%252Fgui%252Fdynamic..rkt%2529._gui-available%7E3f%2529%2529&version=8.18.0.13) and [sandbox-gui-available](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._sandbox-gui-available%29%29) are checked at the time that a sandbox evaluator is created.\n\n> ```\n(call-with-limits secs mb thunk)  →  any\n  secs : (or/c exact-nonnegative-integer? #f)\n  mb : (or/c exact-nonnegative-integer? #f)\n  thunk : ( →  any)\n```"} {"text": "# 14.12 Sandboxed Evaluation\nExecutes the given thunk with memory and time restrictions: if execution consumes more than mb megabytes or more than secs shallow time seconds, then the computation is aborted and an exception recognizable by exn:fail:resource? is raised. Otherwise, the result of the thunk is returned as usual (a value, multiple values, or an exception). Each of the two limits can be #f to indicate the absence of a limit. See also custodian-limit-memory for information on memory limits.\nTo enforce limits, thunk is run in a new thread. As usual, the new thread starts with the same parameter values as the one that calls call-with-limits. Not as usual, parameter values from the thread used to run thunk are copied back to the thread that called call-with-limits when thunk completes.\nSandboxed evaluators use call-with-limits, according to the sandbox-eval-limits setting and uses of set-eval-limits: each expression evaluation is protected from timeouts and memory problems. Use call-with-limits directly only to limit a whole testing session, instead of each expression.\n>
\n

syntax

\n

(with-limits sec-expr mb-expr body ...)

\nA macro version of call-with-limits.\n> ```\n(call-with-deep-time-limit secs thunk) → any\n  secs : exact-nonnegative-integer?\n  thunk : ( →  any)```\nExecutes the given thunk with [deep time](#%28tech._deep._time%29) restrictions, and returns the values produced by thunk."} {"text": "# 14.12 Sandboxed Evaluation\nThe given thunk is run in a new thread. If it errors or if the thread terminates returning a value, then ([values](values.html#%28def._%28%28quote._~23~25kernel%29._values%29%29)) is returned.\nChanged in version 1.1 of package sandbox-lib: Changed to return thunk’s result if it completes normally.\n>
\n

syntax

\n

([with-deep-time-limit](#%28form._%28%28lib._racket%2Fsandbox..rkt%29._with-deep-time-limit%29%29) secs-expr body ...)

\nA macro version of [call-with-deep-time-limit](#%28def._%28%28lib._racket%2Fsandbox..rkt%29._call-with-deep-time-limit%29%29).\n> ```\n(exn:fail:resource? v)  →  boolean?\n  v : any/c\n(exn:fail:resource-resource exn)\n  →  (or/c 'time 'memory 'deep-time)\n  exn : exn:fail:resource?"} {"text": "# 14.12 Sandboxed Evaluation\n```\nA predicate and accessor for exceptions that are raised by call-with-limits. The resource field holds a symbol, representing the resource that was expended. 'time is used for shallow time and 'deep-time is used for deep time.\n\n------------------------------------------------------------------------\n\n# 14.13 The racket/repl Library\n\n### 14.13 The [racket/repl]() Library\n\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/repl]()) |  package: base |\n\nThe [racket/repl]() provides the same read-eval-print-loop binding as racket/base, but with even fewer internal dependencies than racket/base. It is loaded in some situations on startup, as described in Initialization.\n\n------------------------------------------------------------------------\n\n# 14.14 Linklets and the Core Compiler\n\n### 14.14 Linklets and the Core Compiler\n\n| | |\n|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/linklet]()) |  package: base |\n\nA linklet is a primitive element of compilation, bytecode marshaling, and evaluation. Racket’s implementations of modules, macros, and top-level evaluation are all built on linklets. Racket programmers generally do not encounter linklets directly, but the [racket/linklet]() library provides access to linklet facilities.\n\nA single Racket module (or collection of top-level forms) is typically implemented by multiple linklets. For example, each phase of evaluation that exists in a module is implemented in a separate linklet. A linklet is also used for metadata such as the module path indexes for a module’s requires. These linklets, plus some other metadata, are combined to form a linklet bundle. Information in a linklet bundle is keyed by either a symbol or a fixnum. A linklet bundle containing linklets can be marshaled to and from a byte stream by write and (with read-accept-compiled is enabled) read.\n\nWhen a Racket module has submodules, the linklet bundles for the module and the submodules are grouped together in a linklet directory. A linklet directory can have nested linklet directories. Information in a linklet directory is keyed by #f or a symbol, where #f must be mapped to a linklet bundle (if anything) and each symbol must be mapped to a linklet directory. A linklet directory can be equivalently viewed as a mapping from a lists of symbols to a linklet bundle. Like linklet bundles, a linklet directory can be marshaled to and from a byte stream by write and read; the marshaled form allows individual linklet bundles to be loaded independently.\n\nA linklet consists of a set of variable definitions and expressions, an exported subset of the defined variable names, a set of variables to export from the linklet despite having no corresponding definition, and a set of imports that provide other variables for the linklet to use. To run a linklet, it is instantiated as as linklet instance (or just instance, for short). When a linklet is instantiated, it receives other linklet instances for its imports, and it extracts a specified set of variables that are exported from each of the given instances. The newly created linklet instance provides its exported variables for use by other linklets or for direct access via instance-variable-value. A linklet instance can be synthesized directly with make-instance.\n\nA linklet is created by compiling an enriched S-expression representation of its source. Since linklets exist below the layer of macros and syntax objects, linklet compilation does not use syntax objects. Instead, linklet compilation uses correlated objects, which are like syntax objects without lexical-context information and without the constraint that content is coerced to correlated objects. Using an S-expression or correlated object, the grammar of a linklet as recognized by compile-linklet is\n\n> > ```\n(linklet [[imported-id/renamed ...] ...]\n> > [ exported-id/renamed ... ]\n> > defn-or-expr ... )\n \nimported-id/renamed   =   imported-id\n    |   (external-imported-id internal-imported-id)\n         \nexported-id/renamed   =   exported-id\n    |   (internal-exported-id external-exported-id)```\n\n\nEach import set \\[imported-id/renamed [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)\\] refers to a single imported instance, and each import-id/renamed corresponds to a variable from that instance. If separate external-imported-id and internal-imported-id are specified, then external-imported-id is the name of the variable as exported by the instance, and internal-imported-id is the name used to refer to the variable in the defn-or-exprs. For exports, separate internal-exported-id and external-exported-id names corresponds to the variable name as exported as referenced in the defn-or-exprs, respectively.\n\nThe grammar of an defn-or-expr is similar to the expander’s grammar of fully expanded expressions (see [Fully Expanded Programs](syntax-model.html#%28part._fully-expanded%29)) with some exceptions: [quote-syntax](Syntax_Quoting__quote-syntax.html#%28form._%28%28quote._~23~25kernel%29._quote-syntax%29%29) and [#%top](__top.html#%28form._%28%28quote._~23~25kernel%29._~23~25top%29%29) are not allowed; [#%plain-lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~23~25plain-lambda%29%29) is spelled [lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29); [#%plain-app](application.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._~23~25plain-app%29%29) is omitted (i.e., application is implicit); [lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29), [case-lambda](lambda.html#%28form._%28%28quote._~23~25kernel%29._case-lambda%29%29), [let-values](let.html#%28form._%28%28quote._~23~25kernel%29._let-values%29%29), and [letrec-values](let.html#%28form._%28%28quote._~23~25kernel%29._letrec-values%29%29) can have only a single body expression; begin-unsafe is like [begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29) in an expression position, but its body is compiled in [unsafe mode](#%28tech._unsafe._mode%29); and numbers, booleans, strings, and byte strings are self-quoting. Primitives are accessed directly by name, and shadowing is not allowed within a linklet form for primitive names (see [linklet-body-reserved-symbol?](#%28def._%28%28lib._racket%2Flinklet..rkt%29._linklet-body-reserved-symbol~3f%29%29)), imported variables, defined variables, or local variables.\n\nWhen an exported-id/renamed has no corresponding definition among the defn-or-exprs, then the variable is effectively defined as uninitialized; referencing the variable will trigger [exn:fail:contract:variable](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract~3avariable%29%29), the same as referencing a variable before it is defined. When a target instance is provided to [instantiate-linklet](#%28def._%28%28lib._racket%2Flinklet..rkt%29._instantiate-linklet%29%29), any existing variable with the same name will be left as-is, instead of set to undefined. This treatment of uninitialized variables provides core support for top-level evaluation where variables may be referenced and then defined in a separate element of compilation.\n\nAdded in version 6.90.0.1 of package base.\n\n> ```\n(linklet? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 14.12 Sandboxed Evaluation\nReturns #t if v is a linklet, #f otherwise.\n> ```\n(compile-linklet form\n   [ info        \n    import-keys        \n    get-import        \n    options)   →   linklet?\n  form : (or/c correlated? any/c)\n  info : (or/c hash? any/c) = #f\n  import-keys : #f = #f\n  get-import : #f = #f\n   options   :   ( listof ( or/c ' serializable ' unsafe ' static ' quick\n> ' use-prompt ' unlimited-compile\n> ' uninterned-literal ) )\n      =   '(serializable)\n(compile-linklet   form        \n    info        \n    import-keys        \n   [ get-import        \n    options)   →   linklet?   vector?\n  form : (or/c correlated? any/c)\n  info : (or/c hash? any/c)\n  import-keys : vector?\n   get-import   :   ( or/c #f ( any/c . → . ( values ( or/c linklet? instance? #f )\n> ( or/c vector? #f ) ) ) )\n      =   #f\n   options   :   ( listof ( or/c ' serializable ' unsafe ' static ' quick\n> ' use-prompt ' unlimited-compile\n> ' uninterned-literal ) )\n      =   '(serializable)```\nTakes an S-expression or [correlated object](#%28tech._correlated._object%29) for a linklet form and produces a [linklet](#%28tech._linklet%29). As long as 'serializable included in options, the resulting linklet can be marshaled to and from a byte stream when it is part of a [linklet bundle](#%28tech._linklet._bundle%29) (possibly in a [linklet directory](#%28tech._linklet._directory%29))."} {"text": "# 14.12 Sandboxed Evaluation\nThe optional info hash provides various debugging details about the linklet, such as the module name the linklet is part of, the linklet name, and the phase for body linklets. If a 'name value is present in the hash, it is associated to the linklet for debugging purposes and as the default name of the linklet’s instance. If info is not a hash, it is assumed to be a name value directly for backward compatibility.\nThe optional import-keys and get-import arguments support cross-linklet optimization. If import-keys is a vector, it must have as many elements as sets of imports in form. If the compiler becomes interested in optimizing a reference to an imported variable, it passes back to get-import (if non-#f) the element of import-keys that corresponds to the variable’s import set. The get-import function can then return a linklet or instance that represents an instance to be provided to the compiled linklet when it is eventually instantiated; ensuring consistency between reported linklet or instance and the eventual instance is up to the caller of [compile-linklet](#%28def._%28%28lib._racket%2Flinklet..rkt%29._compile-linklet%29%29), but see also [linklet-add-target-machine-info](#%28def._%28%28lib._racket%2Flinklet..rkt%29._linklet-add-target-machine-info%29%29). If get-import returns #f as its first value, the compiler will be prevented from making any assumptions about the imported instance. The second result from get-import is an optional vector of keys to provide transitive information on a returned linklet’s imports (and is not allowed for a returned instance); the returned vector must have the same number of elements as the linklet has imports. When vector elements are [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) and non-#f, the compiler can assume that they correspond to the same run-time instance. A #f value for get-import is equivalent to a function that always returns two #f results."} {"text": "# 14.12 Sandboxed Evaluation\nWhen import-keys is not #f, then the compiler is allowed to grow or shrink the set of imported instances for the linklet. The result vector specifies the keys of the imports for the returned linklet. Any key that is #f or a [linklet instance](#%28tech._linklet._instance%29) must be preserved intact, however.\nIf 'unsafe is included in options, then the linklet is compiled in unsafe mode: uses of safe operations within the linklet can be converted to unsafe operations on the assumption that the relevant contracts are satisfied. For example, [car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29) is converted to [unsafe-car](unsafe.html#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-car%29%29). Some substituted unsafe operations may not have directly accessible names, such as the unsafe variant of [in-list](sequences.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._in-list%29%29) that can be substituted in [unsafe mode](#%28tech._unsafe._mode%29). An unsafe operation is substituted only if its (unchecked) contract is subsumed by the safe operation’s contract. The fact that the linklet is compiled in [unsafe mode](#%28tech._unsafe._mode%29) can be exposed through [variable-reference-from-unsafe?](Namespaces.html#%28def._%28%28quote._~23~25kernel%29._variable-reference-from-unsafe~3f%29%29) using a variable reference produced by a [#%variable-reference](Locations____variable-reference.html#%28form._%28%28quote._~23~25kernel%29._~23~25variable-reference%29%29) form within the module body. Within a linklet an individual expression can be compiled in unsafe mode by wrapping it in begin-unsafe; when a whole linklet is compiled in unsafe mode, begin-unsafe is redundant and ignored."} {"text": "# 14.12 Sandboxed Evaluation\nIf 'static is included in options, then the linklet must be instantiated only once; if the linklet is serialized, then any individual instance read from the serialized form must be instantiated at most once. Compilation with 'static is intended to improve the performance of references within the linklet to defined and imported variables.\nIf 'quick is included in options, then linklet compilation may trade run-time performance for compile-time performance—that is, spend less time compiling the linklet, but the resulting linklet may run more slowly.\nIf 'use-prompt is included in options, then instantiating resulting linklet always wraps a prompt around each definition and immediate expression in the linklet. Otherwise, supplying #t as the use-prompt? argument to [instantiate-linklet](#%28def._%28%28lib._racket%2Flinklet..rkt%29._instantiate-linklet%29%29) may only wrap a prompt around the entire instantiation.\nIf 'unlimited-compile is included in options, then compilation never falls back to interpreted mode for an especially large linklet. See also [CS Compilation Modes](compiler.html#%28part._cs-compiler-modes%29)."} {"text": "# 14.12 Sandboxed Evaluation\nIf 'uninterned-literal is included in options, then literals in form will not necessarily be interned via [datum-intern-literal](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-intern-literal%29%29) when compiling or loading the linklet. Disabling the use of [datum-intern-literal](stxops.html#%28def._%28%28quote._~23~25kernel%29._datum-intern-literal%29%29) can be especially useful of the linklet includes a large string or byte string constant that is not meant to be shared.\nThe symbols in options must be distinct, otherwise [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nChanged in version 7.1.0.8 of package base: Added the 'use-prompt option. \nChanged in version 7.1.0.10: Added the 'uninterned-literal option. \nChanged in version 7.5.0.14: Added the 'quick option. \nChanged in version 8.11.1.2: Changed info to a hash. \nChanged in version 8.13.0.9: Added the 'unlimited-compile option.\n> ```\n(recompile-linklet linklet\n   [ info        \n    import-keys        \n    get-import        \n    options)   →   linklet?\n  linklet : linklet?\n  info : (or/c hash? any/c) = #f\n  import-keys : #f = #f\n  get-import : #f = #f\n   options   :   ( listof ( or/c ' serializable ' unsafe ' static ' quick\n> ' use-prompt ' uninterned-literal ) )\n      =   '(serializable)\n(recompile-linklet   linklet        \n    info        \n    import-keys        \n   [ get-import        \n    options)   →   linklet?   vector?"} {"text": "# 14.12 Sandboxed Evaluation\n  linklet : linklet?\n  info : (or/c hash? any/c)\n  import-keys : vector?\n   get-import   :   ( or/c ( any/c . → . ( values ( or/c linklet? #f )\n> ( or/c vector? #f ) ) )\n> #f )\n      =   (lambda (import-key) (values #f #f))\n   options   :   ( listof ( or/c ' serializable ' unsafe ' static ' quick\n> ' use-prompt ' uninterned-literal ) )\n      =   '(serializable)\n```\nLike compile-linklet, but takes an already-compiled linklet and potentially optimizes it further.\n\nChanged in version 7.1.0.6 of package base: Added the options argument. \nChanged in version 7.1.0.8: Added the 'use-prompt option. \nChanged in version 7.1.0.10: Added the 'uninterned-literal option. \nChanged in version 7.5.0.14: Added the 'quick option. \nChanged in version 8.11.1.2: Changed info to a hash.\n\n> ```\n(eval-linklet linklet)  →  linklet?\n  linklet : linklet?```\n\n\nReturns a variant of a linklet that is prepared for JIT compilation such that every later use of the result linklet with [instantiate-linklet](#%28def._%28%28lib._racket%2Flinklet..rkt%29._instantiate-linklet%29%29) shares the JIT-generated code. However, the result of [eval-linklet](#%28def._%28%28lib._racket%2Flinklet..rkt%29._eval-linklet%29%29) cannot be marshaled to a byte stream as part of a [linklet bundle](#%28tech._linklet._bundle%29), and it cannot be used with [recompile-linklet](#%28def._%28%28lib._racket%2Flinklet..rkt%29._recompile-linklet%29%29).\n\n> ```\n(instantiate-linklet linklet\n    import-instances        \n   [ target-instance?        \n    use-prompt?)   →   instance?\n\n  linklet : linklet?\n  import-instances : (listof instance?)\n  target-instance? : #f = #f\n  use-prompt? : any/c = #t\n(instantiate-linklet   linklet        \n    import-instances        \n    target-instance        \n   [ use-prompt?)   →   any\n\n  linklet : linklet?\n  import-instances : (listof instance?)\n  target-instance : instance?\n  use-prompt? : any/c = #t\n```"} {"text": "# 14.12 Sandboxed Evaluation\n(parameter)\t→\t\n(-> listof (listof symbol?))```\nReturns a description of a linklet’s imports. Each element of the result list corresponds to an import set as satisfied by a single instance on instantiation, and each member of the set is a variable name that is used from the corresponding imported instance.\n> ```\n(parameter)\t→\t\n(-> listof symbol?)\n```\n\n\nReturns a description of a linklet’s exports. Each element of the list corresponds to a variable that is made available by the linklet in its instance.\n\n> ```\n(linklet-add-target-machine-info   linklet        \n    from-linklet)   →   linklet?\n\n  linklet : linklet?\n  from-linklet : (or linklet? hash?)\n```"} {"text": "# 14.12 Sandboxed Evaluation\nWhen [compile-linklet](#%28def._%28%28lib._racket%2Flinklet..rkt%29._compile-linklet%29%29) or [recompile-linklet](#%28def._%28%28lib._racket%2Flinklet..rkt%29._recompile-linklet%29%29) requests a linklet via get-import for cross-module information, the linklet is expected to have information compatible with the current compilation target as determined by [current-compile-target-machine](eval.html#%28def._%28%28quote._~23~25kernel%29._current-compile-target-machine%29%29). To simplify the management of linklets to both run and use for cross-compilation, a linklet implementation may support information for multiple target machines within a linklet, in which case [linklet-add-target-machine-info](#%28def._%28%28lib._racket%2Flinklet..rkt%29._linklet-add-target-machine-info%29%29) returns a linklet like linklet but with target-specific information added from from-linklet. The two linklets must be from compatible sources, but [linklet-add-target-machine-info](#%28def._%28%28lib._racket%2Flinklet..rkt%29._linklet-add-target-machine-info%29%29) might perform only a sanity check for compatibility.\nThe from-linklet can be a linklet or a summary of a linklet’s information as produced by [linklet-summarize-target-machine-info](#%28def._%28%28lib._racket%2Flinklet..rkt%29._linklet-summarize-target-machine-info%29%29).\nAdded in version 8.12.0.3 of package base. \nChanged in version 8.17.0.3: Added support for from-linklet as a summary.\n> ```\n(linklet-summarize-target-machine-info from-linklet)  →  hash?\n  from-linklet : linklet?"} {"text": "# 14.12 Sandboxed Evaluation\n```\nReturns a value that has the same information as from-linklet for linklet-add-target-machine-info, but in a form that can be portably serialized via racket/fasl.\n\nAdded in version 8.17.0.3 of package base.\n\n> ```\n(linklet-directory? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a [linklet directory](#%28tech._linklet._directory%29), #f otherwise.\n\n> ```\n(hash → linklet-directory content)  →  linklet-directory?\n  content : (and/c hash? hash-eq? immutable? (not/c impersonator?))\n```\nConstructs a linklet directory given mappings in the form of a hash table. Each key of content must be either a symbol or #f, each symbol must be mapped to a linklet directory, and #f must be mapped to a linklet bundle or not mapped.\n> ```\n(linklet-directory → hash linklet-directory)\n  →  (and/c hash? hash-eq? immutable? (not/c impersonator?))\n  linklet-directory : linklet-directory?```\nExtracts the content of a [linklet directory](#%28tech._linklet._directory%29) into a [hash table](hashtables.html#%28tech._hash._table%29).\n> ```\n(linklet-bundle? v)  →  boolean?\n  v : any/c"} {"text": "# 14.12 Sandboxed Evaluation\n```\nReturns #t if v is a linklet bundle, #f otherwise.\n\n> ```\n(hash → linklet-bundle content)  →  linklet-bundle?\n  content : (and/c hash? hash-eq? immutable? (not/c impersonator?))```\n\n\nConstructs a [linklet bundle](#%28tech._linklet._bundle%29) given mappings in the form of a [hash table](hashtables.html#%28tech._hash._table%29). Each key of content must be either a symbol or a [fixnum](numbers.html#%28tech._fixnum%29). Values in the hash table are unconstrained, but the intent is that they are all [linklets](#%28tech._linklet%29) or values that can be recovered from [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29) output by [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29).\n\n> ```\n(linklet-bundle → hash linklet-bundle)\n  →  (and/c hash? hash-eq? immutable? (not/c impersonator?))\n  linklet-bundle : linklet-bundle?\n```\n(parameter)\t→```\nReturn #t if sym is a primitive name or other identifier that is not allowed as a binding within a linklet, #f otherwise.\nAdded in version 8.2.0.1 of package base.\n> ```\n(instance? v)  →  boolean?\n  v : any/c"} {"text": "# 14.12 Sandboxed Evaluation\n```\n(parameter)\t→\t\n(-> or/c #f 'constant 'consistent)```\n\n\nConstructs a [linklet instance](#%28tech._linklet._instance%29) directly. Besides associating an arbitrary name and data value to the instance, the instance is populated with variables as specified by variable-name and variable-value.\n\nThe optional data and mode arguments must be provided if any variable-name and variable-value arguments are provided. The mode argument is used as in [instance-set-variable-value!](#%28def._%28%28lib._racket%2Flinklet..rkt%29._instance-set-variable-value%21%29%29) for every variable-name.\n\n> ```\n(instance-name instance)  →  any/c\n  instance : instance?\n```\nReturns the value associated to instance as its name—either the first value provided to make-instance or the name of a linklet that was instantiated to create the instance.\n> ```\n(instance-data instance)  →  any/c\n  instance : instance?```\nReturns the value associated to instance as its data—either the second value provided to [make-instance](#%28def._%28%28lib._racket%2Flinklet..rkt%29._make-instance%29%29) or the default #f.\n> ```\n(parameter)\t→\t\n(-> list symbol?)\n```\n(parameter)\t→\t\n(-> lambda () (error ....))```\n\n\nReturns the value of the variable exported as name from instance. If no such variable is exported, then fail-k is used in the same way as by [hash-ref](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-ref%29%29).\n\n> ```\n(parameter)\t→\t\n(-> or/c #f 'constant 'consistent)\n```\n(parameter)\t→```"} {"text": "# 14.12 Sandboxed Evaluation\nChanges instance so that it does not export a variable as name, as long as name does not exist as a constant variable. If a variable for name exists as constant, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n> ```\n(parameter)\t→\n```\n(parameter)\t→\t\n(-> if ref-site? (or/c instance? #f symbol?) instance?)```\n\n\nExtracts the instance where the variable of varref is defined if ref-site? is #f, and returns the instance where varref itself resides if ref-site? is true. This notion of [variable reference](Locations____variable-reference.html#%28tech._variable._reference%29) is the same as at the module level and can reflect the linklet instance that implements a particular phase of a module instance.\n\nWhen ref-site? is #f, the result is #f when varref is from ([#%variable-reference](Locations____variable-reference.html#%28form._%28%28quote._~23~25kernel%29._~23~25variable-reference%29%29)) with no identifier. The result is a symbol if varref refers to a primitive.\n\n> ```\n(correlated? v) → boolean?\n  v : any/c\n\n(correlated-source crlt)  →  any\n  crlt : correlated?\n\n(correlated-line crlt)  →  (or/c exact-positive-integer? #f)\n  crlt : correlated?\n\n(correlated-column crlt)  →  (or/c exact-nonnegative-integer? #f)\n  crlt : correlated?\n\n(correlated-position crlt)  →  (or/c exact-positive-integer? #f)\n  crlt : correlated?\n\n(correlated-span crlt)  →  (or/c exact-nonnegative-integer? #f)\n  crlt : correlated?\n\n(correlated-e crlt)  →  any\n  crlt : correlated?\n\n(correlated → datum crlt)  →  any\n  crlt : (or/c correlated? any/c)\n\n(datum → correlated v [srcloc prop)  →  correlated?\n  v : any/c\n   srcloc   :   ( or/c correlated? #f\n> ( list/c any/c\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f ) )\n> ( vector/c any/c\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f )\n> ( or/c exact-positive-integer? #f )\n> ( or/c exact-nonnegative-integer? #f ) ) )\n      =   #f\n\n  prop : (or/c correlated? #f) = #f\n\n(correlated-property crlt key val)  →  correlated?\n  crlt : correlated?\n  key : any/c\n  val : any/c\n(correlated-property crlt key)  →  any/c\n  crlt : correlated?\n  key : any/c\n\n(correlated-property-symbol-keys crlt)  →  list?\n  crlt : correlated?\n```"} {"text": "# 14.12 Sandboxed Evaluation\nLike syntax?, syntax-source, syntax-line, syntax-column, syntax-position, syntax-span, syntax-e, syntax → datum, datum → syntax, syntax-property, and syntax-property-symbol-keys, but for correlated objects.\nUnlike datum → syntax, datum → correlated does not recur through the given S-expression and convert pieces to correlated objects. Instead, a correlated object is simply wrapped around the immediate value. In contrast, correlated → datum recurs through its argument (which is not necessarily a correlated object) to discover any correlated objects and convert them to plain S-expressions.\nChanged in version 7.6.0.6 of package base: Added the prop argument to datum → correlated.\n------------------------------------------------------------------------"} {"text": "# 14.15 Deprecation"} {"text": "### 14.15 Deprecation\n| | |\n|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require [racket/deprecation]()) |  package: base |\nThe bindings documented in this section are provided by the [racket/deprecation]() library, not racket/base or racket.\nA deprecated function, macro, or other API element is one that’s been formally declared obsolete, typically with an intended replacement that users should migrate to. The [racket/deprecation]() library provides a standardized mechanism for declaring deprecations in a machine-processable manner. These declarations can allow tools such as resyntax to automate migrating code away from deprecated APIs. Note that a dependency on the [racket/deprecation]() library does not imply a dependency on any such tools."} {"text": "#### 14.15.1 Deprecated Aliases\n>
\n

syntax

\n

(define-deprecated-alias alias-id target-id)

\nBinds alias-id as an alias of target-id with the intent that users of alias-id should prefer to use target-id instead. The given alias-id is bound as a deprecated alias transformer, which is a kind of rename transformer. The given target-id may be bound to a function, macro, or any other kind of binding.\nNote that although alias-id is an alias of target-id, it is not considered the same binding as target-id and is not free-identifier=?. This is because the alias binding must be inspectable at compile-time with deprecated-alias? and deprecated-alias-target, and it must remain inspectable even if the alias is provided by a module. This requires a module providing the alias and the target to provide them as two distinct bindings: one which is bound to a deprecated alias transformer and one which isn’t.\nExamples:\n> ```racket\n> > ( require racket/deprecation )\n> > ( define a 42 )\n> > ( define-deprecated-alias legacy-a a )\n> > legacy-a\n> 42\n> ```"} {"text": "#### 14.15.2 Deprecated Alias Transformers\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require racket/deprecation/transformer) |  package: base |\nThe racket/deprecation/transformer module provides compile-time supporting code for the [racket/deprecation]() library, primarily for use in tools that wish to reflect on deprecated code.\nA deprecated alias transformer is a kind of rename transformer which signals that the transformer binding is a deprecated alias of the target identifier. This signal is intended for consumption in tools such as editors (which may wish to display a warning when deprecated aliases are used) and automated refactoring systems (which may wish to replace deprecated aliases with their target identifiers automatically).\n> ```\n(deprecated-alias? v) → boolean?\n  v : any/c```"} {"text": "# 14.15 Deprecation\nReturns true if v is a [deprecated alias transformer](#%28tech._deprecated._alias._transformer%29) and returns false otherwise. Implies [rename-transformer?](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._rename-transformer~3f%29%29). To determine if an identifier is bound to a deprecated alias transformer, use [syntax-local-value/immediate](stxtrans.html#%28def._%28%28quote._~23~25kernel%29._syntax-local-value%2Fimmediate%29%29) and then use [deprecated-alias?](#%28def._%28%28lib._racket%2Fdeprecation%2Ftransformer..rkt%29._deprecated-alias~3f%29%29) on the transformer value.\nExamples:\n> ```racket\n> > ( require ( for-syntax racket/base racket/deprecation/transformer ) racket/deprecation syntax/parse/define )\n> > ( define-syntax-parse-rule ( is-deprecated? id:id ) #:do [ ( define-values ( transformer _ ) ( syntax-local-value/immediate #' id ( λ ( ) ( values #false #false ) ) ) ) ] #:with result ( deprecated-alias? transformer ) ' result )\n> > ( define-deprecated-alias bad-list list )\n> > ( is-deprecated? list )\n> #f\n> > ( is-deprecated? bad-list )\n> #t\n> ```\n> ```\n(deprecated-alias target)  →  deprecated-alias?\n  target : identifier?"} {"text": "# 14.15 Deprecation\n```\nConstructs a deprecated alias transformer which expands to target when used. The returned alias is a rename transformer and is thus suitable for use with define-syntax. When expanding, the usage of target is annotated with the 'not-free-identifier=? syntax property to ensure that the alias and the target are treated as distinct bindings, even when provided by a module.\n\nThis constructor is not intended for direct use by users who just want to declare a deprecated alias. Such users should prefer the define-deprecated-alias form instead.\n\n> ```\n(deprecated-alias-target alias) → identifier?\n  alias : deprecated-alias?```\n\n\nReturns the target identifier that alias expands to.\n\n------------------------------------------------------------------------\n\n# 15 Operating System\n\n## 15 Operating System\n\n| |\n|----------------------------------------------------------------------------------------------------------------------------------|\n|     [15.1 Paths](pathutils.html) |\n|       [15.1.1 Manipulating Paths](Manipulating_Paths.html) |\n|       [15.1.2 More Path Utilities](More_Path_Utilities.html) |\n|       [15.1.3 Unix and Mac OS Paths](unixpaths.html) |\n|         [15.1.3.1 Unix Path Representation](unixpaths.html#%28part._unixpathrep%29) |\n|       [15.1.4 Windows Paths](windowspaths.html) |\n|         [15.1.4.1 Windows Path Representation](windowspaths.html#%28part._windowspathrep%29) |\n|     [15.2 Filesystem](Filesystem.html) |\n|       [15.2.1 Locating Paths](Filesystem.html#%28part._findpaths%29) |\n|       [15.2.2 Files](Filesystem.html#%28part._fileutils%29) |\n|       [15.2.3 Directories](Filesystem.html#%28part._directories%29) |\n|       [15.2.4 Detecting Filesystem Changes](Filesystem.html#%28part._filesystem-change%29) |\n|       [15.2.5 Declaring Paths Needed at Run Time](Filesystem.html#%28part._runtime-path%29) |\n|       [15.2.6 More File and Directory Utilities](Filesystem.html#%28part._file-lib%29) |\n|     [15.3 Networking](networking.html) |\n|       [15.3.1 TCP](tcp.html) |\n|       [15.3.2 UDP](udp.html) |\n|     [15.4 Processes](subprocess.html) |\n|       [15.4.1 Simple Subprocesses](subprocess.html#%28part._.Simple_.Subprocesses%29) |\n|     [15.5 Logging](logging.html) |\n|       [15.5.1 Creating Loggers](logging.html#%28part._.Creating_.Loggers%29) |\n|       [15.5.2 Logging Events](logging.html#%28part._.Logging_.Events%29) |\n|       [15.5.3 Receiving Logged Events](logging.html#%28part._receiving-logged-events%29) |\n|       [15.5.4 Additional Logging Functions](logging.html#%28part._.Additional_.Logging_.Functions%29) |\n|     [15.6 Time](time.html) |\n|       [15.6.1 Date Utilities](time.html#%28part._date-string%29) |\n|     [15.7 Environment Variables](envvars.html) |\n|     [15.8 Environment and Runtime Information](runtime.html) |\n|     [15.9 Command-Line Parsing](Command-Line_Parsing.html) |\n|     [15.10 Additional Operating System Functions](os-lib.html) |\n\n------------------------------------------------------------------------\n\n# 15.1 Paths\n\n### 15.1 Paths\n\nWhen a Racket procedure takes a filesystem path as an argument, the path can be provided either as a string or as an instance of the path datatype. If a string is provided, it is converted to a path using [string->path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._string-~3epath%29%29). Beware that some paths may not be representable as strings; see [Unix Path Representation](unixpaths.html#%28part._unixpathrep%29) and [Windows Path Representation](windowspaths.html#%28part._windowspathrep%29) for more information. A Racket procedure that generates a filesystem path always generates a [path](#%28tech._path%29) value.\n\nBy default, paths are created and manipulated for the current platform, but procedures that merely manipulate paths (without using the filesystem) can manipulate paths using conventions for other supported platforms. The [bytes->path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._bytes-~3epath%29%29) procedure accepts an optional argument that indicates the platform for the path, either 'unix or 'windows. For other functions, such as [build-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._build-path%29%29) or [simplify-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._simplify-path%29%29), the behavior is sensitive to the kind of path that is supplied. Unless otherwise specified, a procedure that requires a path accepts only paths for the current platform.\n\nTwo [path](#%28tech._path%29) values are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29) when they use the same convention type and when their byte-string representations are [equal?](Equality.html#%28def._%28%28quote._~23~25kernel%29._equal~3f%29%29). A path string (or byte string) cannot be empty, and it cannot contain a nul character or byte. When an empty string or a string containing nul is provided as a path to any procedure except [absolute-path?](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._absolute-path~3f%29%29), [relative-path?](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._relative-path~3f%29%29), or [complete-path?](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._complete-path~3f%29%29), the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nMost Racket primitives that accept paths first cleanse the path before using it. Procedures that build paths or merely check the form of a path do not cleanse paths, with the exceptions of [cleanse-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._cleanse-path%29%29), [expand-user-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._expand-user-path%29%29), and [simplify-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._simplify-path%29%29). For more information about path cleansing and other platform-specific details, see [Unix and Mac OS Paths](unixpaths.html) and [Windows Paths](windowspaths.html).\n\n------------------------------------------------------------------------\n\n# 15.1.1 Manipulating Paths\n\n#### 15.1.1 Manipulating Paths\n\n> ```\n(path? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 14.15 Deprecation\nReturns #t if v is a path value for the current platform (not a string, and not a path for a different platform), #f otherwise.\n> ```\n(path-string? v)  →  boolean?\n  v : any/c\n```\n\n\nReturns #t if v is either a path or string: either a path for the current platform or a non-empty string without nul characters. Returns #f otherwise.\n\n> ```\n(path-for-some-system? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a path value for some platform (not a string), #f otherwise.\n> ```\n(string → path str)  →  path?\n  str : string?\n```\n\n\nProduces a path whose byte-string encoding is ([string->bytes/locale](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._string-~3ebytes%2Flocale%29%29) str ([char->integer](characters.html#%28def._%28%28quote._~23~25kernel%29._char-~3einteger%29%29) #\\\\?)) on Unix and Mac OS or ([string->bytes/utf-8](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._string-~3ebytes%2Futf-8%29%29) str) on Windows.\n\nBeware that the current locale might not encode every string, in which case [string->path](#%28def._%28%28quote._~23~25kernel%29._string-~3epath%29%29) can produce the same path for different strs. See also [string->path-element](#%28def._%28%28quote._~23~25kernel%29._string-~3epath-element%29%29), which should be used instead of [string->path](#%28def._%28%28quote._~23~25kernel%29._string-~3epath%29%29) when a string represents a single [path element](More_Path_Utilities.html#%28tech._path._element%29). For information on how strings and byte strings encode paths, see [Unix Path Representation](unixpaths.html#%28part._unixpathrep%29) and [Windows Path Representation](windowspaths.html#%28part._windowspathrep%29).\n\nSee also [string->some-system-path](More_Path_Utilities.html#%28def._%28%28lib._racket%2Fpath..rkt%29._string-~3esome-system-path%29%29), and see [Unix Path Representation](unixpaths.html#%28part._unixpathrep%29) and [Windows Path Representation](windowspaths.html#%28part._windowspathrep%29) for information on how strings encode paths.\n\nChanged in version 6.1.1.1 of package base: Changed Windows conversion to always use UTF-8.\n\n> ```\n(bytes → path bstr [type) → path?\n  bstr : bytes?\n  type : (or/c 'unix 'windows) = (system-path-convention-type)\n```"} {"text": "# 14.15 Deprecation\nProduces a path (for some platform) whose byte-string encoding is bstr, where bstr must not contain a nul byte. The optional type specifies the convention to use for the path.\nFor converting relative path elements from literals, use instead bytes → path-element, which applies a suitable encoding for individual elements.\nFor information on how byte strings encode paths, see Unix Path Representation and Windows Path Representation.\n> ```\n(path → string path)  →  string?\n  path : path?```\nProduces a string that represents path by decoding path’s byte-string encoding using the current locale on Unix and Mac OS and by using UTF-8 on Windows. In the former case, ? is used in the result string where encoding fails, and if the encoding result is the empty string, then the result is \"?\".\nThe resulting string is suitable for displaying to a user, string-ordering comparisons, etc., but it is not suitable for re-creating a path (possibly modified) via [string->path](#%28def._%28%28quote._~23~25kernel%29._string-~3epath%29%29), since decoding and re-encoding the path’s byte string may lose information.\nFurthermore, for display and sorting based on individual [path elements](More_Path_Utilities.html#%28tech._path._element%29) (such as pathless file names), use [path-element->string](#%28def._%28%28quote._~23~25kernel%29._path-element-~3estring%29%29), instead, to avoid special encodings use to represent some relative paths. See [Windows Paths](windowspaths.html) for specific information about the conversion of Windows paths."} {"text": "# 14.15 Deprecation\nSee also [some-system-path->string](More_Path_Utilities.html#%28def._%28%28lib._racket%2Fpath..rkt%29._some-system-path-~3estring%29%29).\nChanged in version 6.1.1.1 of package base: Changed Windows conversion to always use UTF-8.\n> ```\n(path → bytes path)  →  bytes?\n  path : path-for-some-system?\n```\nProduces path’s byte-string representation. No information is lost in this translation, so that (bytes → path (path → bytes path) (path-convention-type path)) always produces a path that is equal? to path. The path argument can be a path for any platform.\n\nConversion to and from byte values is useful for marshaling and unmarshaling paths, but manipulating the byte form of a path is generally a mistake. In particular, the byte string may start with a \\\\\\\\?\\\\REL encoding for Windows paths. Instead of path → bytes, use split-path and path-element → bytes to manipulate individual path elements.\n\nFor information on how byte strings encode paths, see Unix Path Representation and Windows Path Representation.\n\n> ```\n(string → path-element str\n   [ false-on-non-element?)  \n\n  →  (or/c (and/c path? path-element?) #f)\n  str : string?\n  false-on-non-element? : any/c = #f```\n\n\nLike [string->path](#%28def._%28%28quote._~23~25kernel%29._string-~3epath%29%29), except that str corresponds to a single relative element in a path, and it is encoded as necessary to convert it to a path. See [Unix and Mac OS Paths](unixpaths.html) and [Windows Paths](windowspaths.html) for more information on the conversion of paths.\n\nIf str does not correspond to any [path element](More_Path_Utilities.html#%28tech._path._element%29) (e.g., it is an absolute path, or it can be split), or if it corresponds to an up-directory or same-directory indicator on Unix and Mac OS, then either #f is returned or [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. A #f is returned only when false-on-non-element? is true.\n\nLike [path->string](#%28def._%28%28quote._~23~25kernel%29._path-~3estring%29%29), information can be lost from str in the locale-specific conversion to a path.\n\nChanged in version 8.1.0.6 of package base: Added the false-on-non-element? argument.\n\n> ```\n(bytes → path-element bstr\n   [ type  \n    false-on-non-element?)  \n\n  →  (or/c path-element? #f)\n  bstr : bytes?\n  type : (or/c 'unix 'windows) = (system-path-convention-type)\n  false-on-non-element? : any/c = #f\n```"} {"text": "# 14.15 Deprecation\nLike bytes → path, except that bstr corresponds to a single relative element in a path. In terms of conversions, restrictions on bstr, and the treatment of false-on-non-element?, bytes → path-element is like string → path-element.\nThe bytes → path-element procedure is generally the best choice for reconstructing a path based on another path (where the other path is deconstructed with split-path and path-element → bytes) when ASCII-level manipulation of path elements is necessary.\nChanged in version 8.1.0.6 of package base: Added the false-on-non-element? argument.\n> ```\n(path-element → string path)  →  string?\n  path : path-element?```\nLike [path->string](#%28def._%28%28quote._~23~25kernel%29._path-~3estring%29%29), except that trailing path separators are removed (as by [split-path](#%28def._%28%28quote._~23~25kernel%29._split-path%29%29)). On Windows, any \\\\\\\\?\\\\REL encoding prefix is also removed; see [Windows Paths](windowspaths.html) for more information.\nThe path argument must be such that [split-path](#%28def._%28%28quote._~23~25kernel%29._split-path%29%29) applied to path would return 'relative as its first result and a path as its second result, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nThe [path-element->string](#%28def._%28%28quote._~23~25kernel%29._path-element-~3estring%29%29) procedure is generally the best choice for presenting a pathless file or directory name to a user.\n> ```"} {"text": "# 14.15 Deprecation\n(path-element → bytes path)  →  bytes?\n  path : path-element?\n```\nLike path → bytes, except that any encoding prefix is removed, etc., as for path-element → string.\n\nFor any reasonable locale, consecutive ASCII characters in the printed form of path are mapped to consecutive byte values that match each character’s code-point value, and a leading or trailing ASCII character is mapped to a leading or trailing byte, respectively. The path argument can be a path for any platform.\n\nThe path-element → bytes procedure is generally the right choice (in combination with split-path) for extracting the content of a path to manipulate it at the ASCII level (then reassembling the result with bytes → path-element and build-path).\n\n>
\n\n

procedure

\n\n

(path

  a-path : path?
  b-path : path?
\n\nReturns #t if the arguments are sorted, where the comparison for each pair of paths is the same as using path → bytes and bytes ```\n(path-convention-type path) → (or/c 'unix 'windows)\n  path : path-for-some-system?```\n\n\nAccepts a path value (not a string) and returns its convention type.\n\n> ```\n(system-path-convention-type)  →  (or/c 'unix 'windows)\n```"} {"text": "# 14.15 Deprecation\nReturns the path convention type of the current platform: 'unix for Unix and Mac OS, 'windows for Windows.\n> ```\n(build-path base sub ...) → path-for-some-system?\n  base : (or/c path-string? path-for-some-system? 'up 'same)\n   sub   :   ( or/c ( and/c ( or/c path-string? path-for-some-system? )\n> ( not/c complete-path? ) )\n> ( or/c ' up ' same ) )```\nCreates a path given a base path and any number of sub-path extensions. If base is an absolute path, the result is an absolute path, otherwise the result is a relative path.\nThe base and each sub must be either a relative path, the symbol 'up (indicating the relative parent directory), or the symbol 'same (indicating the relative current directory). For Windows paths, if base is a drive specification (with or without a trailing slash) the first sub can be an absolute (driveless) path. For all platforms, the last sub can be a filename.\nThe base and sub arguments can be paths for any platform. The platform for the resulting path is inferred from the base and sub arguments, where string arguments imply a path for the current platform. If different arguments are for different platforms, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. If no argument implies a platform (i.e., all are 'up or 'same), the generated path is for the current platform.\nEach sub and base can optionally end in a directory separator. If the last sub ends in a separator, it is included in the resulting path."} {"text": "# 14.15 Deprecation\nIf base or sub is an illegal path string (because it is empty or contains a nul character), the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nThe [build-path](#%28def._%28%28quote._~23~25kernel%29._build-path%29%29) procedure builds a path without checking the validity of the path or accessing the filesystem.\nSee [Unix and Mac OS Paths](unixpaths.html) and [Windows Paths](windowspaths.html) for more information on the construction of paths.\nThe following examples assume that the current directory is \"/home/joeuser\" for Unix examples and \"C:\\\\Joe’s Files\" for Windows examples.\n> ```racket\n> ( define p1 ( build-path ( current-directory ) \"src\" \"racket\" ) )\n> ; Unix: p1 is \"/home/joeuser/src/racket\"\n> ; Windows: p1 is \"C:\\\\Joe's Files\\\\src\\\\racket\"\n> ( define p2 ( build-path ' up ' up \"docs\" \"Racket\" ) )\n> ; Unix: p2 is \"../../docs/Racket\"\n> ; Windows: p2 is \"..\\\\..\\\\docs\\\\Racket\"\n> ( build-path p2 p1 )\n> ; Unix and Windows: raises exn:fail:contract ; p1 is absolute\n> ( build-path p1 p2 )\n> ; Unix: is \"/home/joeuser/src/racket/../../docs/Racket\"\n> ; Windows: is \"C:\\\\Joe's Files\\\\src\\\\racket\\\\..\\\\..\\\\docs\\\\Racket\"\n> ```\n> ```\n(build-path/convention-type type\n    base        \n    sub ...)   →   path-for-some-system?\n  type : (or/c 'unix 'windows)\n  base : (or/c path-string? path-for-some-system? 'up 'same)\n   sub   :   ( or/c ( and/c ( or/c path-string? path-for-some-system? )\n> ( not/c complete-path? ) )\n> ( or/c ' up ' same ) )"} {"text": "# 14.15 Deprecation\n```\nLike build-path, except a path convention type is specified explicitly.\n\nNote that, just as with build-path, any string arguments for either base or sub will be implicitly converted into a path for the current platform before being combined with the others. For this reason, you cannot use this function to build paths from strings for any platform other than the current one; in such attempts, type does not match the inferred convention type for the strings and an exn:fail:contract exception is raised. (To create paths for foreign platforms, see bytes → path.)\n\nThe usefulness of build-path/convention-type over build-path is limited to cases where the sub-paths contain 'same or 'up elements.\n\n> ```\n(absolute-path? path)  →  boolean?\n  path : (or/c path? string? path-for-some-system?)```\n\n\nReturns #t if path is an absolute path, #f otherwise. The path argument can be a path for any platform. If path is not a legal path string (e.g., it contains a nul character), #f is returned. This procedure does not access the filesystem.\n\n> ```\n(relative-path? path)  →  boolean?\n  path : (or/c path? string? path-for-some-system?)\n```\nReturns #t if path is a relative path, #f otherwise. The path argument can be a path for any platform. If path is not a legal path string (e.g., it contains a nul character), #f is returned. This procedure does not access the filesystem.\n> ```\n(complete-path? path)  →  boolean?\n  path : (or/c path? string? path-for-some-system?)```"} {"text": "# 14.15 Deprecation\nReturns #t if path is a completely determined path (not relative to a directory or drive), #f otherwise. The path argument can be a path for any platform. Note that for Windows paths, an absolute path can omit the drive specification, in which case the path is neither relative nor complete. If path is not a legal path string (e.g., it contains a nul character), #f is returned.\nThis procedure does not access the filesystem.\n> ```\n(current-directory)\t→\t\n(-> or/c path-string? path-for-some-system?)\n```\nReturns path as a complete path. If path is already a complete path, it is returned as the result. Otherwise, path is resolved with respect to the complete path base. If base is not a complete path, the exn:fail:contract exception is raised.\n\nThe path and base arguments can be paths for any platform; if they are for different platforms, the exn:fail:contract exception is raised.\n\nThis procedure does not access the filesystem.\n\n> ```\n(path → directory-path path)  →  path-for-some-system?\n  path : (or/c path-string? path-for-some-system?)```\n\n\nReturns path if path syntactically refers to a directory and ends in a separator, otherwise it returns an extended version of path that specifies a directory and ends with a separator. For example, on Unix and Mac OS, the path \"x/y/\" syntactically refers to a directory and ends in a separator, but \"x/y\" would be extended to \"x/y/\", and \"x/..\" would be extended to \"x/../\". The path argument can be a path for any platform, and the result will be for the same platform.\n\nThis procedure does not access the filesystem.\n\n> ```\n(resolve-path path)  →  path?\n  path : path-string?\n```"} {"text": "# 14.15 Deprecation\nCleanses path and returns a path that references the same file or directory as path. If path is a soft link to another path, then the referenced path is returned (this may be a relative path with respect to the directory owning path), otherwise path is returned (after cleansing).\nOn Windows, the path for a link should be simplified syntactically, so that an up-directory indicator removes a preceding path element independent of whether the preceding element itself refers to a link. For relative-paths links, the path should be parsed specially; see Windows Paths for more information.\nChanged in version 6.0.1.12 of package base: Added support for links on Windows.\n> ```\n(cleanse-path path)  →  path-for-some-system?\n  path : (or/c path-string? path-for-some-system?)```\n[Cleanse](pathutils.html#%28tech._cleanse%29)s path (as described at the beginning of this chapter) without consulting the filesystem.\nExample:\n> ```racket\n> > ( let ( [ p ( string->some-system-path \"tiny//dancer\" ' unix ) ] ) ( cleanse-path p ) )\n> #\n> ```\n> ```\n(expand-user-path path)  →  path?\n  path : path-string?"} {"text": "# 14.15 Deprecation\n```\nCleanses path. In addition, on Unix and Mac OS, a leading \\~ is treated as user’s home directory and expanded; the username follows the \\~ (before a / or the end of the path), where \\~ by itself indicates the home directory of the current user.\n\n> ```\n(simplify-path path [use-filesystem?) → path-for-some-system?\n  path : (or/c path-string? path-for-some-system?)\n  use-filesystem? : boolean? = #t```\n\n\nEliminates redundant path separators (except for a single trailing separator), up-directory .., and same-directory . indicators in path, and changes / separators to \\\\ separators in Windows paths, such that the result accesses the same file or directory (if it exists) as path.\n\nIn general, the pathname is normalized as much as possible—without consulting the filesystem if use-filesystem? is #f, and (on Windows) without changing the case of letters within the path. If path syntactically refers to a directory, the result ends with a directory separator.\n\nWhen path is simplified other than just converting slashes to backslashes and use-filesystem? is true (the default), a complete path is returned. If path is relative, it is resolved with respect to the current directory. On Unix and Mac OS, up-directory indicators are removed taking into account soft links (so that the resulting path refers to the same directory as before); on Windows, up-directory indicators are removed by deleting a preceding [path element](More_Path_Utilities.html#%28tech._path._element%29).\n\nWhen use-filesystem? is #f, up-directory indicators are removed by deleting a preceding [path element](More_Path_Utilities.html#%28tech._path._element%29), and the result can be a relative path with up-directory indicators remaining at the beginning of the path; up-directory indicators are dropped when they refer to the parent of a root directory. Similarly, the result can be the same as ([build-path](#%28def._%28%28quote._~23~25kernel%29._build-path%29%29) 'same) (but with a trailing separator) if eliminating up-directory indicators leaves only same-directory indicators.\n\nThe path argument can be a path for any platform when use-filesystem? is #f, and the resulting path is for the same platform.\n\nThe filesystem might be accessed when use-filesystem? is true, but the source or simplified path might be a non-existent path. If path cannot be simplified due to a cycle of links, the [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) exception is raised (but a successfully simplified path may still involve a cycle of links if the cycle did not inhibit the simplification).\n\nSee [Unix and Mac OS Paths](unixpaths.html) and [Windows Paths](windowspaths.html) for more information on simplifying paths.\n\nExample:\n\n> ```racket\n> > ( let ( [ p ( string->some-system-path \"tiny//in/my/head/../../../dancer\" ' unix ) ] ) ( simplify-path p #f ) )\n> #\n> ```\n\n> ```\n(normal-case-path path)  →  path-for-some-system?\n  path : (or/c path-string? path-for-some-system?)\n```"} {"text": "# 14.15 Deprecation\nReturns path with “normalized” case characters. For Unix and Mac OS paths, this procedure always returns the input path, because filesystems for these platforms can be case-sensitive. For Windows paths, if path does not start with \\\\\\\\?\\\\, the resulting string uses only lowercase letters, based on the current locale. In addition, for Windows paths when the path does not start with \\\\\\\\?\\\\, all /s are converted to \\\\s, and trailing spaces and .s are removed.\nThe path argument can be a path for any platform, but beware that local-sensitive decoding and conversion of the path may be different on the current platform than for the path’s platform.\nThis procedure does not access the filesystem.\n> ```\n(split-path path)   →   (or/c path-for-some-system? 'relative #f)\n(or/c path-for-some-system? 'up 'same)\nboolean?\n  path : (or/c path-string? path-for-some-system?)```\nDeconstructs path into a smaller path and an immediate directory or file name. Three values are returned:\n- base is either\n - a path,\n - 'relative if path is an immediate relative directory or filename, or\n - #f if path is a root directory.\n- \n name is either\n - a directory-name path,\n - a filename,\n - 'up if the last part of path specifies the parent directory of the preceding path (e.g., .. on Unix), or\n - 'same if the last part of path specifies the same directory as the preceding path (e.g., . on Unix)."} {"text": "# 14.15 Deprecation\n- must-be-dir? is #t if path explicitly specifies a directory (e.g., with a trailing separator), #f otherwise. Note that must-be-dir? does not specify whether name is actually a directory or not, but whether path syntactically specifies a directory.\nCompared to path, redundant separators (if any) are removed in the result base and name. If base is #f, then name cannot be 'up or 'same. The path argument can be a path for any platform, and resulting paths for the same platform.\nThis procedure does not access the filesystem.\nSee [Unix and Mac OS Paths](unixpaths.html) and [Windows Paths](windowspaths.html) for more information on splitting paths.\n> ```\n(explode-path path)\n  →  (listof (or/c path-for-some-system? 'up 'same))\n  path : (or/c path-string? path-for-some-system?)"} {"text": "# 14.15 Deprecation\n```\nReturns the list of path elements that constitute path. If path is simplified in the sense of simple-form-path, then the result is always a list of paths, and the first element of the list is a root.\n\nThe explode-path function computes its result in time proportional to the length of path (unlike a loop that uses split-path, which must allocate intermediate paths).\n\n> ```\n(path-replace-extension path ext)  →  path-for-some-system?\n  path : (or/c path-string? path-for-some-system?)\n  ext : (or/c string? bytes?)```\n\n\nReturns a path that is the same as path, except that the extension for the last element of the path (including the extension separator) is changed to ext. If the last element of path has no extension, then ext is added to the path.\n\nAn extension is defined as a . that is not at the start of the path element followed by any number of non-. characters/bytes at the end of the [path element](More_Path_Utilities.html#%28tech._path._element%29), as long as the path element is not a directory indicator like \"..\".\n\nThe path argument can be a path for any platform, and the result is for the same platform. If path represents a root, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. The given ext typically starts with ., but it is not required to start with an extension separator.\n\nExamples:\n\n> ```racket\n> > ( path-replace-extension \"x/y.ss\" #\".rkt\" )\n> #\n> > ( path-replace-extension \"x/y.ss\" #\"\" )\n> #\n> > ( path-replace-extension \"x/y\" #\".rkt\" )\n> #\n> > ( path-replace-extension \"x/y.tar.gz\" #\".rkt\" )\n> #\n> > ( path-replace-extension \"x/.racketrc\" #\".rkt\" )\n> #\n> ```\n\nAdded in version 6.5.0.3 of package base.\n\n> ```\n(path-add-extension path ext [sep) → path-for-some-system?\n  path : (or/c path-string? path-for-some-system?)\n  ext : (or/c string? bytes?)\n  sep : (or/c string? bytes?) = #\"_\"\n```"} {"text": "# 14.15 Deprecation\nSimilar to path-replace-extension, but any existing extension on path is preserved by replacing the . before the extension with sep, and then the ext is added to the end.\nExamples:\n> ```racket\n> > ( path-add-extension \"x/y.ss\" #\".rkt\" )\n> #\n> > ( path-add-extension \"x/y\" #\".rkt\" )\n> #\n> > ( path-add-extension \"x/y.tar.gz\" #\".rkt\" )\n> #\n> > ( path-add-extension \"x/y.tar.gz\" #\".rkt\" #\".\" )\n> #\n> > ( path-add-extension \"x/.racketrc\" #\".rkt\" )\n> #\n> ```\nAdded in version 6.5.0.3 of package base. \nChanged in version 6.8.0.2: Added the sep optional argument.\n> ```\n(path-replace-suffix path ext)  →  path-for-some-system?\n  path : (or/c path-string? path-for-some-system?)\n  ext : (or/c string? bytes?)```\n> NOTE: This function is deprecated; use [path-replace-extension](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._path-replace-extension%29%29), instead.\nLike [path-replace-extension](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._path-replace-extension%29%29), but treats a leading . in a path element as an extension separator.\n> ```\n(path-add-suffix path ext)  →  path-for-some-system?\n  path : (or/c path-string? path-for-some-system?)\n  ext : (or/c string? bytes?)"} {"text": "# 14.15 Deprecation\n```\n> NOTE: This function is deprecated; use path-add-extension, instead.\n\nLike path-add-extension, but treats a leading . in a path element as an extension separator.\n\n> ```\n(reroot-path path root-path)  →  path-for-some-system?\n  path : (or/c path-string? path-for-some-system?)\n  root-path : (or/c path-string? path-for-some-system?)```\n\n\nProduces a path that extends root-path based on the complete form of path.\n\nIf path is not already [complete](#%28tech._complete%29), is it completed via [path->complete-path](#%28def._%28%28quote._~23~25kernel%29._path-~3ecomplete-path%29%29), in which case path must be a path for the current platform. The path argument is also [cleanse](pathutils.html#%28tech._cleanse%29)d and case-normalized via [normal-case-path](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._normal-case-path%29%29). The path is then appended to root-path; in the case of Windows paths, a root letter drive becomes a letter path element, while a root UNC path is prefixed with \"UNC\" as a path element and the machine and volume names become path elements.\n\nExamples:\n\n> ```racket\n> > ( reroot-path ( bytes->path #\"/home/caprica/baltar\" ' unix ) ( bytes->path #\"/earth\" ' unix ) )\n> #\n> > ( reroot-path ( bytes->path #\"c:\\\\usr\\\\adama\" ' windows ) ( bytes->path #\"\\\\\\\\earth\\\\africa\\\\\" ' windows ) )\n> #\n> > ( reroot-path ( bytes->path #\"\\\\\\\\galactica\\\\cac\\\\adama\" ' windows ) ( bytes->path #\"s:\\\\earth\\\\africa\\\\\" ' windows ) )\n> #\n> ```\n\n------------------------------------------------------------------------\n\n# 15.1.2 More Path Utilities\n\n#### 15.1.2 More Path Utilities\n\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/path]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/path]() and [racket](index.html) libraries, but not [racket/base](index.html).\n\n> ```\n(file-name-from-path path)  →  (or/c path-for-some-system? #f)\n  path : (or/c path-string? path-for-some-system?)\n```"} {"text": "# 14.15 Deprecation\nReturns the last element of path. If path is syntactically a directory path (see split-path), then the result is #f.\n> ```\n(path-get-extension path)  →  (or/c bytes? #f)\n  path : (or/c path-string? path-for-some-system?)```\nReturns a byte string that is the extension part of the filename in path, including the . separator. If the path has no extension, #f is returned.\nSee [path-replace-extension](Manipulating_Paths.html#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._path-replace-extension%29%29) for the definition of a filename extension.\nExamples:\n> ```racket\n> > ( path-get-extension \"x/y.rkt\" )\n> #\".rkt\"\n> > ( path-get-extension \"x/y\" )\n> #f\n> > ( path-get-extension \"x/y.tar.gz\" )\n> #\".gz\"\n> > ( path-get-extension \"x/.racketrc\" )\n> #f\n> ```\nAdded in version 6.5.0.3 of package base.\n> ```\n(path-has-extension? path ext)  →  boolean?\n  path : (or/c path-string? path-for-some-system?)\n  ext : (or/c bytes? string?)"} {"text": "# 14.15 Deprecation\n```\nDetermines whether the last element of path ends with ext but is not exactly the same as ext.\n\nIf ext is a byte string with the shape of an extension (i.e., starting with . and not including another .), this check is equivalent to checking whether (path-get-extension path) produces ext.\n\nExamples:\n\n> ```racket\n> > ( path-has-extension? \"x/y.rkt\" #\".rkt\" )\n> #t\n> > ( path-has-extension? \"x/y.ss\" #\".rkt\" )\n> #f\n> > ( path-has-extension? \"x/y\" #\".rkt\" )\n> #f\n> > ( path-has-extension? \"x/.racketrc\" #\".racketrc\" )\n> #f\n> > ( path-has-extension? \"x/compiled/y_rkt.zo\" #\"_rkt.zo\" )\n> #t\n> ```\n\nAdded in version 6.5.0.3 of package base.\n\n> ```\n(filename-extension path)  →  (or/c bytes? #f)\n  path : (or/c path-string? path-for-some-system?)```\n\n\n> NOTE: This function is deprecated; use [path-get-extension](#%28def._%28%28lib._racket%2Fpath..rkt%29._path-get-extension%29%29), instead.\n\nReturns a byte string that is the extension part of the filename in path without the . separator. If path is syntactically a directory (see [split-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._split-path%29%29)) or if the path has no extension, #f is returned.\n\n> ```\n(find-relative-path base\n    path  \n   [ #:more-than-root? more-than-root?  \n    #:more-than-same? more-than-same?  \n    #:normalize-case? normalize-case?)  \n\n  →  (or/c path-for-some-system? path-string?)\n  base : (or/c path-string? path-for-some-system?)\n  path : (or/c path-string?  path-for-some-system?)\n  more-than-root? : any/c = #f\n  more-than-same? : any/c = #t\n  normalize-case? : any/c = #t\n```"} {"text": "# 14.15 Deprecation\n(current-directory)\t→\t\n(-> and/c path-string? complete-path?)```\n> > > For most purposes, [simple-form-path](#%28def._%28%28lib._racket%2Fpath..rkt%29._simple-form-path%29%29) is the preferred mechanism to normalize a path, because it works for paths that include non-existent directory components, and it avoids unnecessarily expanding soft links.\nReturns a complete version of path by making the path complete, expanding the complete path, and resolving all soft links (which requires consulting the filesystem). If path is relative, then wrt is used as the base path.\nLetter case is not normalized by [normalize-path](#%28def._%28%28lib._racket%2Fpath..rkt%29._normalize-path%29%29). For this and other reasons, such as whether the path is syntactically a directory, the result of [normalize-path](#%28def._%28%28lib._racket%2Fpath..rkt%29._normalize-path%29%29) is not suitable for comparisons that determine whether two paths refer to the same file or directory (i.e., the comparison may produce false negatives).\nAn error is signaled by [normalize-path](#%28def._%28%28lib._racket%2Fpath..rkt%29._normalize-path%29%29) if the input path contains an embedded path for a non-existent directory, or if an infinite cycle of soft links is detected.\nExample:\n> ```racket\n> > ( equal? ( current-directory ) ( normalize-path \".\" ) )\n> #t\n> ```\n> ```\n(path-element? path)  →  boolean?\n  path : any/c"} {"text": "# 14.15 Deprecation\n```\nReturns #t if path is a path element: a path value for some platform (see path-for-some-system?) such that split-path applied to path would return 'relative as its first result and a path as its second result. Otherwise, the result is #f.\n\n> ```\n(path-only path)  →  (or/c #f path-for-some-system?)\n  path : (or/c path-string? path-for-some-system?)```\n\n\nReturns path without its final path element in the case that path is not syntactically a directory; if path has only a single, non-directory path element, #f is returned. If path is syntactically a directory, then path is returned unchanged (but as a path, if it was a string).\n\nExamples:\n\n> ```racket\n> > ( path-only ( build-path \"a\" \"b\" ) )\n> #\n> > ( path-only ( build-path \"a\" ) )\n> #f\n> > ( path-only ( path->directory-path ( build-path \"a\" ) ) )\n> #\n> > ( path-only ( build-path ' up ' up ) )\n> #\n> ```\n\n> ```\n(simple-form-path path)  →  path?\n  path : path-string?\n```\nReturns (simplify-path (path → complete-path path)), which ensures that the result is a complete path containing no up- or same-directory indicators.\n> ```\n(some-system-path → string path)  →  string?\n  path : path-for-some-system?```\nConverts path to a string using a UTF-8 encoding of the path’s bytes.\nUse this function when working with paths for a different system (whose encoding of pathnames might be unrelated to the current locale’s encoding) and when starting and ending with strings.\n> ```"} {"text": "# 14.15 Deprecation\n(string → some-system-path str kind)  →  path-for-some-system?\n  str : string?\n  kind : (or/c 'unix 'windows)\n```\n\n\nConverts str to a kind path using a UTF-8 encoding of the path’s bytes.\n\nUse this function when working with paths for a different system (whose encoding of pathnames might be unrelated to the current locale’s encoding) and when starting and ending with strings.\n\n> ```\n(shrink-path-wrt pth other-pths)  →  (or/c #f path?)\n  pth : path?\n  other-pths : (listof path?)\n```\nReturns a suffix of pth that shares nothing in common with the suffixes of other-pths, or pth, if not possible (e.g. when other-pths is empty or contains only paths with the same elements as pth).\nExamples:\n> ```racket\n> > ( shrink-path-wrt ( build-path \"racket\" \"list.rkt\" ) ( list ( build-path \"racket\" \"list.rkt\" ) ( build-path \"racket\" \"base.rkt\" ) ) )\n> #\n> > ( shrink-path-wrt ( build-path \"racket\" \"list.rkt\" ) ( list ( build-path \"racket\" \"list.rkt\" ) ( build-path \"racket\" \"private\" \"list.rkt\" ) ( build-path \"racket\" \"base.rkt\" ) ) )\n> #\n> ```\n------------------------------------------------------------------------"} {"text": "# 15.1.3 Unix and Mac OS Paths"} {"text": "#### 15.1.3 Unix and Mac OS Paths\nIn a path on Unix and Mac OS, a / separates elements of the path, . as a path element always means the directory indicated by preceding path, and .. as a path element always means the parent of the directory indicated by the preceding path. A leading \\~ in a path is not treated specially, but [expand-user-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._expand-user-path%29%29) can be used to convert a leading \\~ element to a user-specific directory. No other character or byte has a special meaning within a path. Multiple adjacent / are equivalent to a single / (i.e., they act as a single path separator).\nA path root is always /. A path starting with / is an absolute, complete path, and a path starting with any other character is a relative path.\nAny pathname that ends with a / syntactically refers to a directory, as does any path whose last element is . or ...\nA Unix and Mac OS path is [cleanse](pathutils.html#%28tech._cleanse%29)d by replacing multiple adjacent /s with a single /."} {"text": "# 15.1.3 Unix and Mac OS Paths\nFor ([bytes->path-element](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._bytes-~3epath-element%29%29) bstr), bstr must not contain any /, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. The result of ([path-element->bytes](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._path-element-~3ebytes%29%29) path) or ([path-element->string](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._path-element-~3estring%29%29) path) is always the same as the result of ([path->bytes](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._path-~3ebytes%29%29) path) and ([path->string](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._path-~3estring%29%29) path). Since that is not the case for other platforms, however, [path-element->bytes](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._path-element-~3ebytes%29%29) and [path-element->string](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._path-element-~3estring%29%29) should be used when converting individual path elements.\nOn Mac OS, Finder aliases are zero-length files."} {"text": "##### 15.1.3.1 Unix Path Representation\nA path on Unix and Mac OS is natively a byte string. For presentation to users and for other string-based operations, a path is converted to/from a string using the current locale’s encoding with ? (encoding) or #\\\\uFFFD (decoding) in place of errors. Beware that the encoding may not accommodate all possible paths as distinct strings.\n------------------------------------------------------------------------"} {"text": "# 15.1.4 Windows Paths"} {"text": "#### 15.1.4 Windows Paths\nIn general, a Windows pathname consists of an optional drive specifier and a drive-specific path. A Windows path can be absolute but still relative to the current drive; such paths start with a / or \\\\ separator and are not UNC paths or paths that start with \\\\\\\\?\\\\.\nA path that starts with a drive specification is complete. Roughly, a drive specification is either a Latin letter followed by a colon, a UNC path of the form \\\\\\\\‹machine›\\\\‹volume›, or a \\\\\\\\?\\\\ form followed by something other than REL\\\\‹element›, or RED\\\\‹element›. (Variants of \\\\\\\\?\\\\ paths are described further below.)\nRacket fails to implement the usual Windows path syntax in one way. Outside of Racket, a pathname \"C:rant.txt\" can be a drive-specific relative path. That is, it names a file \"rant.txt\" on drive \"C:\", but the complete path to the file is determined by the current working directory for drive \"C:\". Racket does not support drive-specific working directories (only a working directory across all drives, as reflected by the [current-directory](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29) parameter). Consequently, Racket implicitly converts a path like \"C:rant.txt\" into \"C:\\\\rant.txt\".\n- Racket-specific: Whenever a path starts with a drive specifier ‹letter›: that is not followed by a / or \\\\, a \\\\ is inserted as the path is [cleanse](pathutils.html#%28tech._cleanse%29)d."} {"text": "# 15.1.4 Windows Paths\nOtherwise, Racket follows standard Windows path conventions, but also adds \\\\\\\\?\\\\REL and \\\\\\\\?\\\\RED conventions to deal with paths inexpressible in the standard convention, plus conventions to deal with excessive \\\\s in \\\\\\\\?\\\\ paths.\nIn the following, ‹letter› stands for a Latin letter (case does not matter), ‹machine› stands for any sequence of characters that does not include \\\\ or / and is not ?, ‹volume› stands for any sequence of characters that does not include \\\\ or / , and ‹element› stands for any sequence of characters that does not include \\\\.\n- Trailing spaces and . in a path element are ignored when the element is the last one in the path, unless the path starts with \\\\\\\\?\\\\ or the element consists of only spaces and .s.\n- The following special “files”, which access devices, exist in all directories, case-insensitively, and with all possible endings after a period or colon, except in pathnames that start with \\\\\\\\?\\\\: \"NUL\", \"CON\", \"PRN\", \"AUX\", \"COM1\", \"COM2\", \"COM3\", \"COM4\", \"COM5\", \"COM6\", \"COM7\", \"COM8\", \"COM9\", \"LPT1\", \"LPT2\", \"LPT3\", \"LPT4\", \"LPT5\", \"LPT6\", \"LPT7\", \"LPT8\", \"LPT9\".\n- Except for \\\\\\\\?\\\\ paths, /s are equivalent to \\\\s. Except for \\\\\\\\?\\\\ paths and the start of UNC paths, multiple adjacent /s and \\\\s count as a single \\\\. In a path that starts \\\\\\\\?\\\\ paths, elements can be separated by either a single or double \\\\."} {"text": "# 15.1.4 Windows Paths\n- A directory can be accessed with or without a trailing separator. In the case of a non-\\\\\\\\?\\\\ path, the trailing separator can be any number of /s and \\\\s; in the case of a \\\\\\\\?\\\\ path, a trailing separator must be a single \\\\, except that two \\\\s can follow \\\\\\\\?\\\\‹letter›:.\n- Except for \\\\\\\\?\\\\ paths, a single . as a path element means “the current directory,” and a .. as a path element means “the parent directory.” Up-directory path elements (i.e., ..) immediately after a drive are ignored.\n- A pathname that starts \\\\\\\\‹machine›\\\\‹volume› (where a / can replace any \\\\) is a UNC path, and the starting \\\\\\\\‹machine›\\\\‹volume› counts as the drive specifier.\n- Normally, a path element cannot contain a character in the range #\\\\x 0 to #\\\\x 1F nor any of the following characters:\n > \\< \\> : \" / \\\\ \\| ? \\*\n Except for \\\\, path elements containing these characters can be accessed using a \\\\\\\\?\\\\ path (assuming that the underlying filesystem allows the characters).\n- In a pathname that starts \\\\\\\\?\\\\‹letter›:\\\\, the \\\\\\\\?\\\\‹letter›:\\\\ prefix counts as the path’s drive, as long as the path does not both contain non-drive elements and end with two consecutive \\\\s, and as long as the path contains no sequence of three or more \\\\s. Two \\\\s can appear in place of the \\\\ before ‹letter›. A / cannot be used in place of a \\\\ (but /s can be used in element names, though the result typically does not name an actual directory or file)."} {"text": "# 15.1.4 Windows Paths\n- In a pathname that starts \\\\\\\\?\\\\UNC\\\\‹machine›\\\\‹volume›, the \\\\\\\\?\\\\UNC\\\\‹machine›\\\\‹volume› prefix counts as the path’s drive, as long as the path does not end with two consecutive \\\\s, and as long as the path contains no sequence of three or more \\\\s. Two \\\\s can appear in place of the \\\\ before UNC, the \\\\s after UNC, and/or the \\\\s after‹machine›. The letters in the UNC part can be uppercase or lowercase, and / cannot be used in place of \\\\s (but / can be used in element names).\n- Racket-specific: A pathname that starts \\\\\\\\?\\\\REL\\\\‹element› or \\\\\\\\?\\\\REL\\\\\\\\‹element› is a relative path, as long as the path does not end with two consecutive \\\\s, and as long as the path contains no sequence of three or more \\\\s. This Racket-specific path form supports relative paths with elements that are not normally expressible in Windows paths (e.g., a final element that ends in a space). The REL part must be exactly the three uppercase letters, and /s cannot be used in place of \\\\s. If the path starts \\\\\\\\?\\\\REL\\\\.. then for as long as the path continues with repetitions of \\\\.., each element counts as an up-directory element; a single \\\\ must be used to separate the up-directory elements. As soon as a second \\\\ is used to separate the elements, or as soon as a non-.. element is encountered, the remaining elements are all literals (never up-directory elements). When a \\\\\\\\?\\\\REL path value is converted to a string (or when the path value is written or displayed), the string does not contain the starting \\\\\\\\?\\\\REL or the immediately following \\\\s; converting a path value to a byte string preserves the \\\\\\\\?\\\\REL prefix."} {"text": "# 15.1.4 Windows Paths\n- Racket-specific: A pathname that starts \\\\\\\\?\\\\RED\\\\‹element› or \\\\\\\\?\\\\RED\\\\\\\\‹element› is a drive-relative path, as long as the path does not end with two consecutive \\\\s, and as long as the path contains no sequence of three or more \\\\s. This Racket-specific path form supports drive-relative paths (i.e., absolute given a drive) with elements that are not normally expressible in Windows paths. The RED part must be exactly the three uppercase letters, and /s cannot be used in place of \\\\s. Unlike \\\\\\\\?\\\\REL paths, a .. element is always a literal path element. When a \\\\\\\\?\\\\RED path value is converted to a string (or when the path value is written or displayed), the string does not contain the starting \\\\\\\\?\\\\RED and it contains a single starting \\\\; converting a path value to a byte string preserves the \\\\\\\\?\\\\RED prefix.\nThree additional Racket-specific rules provide meanings to character sequences that are otherwise ill-formed as Windows paths:\n- Racket-specific: In a pathname of the form \\\\\\\\?\\\\‹any›\\\\\\\\ where ‹any› is any non-empty sequence of characters other than ‹letter›: or \\\\‹letter›:, the entire path counts as the path’s (non-existent) drive.\n- Racket-specific: In a pathname of the form \\\\\\\\?\\\\‹any›\\\\\\\\\\\\‹elements›, where ‹any› is any non-empty sequence of characters and ‹elements› is any sequence that does not start with a \\\\, does not end with two \\\\s, and does not contain a sequence of three \\\\s, then \\\\\\\\?\\\\‹any›\\\\\\\\ counts as the path’s (non-existent) drive."} {"text": "# 15.1.4 Windows Paths\n- Racket-specific: In a pathname that starts \\\\\\\\?\\\\ and does not match any of the patterns from the preceding bullets, \\\\\\\\?\\\\ counts as the path’s (non-existent) drive.\nOutside of Racket, except for \\\\\\\\?\\\\ paths, pathnames are typically limited to 259 characters when used as a file path and 247 characters when used as a directory path. Racket internally converts pathnames longer than 247 characters to \\\\\\\\?\\\\ form to avoid the limits; in that case, the path is first simplified syntactically (in the sense of [simplify-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._simplify-path%29%29)). The operating system cannot access files through \\\\\\\\?\\\\ paths that are longer than 32,000 characters or so.\nWhere the above descriptions says “character,” substitute “byte” for interpreting byte strings as paths. The encoding of Windows paths into bytes preserves ASCII characters, and all special characters mentioned above are ASCII, so all of the rules are the same.\nBeware that the \\\\ path separator is an escape character in Racket strings. Thus, the path \\\\\\\\?\\\\REL\\\\..\\\\\\\\.. as a string must be written \"\\\\\\\\\\\\\\\\?\\\\\\\\REL\\\\\\\\..\\\\\\\\\\\\\\\\..\".\nA path that ends with a directory separator syntactically refers to a directory. In addition, a path syntactically refers to a directory if its last element is a same-directory or up-directory indicator (not quoted by a \\\\\\\\?\\\\ form), or if it refers to a root."} {"text": "# 15.1.4 Windows Paths\nEven on variants of Windows that support symbolic links, up-directory .. indicators in a path are resolved syntactically, not sensitive to links. For example, if a path ends with d\\\\..\\\\f and d refers to a symbolic link that references a directory with a different parent than d, the path nevertheless refers to f in the same directory as d. A relative-path link is parsed as if prefixed with \\\\\\\\?\\\\REL paths, except that .. and . elements are allowed throughout the path, and any number of redundant \\\\ separators are allowed.\nWindows paths are [cleanse](pathutils.html#%28tech._cleanse%29)d as follows: In paths that start \\\\\\\\?\\\\, redundant \\\\s are removed, an extra \\\\ is added in a \\\\\\\\?\\\\REL if an extra one is not already present to separate up-directory indicators from literal path elements, and an extra \\\\ is similarly added after \\\\\\\\?\\\\RED if an extra one is not already present. For other paths, multiple /s and \\\\s are converted to single /s or \\\\ (except at the beginning of a shared folder name), and a \\\\ is inserted after the colon in a drive specification if it is missing."} {"text": "# 15.1.4 Windows Paths\nFor ([bytes->path-element](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._bytes-~3epath-element%29%29) bstr), /s, colons, trailing dots, trailing whitespace, and special device names (e.g., “aux”) in bstr are encoded as a literal part of the path element by using a \\\\\\\\?\\\\REL prefix. The bstr argument must not contain a \\\\, otherwise the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\nFor ([path-element->bytes](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._path-element-~3ebytes%29%29) path) or ([path-element->string](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._path-element-~3estring%29%29) path), if the byte-string form of path starts with a \\\\\\\\?\\\\REL, the prefix is not included in the result."} {"text": "# 15.1.4 Windows Paths\nFor ([build-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._build-path%29%29) base-path sub-path [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)), trailing spaces and periods are removed from the last element of base-path and all but the last sub-path (unless the element consists of only spaces and periods), except for those that start with \\\\\\\\?\\\\. If base-path starts \\\\\\\\?\\\\, then after each non-\\\\\\\\?\\\\REL\\\\ and non-\\\\\\\\?\\\\RED\\\\ sub-path is added, all /s in the addition are converted to \\\\s, multiple consecutive \\\\s are converted to a single \\\\, added . elements are removed, and added .. elements are removed along with the preceding element; these conversions are not performed on the original base-path part of the result or on any \\\\\\\\?\\\\REL\\\\ or \\\\\\\\?\\\\RED\\\\ or sub-path. If a \\\\\\\\?\\\\REL\\\\ or \\\\\\\\?\\\\RED\\\\ sub-path is added to a non-\\\\\\\\?\\\\ base-path, the base-path (with any additions up to the \\\\\\\\?\\\\REL\\\\ or \\\\\\\\?\\\\RED\\\\ sub-path) is simplified and converted to a \\\\\\\\?\\\\ path. In other cases, a \\\\ may be added or removed before combining paths to avoid changing the root meaning of the path (e.g., combining //x and y produces /x/y, because //x/y would be a UNC path instead of a drive-relative path)."} {"text": "# 15.1.4 Windows Paths\nFor ([simplify-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._simplify-path%29%29) path use-filesystem?), path is expanded, and if path does not start with \\\\\\\\?\\\\, trailing spaces and periods are removed, a / is inserted after the colon in a drive specification if it is missing, and a \\\\ is inserted after \\\\\\\\?\\\\ as a root if there are elements and no extra \\\\ already. Otherwise, if no indicators or redundant separators are in path, then path is returned.\nFor ([split-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._split-path%29%29) path) producing base, name, and must-be-dir?, splitting a path that does not start with \\\\\\\\?\\\\ can produce parts that start with \\\\\\\\?\\\\. For example, splitting C:/x /aux/ twice produces \\\\\\\\?\\\\REL\\\\\\\\x  and \\\\\\\\?\\\\REL\\\\\\\\aux; the \\\\\\\\?\\\\ is needed in these cases to preserve a trailing space after x and to avoid referring to the AUX device instead of an \"aux\" file."} {"text": "##### 15.1.4.1 Windows Path Representation\nA path on Windows is natively a sequence of UTF-16 code units, where the sequence can include unpaired surrogates. This sequence is encoded as a byte string through an extension of UTF-8, where unpaired surrogates in the UTF-16 code-unit sequence are converted as if they were non-surrogate values. The extended encodings are implemented on Windows as the \"platform-UTF-16\" and \"platform-UTF-8\" encodings for [bytes-open-converter](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._bytes-open-converter%29%29).\nRacket’s internal representation of a Windows path is a byte string, so that [path->bytes](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._path-~3ebytes%29%29) and [bytes->path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._bytes-~3epath%29%29) are always inverses. When converting a path to a native UTF-16 code-unit sequence, #\\\\tab is used in place of platform-UTF-8 decoding errors (on the grounds that tab is normally disallowed as a character in a Windows path, unlike #\\\\uFFFD).\nA Windows path is converted to a string by treating the platform-UTF-8 encoding as a UTF-8 encoding with #\\\\uFFFD in place of decoding errors. Similarly, a string is converted to a path by UTF-8 encoding (in which case no errors are possible).\n------------------------------------------------------------------------"} {"text": "# 15.2 Filesystem"} {"text": "### 15.2 Filesystem"} {"text": "#### 15.2.1 Locating Paths\n> ```\n(parameter)\t→\n```\n(parameter)\t→\t\n(-> listof (or/c path? 'same))```\n\n\nParses a string or byte string containing a list of paths, and returns a list of paths. On Unix and Mac OS, paths in a path-list string are separated by a :; on Windows, paths are separated by a ;, and all \"s in the string are discarded. Whenever the path list contains an empty path, the list default-path-list is spliced into the returned list of paths. Parts of str that do not form a valid path are not included in the returned list. The given str must not contain a nul character or nul byte.\n\nChanged in version 8.0.0.10 of package base: Changed to allow 'same in default-path-list.\n\n> ```\n(find-executable-path program\n   [ related        \n    deepest?)   →   (or/c path? #f)\n\n  program : path-string?\n  related : (or/c path-string? #f) = #f\n  deepest? : any/c = #f\n```\nFinds a path for the executable program, returning #f if the path cannot be found.\nOn Windows, if program is not found and it has no file extension, then the search starts over with \".exe\" added to program, and the result is #f only if the path with \".exe\" also cannot be found. The result includes the extension \".exe\" if only program with the extension is found.\nIf related is not #f, then it must be a relative path string, and the path found for program must be such that the file or directory related exists in the same directory as the executable. The result is then the full path for the found related, instead of the path for the executable."} {"text": "# 15.2 Filesystem\nThis procedure is used by the Racket executable to find the standard library collection directory (see Libraries and Collections). In this case, program is the name used to start Racket and related is \"collects\". The related argument is used because, on Unix and Mac OS, program may involve a sequence of soft links; in this case, related determines which link in the chain is relevant.\nIf related is not #f, then when find-executable-path does not find a program that is a link to another file path, the search can continue with the destination of the link. Further links are inspected until related is found or the end of the chain of links is reached. If deepest? is #f (the default), then the result corresponds to the first path in a chain of links for which related is found (and further links are not actually explored); otherwise, the result corresponds to the last link in the chain for which related is found.\nIf program is a pathless name, find-executable-path gets the value of the PATH environment variable; if this environment variable is defined, find-executable-path tries each path in PATH as a prefix for program using the search algorithm described above for path-containing programs. If the PATH environment variable is not defined, program is prefixed with the current directory and used in the search algorithm above. (On Windows, the current directory is always implicitly the first item in PATH, so find-executable-path checks the current directory first on Windows.)\nChanged in version 8.1.0.7 of package base: Added search with \".exe\" on Windows."} {"text": "#### 15.2.2 Files\n> ```\n(file-exists? path)  →  boolean?\n  path : path-string?```\nReturns #t if a file (not a directory) path exists, #f otherwise.\nOn Windows, [file-exists?](#%28def._%28%28quote._~23~25kernel%29._file-exists~3f%29%29) reports #t for all variations of the special filenames (e.g., \"LPT1\", \"x:/baddir/LPT1\").\n> ```\n(link-exists? path)  →  boolean?\n  path : path-string?\n```\nReturns #t if a link path exists, #f otherwise.\n\nThe predicates file-exists? or directory-exists? work on the final destination of a link or series of links, while link-exists? only follows links to resolve the base part of path (i.e., everything except the last name in the path).\n\nThis procedure never raises the exn:fail:filesystem exception.\n\nOn Windows, link-exists? reports #t for both symbolic links and junctions.\n\nChanged in version 6.0.1.12 of package base: Added support for links on Windows.\n\n> ```\n(file-or-directory-type path [must-exist?)\n  →  (or/c 'file 'directory 'link 'directory-link #f)\n  path : path-string?\n  must-exist? : any/c = #f```\n\n\nReports whether path refers to a file, directory, link, or directory link (in the case of Windows; see also [make-file-or-directory-link](#%28def._%28%28quote._~23~25kernel%29._make-file-or-directory-link%29%29)), assuming that path can be accessed.\n\nIf path cannot be accessed, the result is #f if must-exist? is #f, otherwise the [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) exception is raised.\n\nAdded in version 7.8.0.5 of package base.\n\n> ```\n(parameter)\t→\n```"} {"text": "# 15.2 Filesystem\n(parameter)\t→```\nRenames the file or directory with path old—if it exists—to the path new. If the file or directory is not renamed successfully, the [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) exception is raised.\nThis procedure can be used to move a file/directory to a different directory (on the same filesystem) as well as rename a file/directory within a directory. Unless exists-ok? is provided as a true value, new cannot refer to an existing file or directory, but the check is not atomic with the rename operation on Unix and Mac OS. Even if exists-ok? is true, new cannot refer to an existing file when old is a directory, and vice versa.\nIf new exists and is replaced, the replacement is atomic on Unix and Mac OS, but it is not guaranteed to be atomic on Windows. Furthermore, if new exists and is opened by any process for reading or writing, then attempting to replace it will typically fail on Windows. See also [call-with-atomic-output-file](#%28def._%28%28lib._racket%2Ffile..rkt%29._call-with-atomic-output-file%29%29).\nIf old is a link, the link is renamed rather than the destination of the link, and it counts as a file for replacing any existing new."} {"text": "# 15.2 Filesystem\nOn Windows, beware that a directory cannot be renamed if any file within the directory is open. That constraint is particularly problematic if a search indexer is running in the background (as in the default Windows configuration). A possible workaround is to combine [copy-directory/files](#%28def._%28%28lib._racket%2Ffile..rkt%29._copy-directory%2Ffiles%29%29) and [delete-directory/files](#%28def._%28%28lib._racket%2Ffile..rkt%29._delete-directory%2Ffiles%29%29), since the latter can deal with open files, although that sequence is obviously not atomic and temporarily duplicates files.\n> ```\n(parameter)\t→\t\n(-> file-or-directory-modify-seconds path\n secs-n)"} {"text": "# 15.2 Filesystem\n```\nReturns the file or directory’s last modification date in seconds since the epoch (see also Time) when secs-n is not provided or is #f.\n\nFor FAT filesystems on Windows, directories do not have modification dates. Therefore, the creation date is returned for a directory, but the modification date is returned for a file.\n\nIf secs-n is provided and not #f, the access and modification times of path are set to the given time.\n\nOn error (e.g., if no such file exists), then fail-thunk is called (through a tail call) to produce the result of the file-or-directory-modify-seconds call. If fail-thunk is not provided, an error raises exn:fail:filesystem.\n\n> ```\n(file-or-directory-permissions path [mode)\n  →  (listof (or/c 'read 'write 'execute))\n  path : path-string?\n  mode : #f = #f\n(file-or-directory-permissions path mode)  →  (integer-in 0 65535)\n  path : path-string?\n  mode : 'bits\n(file-or-directory-permissions path mode)  →  void\n  path : path-string?\n  mode : (integer-in 0 65535)```\n\n\nWhen given one argument or #f as the second argument, returns a list containing 'read, 'write, and/or 'execute to indicate permission the given file or directory path by the current user and group. On Unix and Mac OS, permissions are checked for the current effective user instead of the real user.\n\nIf 'bits is supplied as the second argument, the result is a platform-specific integer encoding of the file or directory properties (mostly permissions), and the result is independent of the current user and group. The lowest nine bits of the encoding are somewhat portable, reflecting permissions for the file or directory’s owner, members of the file or directory’s group, or other users:\n\n- #o400 : owner has read permission\n\n- #o200 : owner has write permission\n\n- #o100 : owner has execute permission\n\n- #o040 : group has read permission\n\n- #o020 : group has write permission\n\n- #o010 : group has execute permission\n\n- #o004 : others have read permission\n\n- #o002 : others have write permission\n\n- #o001 : others have execute permission\n\nSee also [user-read-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._user-read-bit%29%29), etc. On Windows, permissions from all three (owner, group, and others) are always the same, and read and execute permission are always available. On Unix and Mac OS, higher bits have a platform-specific meaning.\n\nIf an integer is supplied as the second argument, it is used as an encoding of properties (mostly permissions) to install for the file.\n\nIn all modes, the [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) exception is raised on error (e.g., if no such file exists).\n\n> ```\n(parameter)\t→\t\n(-> and/c (hash/c symbol? any/c) hash-eq?)\n```"} {"text": "# 15.2 Filesystem\nReturns a hash with the following keys and values, where each value currently is a nonnegative exact integer:\n- 'device-id : device ID\n- 'inode : inode number\n- 'mode : mode bits (see below)\n- 'hardlink-count : number of hard links\n- 'user-id : numeric user ID of owner\n- 'group-id : numeric group ID of owner\n- 'device-id-for-special-file : device ID (if special file)\n- 'size : size of file or symbolic link in bytes\n- 'block-size : size of filesystem blocks\n- 'block-count : number of used filesystem blocks\n- 'access-time-seconds : last access time in seconds since the epoch\n- 'modify-time-seconds : last modification time in seconds since the epoch\n- 'change-time-seconds : last status change time in seconds since the epoch\n- 'creation-time-seconds : creation time in seconds since the epoch\n- 'access-time-nanoseconds : last access time in nanoseconds since the epoch\n- 'modify-time-nanoseconds : last modification time in nanoseconds since the epoch\n- 'change-time-nanoseconds : last status change time in nanoseconds since the epoch\n- 'creation-time-nanoseconds : creation time in nanoseconds since the epoch\nIf as-link? is a true value, then if path refers to a symbolic link, the stat information of the link is returned instead of the stat information of the referenced filesystem item.\nThe mode bits are the bits for permissions and other data, as returned from the Posix stat/lstat functions or the Windows \\_wstat64 function, respectively. To select portions of the bit pattern, use the constants user-read-bit, etc."} {"text": "# 15.2 Filesystem\nDepending on the operating system and filesystem, the “nanoseconds” timestamps may have less than nanoseconds precision. For example, in one environment a timestamp may be 1234567891234567891 (nanoseconds precision) and in another environment 1234567891000000000 (seconds precision).\nValues that aren’t available for a platform/filesystem combination may be set to 0. For example, this applies to the 'user-id and 'group-id keys on Windows. Also, Posix platforms provide the status change timestamp, but not the creation timestamp; for Windows it’s the opposite.\nIf as-link? is #f and path isn’t accessible, the exn:fail:filesystem exception is raised. This exception is also raised if as-link? is a true value and path can’t be resolved, i.e., is a dangling link.\nAdded in version 8.3.0.7 of package base.\n> ```\n(file-or-directory-identity path [as-link?)\n  →  exact-positive-integer?\n  path : path-string?\n  as-link? : any/c = #f```\nReturns a number that represents the identity of path in terms of the device and file or directory that it accesses. This function can be used to check whether two paths correspond to the same filesystem entity under the assumption that the path’s entity selection does not change.\nIf as-link? is a true value, then if path refers to a filesystem link, the identity of the link is returned instead of the identity of the referenced file or directory (if any).\n> ```\n(file-size path)  →  exact-nonnegative-integer?\n  path : path-string?"} {"text": "# 15.2 Filesystem\n```\n(logical)\t→\t\n(-> or/c #f (integer-in 0 65535))```\n\n\nCreates the file dest as a copy of src, if dest does not already exist. If dest already exists and exists-ok? is #f, the copy fails and the [exn:fail:filesystem:exists?](exns.html#%28def._%28%28quote._~23~25kernel%29._exn~3afail~3afilesystem~3aexists~3f%29%29) exception is raised; otherwise, if dest exists, its content is replaced with the content of src.\n\nIf src refers to a link, the target of the link is copied, rather than the link itself. If dest refers to a link and exists-ok? is true, the target of the link is updated.\n\nFile permissions are transferred from src to dest, unless permissions is supplied as non-#f on Unix and Mac OS, in which case permissions is used for dest. Beware that permissions are transferred without regard for the process’s umask setting by default, but see replace-permissions? below. On Windows, the modification time of src is also transferred to dest; if permissions is supplied as non-#f, then after copying, dest is set to read-only or not depending on whether the #o2 bit is present in permissions.\n\nThe replace-permissions? argument is used only on Unix and Mac OS. When dests is created, it is created with permissions or the permissions of src; however, the process’s umask may unset bits in the requested permissions. When dest already exists (and exists-ok? is true), then the permissions of dest are initially left as-is. Finally, when replace-permissions? is a true value, then the permissions of dest are set after the file content is copied to permissions or the permissions of src, without modification by umask.\n\nThe exists-ok?/pos by-position argument is for backward compatibility. That by-position argument can be supplied, or the exists-ok? keyword argument can be supplied, but the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised if both are supplied.\n\nChanged in version 8.7.0.9 of package base: Added #:exists-ok?, #:permissions, and #:replace-permissions? arguments.\n\n> ```\n(parameter)\t→\n```"} {"text": "# 15.2 Filesystem\n(current-force-delete-permissions)\t→\t\n(-> current-force-delete-permissions)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines on Windows whether [delete-file](#%28def._%28%28quote._~23~25kernel%29._delete-file%29%29) and [delete-directory](#%28def._%28%28quote._~23~25kernel%29._delete-directory%29%29) attempt to change a file or directory’s permissions to delete it. The default value is #t."} {"text": "#### 15.2.3 Directories\nSee also: [rename-file-or-directory](#%28def._%28%28quote._~23~25kernel%29._rename-file-or-directory%29%29), [file-or-directory-modify-seconds](#%28def._%28%28quote._~23~25kernel%29._file-or-directory-modify-seconds%29%29), [file-or-directory-permissions](#%28def._%28%28quote._~23~25kernel%29._file-or-directory-permissions%29%29).\n> ```\n(current-directory)\t→\t\n(-> and/c path? complete-path?)\n(current-directory path) → void?\n path\t:\t\n(-> and/c path? complete-path?)\n```\n(current-directory-for-user)\t→\t\n(-> current-directory-for-user)\n(current-directory-for-user path) → void?\n path\t:\t\n(-> current-directory-for-user)```\n\n\nLike [current-directory](#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29), but for use only by [srcloc->string](exns.html#%28def._%28%28quote._~23~25kernel%29._srcloc-~3estring%29%29) for reporting paths relative to a directory.\n\nNormally, [current-directory-for-user](#%28def._%28%28quote._~23~25kernel%29._current-directory-for-user%29%29) should stay at its initial value, reflecting the directory where a user started a process. A tool such as DrRacket, however, implicitly lets a user select a directory (for the file being edited), in which case updating [current-directory-for-user](#%28def._%28%28quote._~23~25kernel%29._current-directory-for-user%29%29) makes sense.\n\n> ```\n(current-drive)\t→\n```\nReturns the current drive name Windows. For other platforms, the exn:fail:unsupported exception is raised. The current drive is always the drive of the current directory.\n> ```"} {"text": "# 15.2 Filesystem\n(directory-exists? path)  →  boolean?\n  path : path-string?```\nReturns #t if path refers to a directory, #f otherwise.\n> ```\n(parameter)\t→\t\n(-> integer-in 0 65535)\n```\n(parameter)\t→```\n\n\nDeletes an existing directory with the path path. If the directory is not deleted successfully, the [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) exception is raised.\n\nOn Windows, if an initial attempt to delete the directory fails with a permission error and the value of [current-force-delete-permissions](#%28def._%28%28quote._~23~25kernel%29._current-force-delete-permissions%29%29) is true, then [delete-file](#%28def._%28%28quote._~23~25kernel%29._delete-file%29%29) attempts to change the directory’s permissions (to allow writes) and then delete the directory; the permission change followed by deletion is a non-atomic sequence, with no attempt to revert a permission change if the deletion fails.\n\nChanged in version 6.1.1.7 of package base: Changed Windows behavior to use [current-force-delete-permissions](#%28def._%28%28quote._~23~25kernel%29._current-force-delete-permissions%29%29).\n\n> ```\n(current-directory)\t→\t\n(-> listof path?)\n```\n> > > See also the in-directory sequence constructor.\nReturns a list of all files and directories in the directory specified by path. If build? is #f, the resulting paths are all path elements; otherwise, the individual results are combined with path using build-path. On Windows, an element of the result list may start with \\\\\\\\?\\\\REL\\\\\\\\."} {"text": "# 15.2 Filesystem\nThe resulting paths are always sorted using path ```\n(filesystem-root-list)  →  (listof path?)```\nReturns a list of all current root directories. Obtaining this list can be particularly slow on Windows."} {"text": "#### 15.2.4 Detecting Filesystem Changes\nMany operating systems provide notifications for filesystem changes, and those notifications are reflected in Racket by [filesystem change events](#%28tech._filesystem._change._event%29).\n> ```\n(filesystem-change-evt? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a filesystem change event, #f otherwise.\n\n> ```\n(filesystem-change-evt path [failure-thunk)\n  →  (or/c filesystem-change-evt? any)\n  path : path-string?\n  failure-thunk : (or/c ( →  any) #f) = #f```\n\n\nCreates a filesystem change event, which is a [synchronizable event](sync.html#%28tech._synchronizable._event%29) that becomes [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29) after a change to path:\n\n- If path refers to a file, the event becomes [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29) when the file’s content or attributes change, or when the file is deleted.\n\n- If path refers to a directory, the event becomes [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29) if a file or subdirectory is added, renamed, or removed within the directory.\n\nThe event also becomes [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29) if it is passed to [filesystem-change-evt-cancel](#%28def._%28%28quote._~23~25kernel%29._filesystem-change-evt-cancel%29%29).\n\nFinally, depending on the precision of information available from the operating system, the event may become [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29) under other circumstances. For example, on Windows, an event for a file becomes ready when any file changes within in the same directory as the file.\n\nAfter a [filesystem change event](#%28tech._filesystem._change._event%29) becomes [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29), it stays [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29). The event’s [synchronization result](sync.html#%28tech._synchronization._result%29) is the event itself.\n\nIf the current platform does not support filesystem-change notifications, then the [exn:fail:unsupported](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aunsupported%29%29) exception is raised if failure-thunk is not provided as a procedure, or failure-thunk is called in tail position if provided. Similarly, if there is any operating-system error when creating the event (such as a non-existent file), then the [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) exception is raised or failure-thunk is called.\n\nCreation of a filesystem change event allocates resources at the operating-system level. The resources are released at latest when the event is sychronized and [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29), when the event is canceled with [filesystem-change-evt-cancel](#%28def._%28%28quote._~23~25kernel%29._filesystem-change-evt-cancel%29%29), or when the garbage collector determine that the filesystem change event is unreachable. See also [system-type](runtime.html#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) in 'fs-change mode.\n\nA filesystem change event is placed under the management of the [current custodian](eval-model.html#%28tech._current._custodian%29) when it is created. If the [custodian](eval-model.html#%28tech._custodian%29) is shut down, [filesystem-change-evt-cancel](#%28def._%28%28quote._~23~25kernel%29._filesystem-change-evt-cancel%29%29) is applied to the event.\n\nChanged in version 7.3.0.8 of package base: Allow #f for failure-thunk.\n\n> ```\n(filesystem-change-evt-ready? evt)  →  boolean?\n  evt : filesystem-change-evt?\n```"} {"text": "# 15.2 Filesystem\n(parameter)\t→```\nCauses evt to become immediately [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29), whether it was ready or not before, and releases the resources (at the operating-system level) for tracking filesystem changes."} {"text": "#### 15.2.5 Declaring Paths Needed at Run Time\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/runtime-path](#%28mod-path._racket%2Fruntime-path%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/runtime-path](#%28mod-path._racket%2Fruntime-path%29) library, not [racket/base](index.html) or [racket](index.html)."} {"text": "# 15.2 Filesystem\nThe [racket/runtime-path](#%28mod-path._racket%2Fruntime-path%29) library provides forms for accessing files and directories at run time using a path that are usually relative to an enclosing source file. Unlike using [collection-path](collects.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._collection-path%29%29), [define-runtime-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path%29%29) exposes each run-time path to tools like the executable and distribution creators, so that files and directories needed at run time are carried along in a distribution.\nIn addition to the bindings described below, [racket/runtime-path](#%28mod-path._racket%2Fruntime-path%29) provides [#%datum](quote.html#%28form._%28%28quote._~23~25kernel%29._~23~25datum%29%29) in [phase level](syntax-model.html#%28tech._phase._level%29) 1, since string constants are often used as compile-time expressions with [define-runtime-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path%29%29).\n>
\n

syntax

"} {"text": "# 15.2 Filesystem\n

([define-runtime-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path%29%29) id maybe-runtime?-id expr)

 
maybe-runtime?-id = 
  | #:runtime?-id runtime?-id
"} {"text": "# 15.2 Filesystem\nUses expr as both a compile-time (i.e., [phase](eval-model.html#%28tech._phase%29) 1) expression and a run-time (i.e., [phase](eval-model.html#%28tech._phase%29) 0) expression. In either context, expr should produce a path, a string that represents a path, a list of the form ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) 'lib str ...+), or a list of the form ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) 'so str) or ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) 'so str vers). If runtime?-id is provided, then it is bound in the context of expr to #f for the compile-time instance of expr and #t for the run-time instance of expr.\nFor run time, id is bound to a path that is based on the result of expr. The path is normally computed by taking a relative path result from expr and adding it to a path for the enclosing file (which is computed as described below). However, tools like the executable creator can also arrange (by colluding with [racket/runtime-path](#%28mod-path._racket%2Fruntime-path%29)) to have a different base path substituted in a generated executable. If expr produces an absolute path, it is normally returned directly, but again may be replaced by an executable creator. In all cases, the executable creator preserves the relative locations of all paths within a given [package](collects.html#%28tech._package%29) (treating paths outside of any package as being together). When expr produces a relative or absolute path, then the path bound to id is always an absolute path."} {"text": "# 15.2 Filesystem\nIf expr produces a list of the form ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) 'lib str ...+), the value bound to id is an absolute path. The path refers to a collection-based file similar to using the value as a [module path](Module_Names_and_Loading.html#%28tech._module._path%29).\nIf expr produces a list of the form ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) 'so str) or ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) 'so str vers), the value bound to id can be either str or an absolute path; it is an absolute path when searching in the Racket-specific shared-object library directories (as determined by [get-lib-search-dirs](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=dirs.html%23%2528def._%2528%2528lib._setup%252Fdirs..rkt%2529._get-lib-search-dirs%2529%2529&version=8.18.0.13)) locates the path. In this way, shared-object libraries that are installed specifically for Racket get carried along in distributions. The search tries each directory in order; within a directory, the search tries using str directly, then it tries adding each version specified by vers—which defaults to '(#f)—along with a platform-specific shared-library extension—as produced by ([system-type](runtime.html#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) 'so-suffix). A vers can be a string, or it can be a list of strings and #f."} {"text": "# 15.2 Filesystem\nIf expr produces a list of the form ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) 'share str), the value bound to id can be either str or an absolute path; it is an absolute path when searching in the directories reported by [find-user-share-dir](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=dirs.html%23%2528def._%2528%2528lib._setup%252Fdirs..rkt%2529._find-user-share-dir%2529%2529&version=8.18.0.13) and [find-share-dir](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=dirs.html%23%2528def._%2528%2528lib._setup%252Fdirs..rkt%2529._find-share-dir%2529%2529&version=8.18.0.13) (in that order) locates the path. In this way, files that are installed in Racket’s \"share\" directory get carried along in distributions."} {"text": "# 15.2 Filesystem\nIf expr produces a list of the form ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) 'module module-path var-ref) or ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) 'so str ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) str-or-false [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29))), the value bound to id is a [module path index](Module_Names_and_Loading.html#%28tech._module._path._index%29), where module-path is treated as relative (if it is relative) to the module that is the home of the [variable reference](Locations____variable-reference.html#%28tech._variable._reference%29) var-ref, where var-ref can be #f if module-path is absolute. In an executable, the corresponding module is carried along, including all of its dependencies."} {"text": "# 15.2 Filesystem\nFor compile-time, the expr result is used by an executable creator—but not the result when the containing module is compiled. Instead, expr is preserved in the module as a compile-time expression (in the sense of [begin-for-syntax](begin.html#%28form._%28%28quote._~23~25kernel%29._begin-for-syntax%29%29)). Later, at the time that an executable is created, the compile-time portion of the module is executed (again), and the result of expr is the file or directory to be included with the executable. The reason for the extra compile-time execution is that the result of expr might be platform-dependent, so the result should not be stored in the (platform-independent) bytecode form of the module; the platform at executable-creation time, however, is the same as at run time for the executable. Note that expr is still evaluated at run time; consequently, avoid procedures like [collection-path](collects.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._collection-path%29%29), which depends on the source installation, and instead use relative paths and forms like ([list](pairs.html#%28def._%28%28quote._~23~25kernel%29._list%29%29) 'lib str ...+).\nIf a path is needed only on some platforms and not on others, use [define-runtime-path-list](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path-list%29%29) with an expr that produces an empty list on platforms where the path is not needed."} {"text": "# 15.2 Filesystem\nBeware that if expr produces the path of a directory when creating an executable, the directory’s full content (including any subdirectories) is included with the executable or eventual distribution.\nAlso beware that [define-runtime-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path%29%29) in a [phase level](syntax-model.html#%28tech._phase._level%29) other than 0 does not cooperate properly with an executable creator. To work around that limitation, put [define-runtime-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path%29%29) in a separate module—perhaps a [submodule](eval-model.html#%28tech._submodule%29) created by [module](module.html#%28form._%28%28quote._~23~25kernel%29._module%29%29)—then export the definition, and then the module containing the definition can be [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29)d into any phase level. Using [define-runtime-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path%29%29) in a [phase level](syntax-model.html#%28tech._phase._level%29) other than 0 logs a warning at expansion time.\nThe enclosing path for a [define-runtime-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path%29%29) is determined as follows from the [define-runtime-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path%29%29) syntactic form:"} {"text": "# 15.2 Filesystem\n- If the form has a source module according to [syntax-source-module](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-source-module%29%29), then the source location is determined by preserving the original expression as a syntax object, extracting its source module path at run time (again using [syntax-source-module](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-source-module%29%29)), and then resolving the resulting module path index. Note that [syntax-source-module](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-source-module%29%29) is based on a syntax object’s [lexical information](syntax-model.html#%28tech._lexical._information%29), not its source location.\n- If the expression has no source module, the [syntax-source](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-source%29%29) location associated with the form is used, if is a string or path.\n- If no source module is available, and [syntax-source](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-source%29%29) produces no path, then [current-load-relative-directory](eval.html#%28def._%28%28quote._~23~25kernel%29._current-load-relative-directory%29%29) is used if it is not #f. Finally, [current-directory](#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29) is used if all else fails."} {"text": "# 15.2 Filesystem\nIn the latter two cases, the path is normally preserved in (platform-specific) byte form, but if the enclosing path corresponds to a result of [collection-file-path](collects.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._collection-file-path%29%29), then the path is record as relative to the corresponding module path.\nChanged in version 6.0.1.6 of package base: Preserve relative paths only within a package. \nChanged in version 7.5.0.7: Added support for 'share in expr.\nExamples:\n> ```racket\n> ; Access a file \"data.txt\" at run-time that is originally\n> ; located in the same directory as the module source file:\n> ( define-runtime-path data-file \"data.txt\" )\n> ( define ( read-data )\n> ( with-input-from-file data-file\n> ( lambda ( )\n> ( read-bytes ( file-size data-file ) ) ) ) )\n> ; Load a platform-specific shared object (using ffi-lib )\n> ; that is located in a platform-specific sub-directory of the\n> ; module ' s source directory:\n> ( define-runtime-path libfit-path\n> ( build-path \"compiled\" \"native\" ( system-library-subpath #f )\n> ( path-replace-suffix \"libfit\"\n> ( system-type ' so-suffix ) ) ) )\n> ( define libfit ( ffi-lib libfit-path ) )\n> ; Load a platform-specific shared object that might be installed\n> ; as part of the operating system, or might be installed\n> ; specifically for Racket:\n> ( define-runtime-path libssl-so\n> ( case ( system-type )\n> [ ( windows ) ' ( so \"ssleay32\" ) ]\n> [ else ' ( so \"libssl\" ) ] ) )\n> ( define libssl ( ffi-lib libssl-so ) )\n> ```\nChanged in version 6.4 of package base: Added #:runtime?-id."} {"text": "# 15.2 Filesystem\n>
\n

syntax

\n

([define-runtime-paths](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-paths%29%29) (id ...) maybe-runtime?-id expr)

\nLike [define-runtime-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path%29%29), but declares and binds multiple paths at once. The expr should produce as many values as ids.\n>
\n

syntax

\n

([define-runtime-path-list](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path-list%29%29) id maybe-runtime?-id expr)

\nLike [define-runtime-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path%29%29), but expr should produce a list of paths.\n>
\n

syntax

\n

([define-runtime-module-path-index](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-module-path-index%29%29) id maybe-runtime?-id module-path-expr)

"} {"text": "# 15.2 Filesystem\nSimilar to [define-runtime-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path%29%29), but id is bound to a [module path index](Module_Names_and_Loading.html#%28tech._module._path._index%29) that encapsulates the result of module-path-expr relative to the enclosing module.\nUse [define-runtime-module-path-index](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-module-path-index%29%29) to bind a module path that is passed to a reflective function like [dynamic-require](Module_Names_and_Loading.html#%28def._%28%28quote._~23~25kernel%29._dynamic-require%29%29) while also creating a module dependency for building and distributing executables.\n>
\n

syntax

\n

([runtime-require](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._runtime-require%29%29) module-path)

\nSimilar to [define-runtime-module-path-index](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-module-path-index%29%29), but creates the distribution dependency without binding a module path index. When [runtime-require](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._runtime-require%29%29) is used multiple times within a module with the same module-path, all but the first use expands to an empty [begin](begin.html#%28form._%28%28quote._~23~25kernel%29._begin%29%29)."} {"text": "# 15.2 Filesystem\n>
\n

syntax

\n

([define-runtime-module-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-module-path%29%29) id module-path)

\nSimilar to [define-runtime-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-path%29%29), but id is bound to a [resolved module path](Module_Names_and_Loading.html#%28tech._resolved._module._path%29). The [resolved module path](Module_Names_and_Loading.html#%28tech._resolved._module._path%29) for id corresponds to module-path (with the same syntax as a module path for [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29)), which can be relative to the enclosing module."} {"text": "# 15.2 Filesystem\nThe [define-runtime-module-path-index](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-module-path-index%29%29) form is usually preferred, because it creates a weaker link to the referenced module. Unlike [define-runtime-module-path-index](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-module-path-index%29%29), the [define-runtime-module-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-module-path%29%29) form creates a [for-label](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-label%29%29) dependency from an enclosing module to module-path. Since the dependency is merely [for-label](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-label%29%29), module-path is not [instantiate](eval-model.html#%28tech._instantiate%29)d or [visit](syntax-model.html#%28tech._visit%29)ed when the enclosing module is [instantiate](eval-model.html#%28tech._instantiate%29)d or [visit](syntax-model.html#%28tech._visit%29)ed (unless such a dependency is created by other [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29)s), but the code for the referenced module is loaded when the enclosing module is loaded.\n>
\n

syntax

\n

([runtime-paths](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._runtime-paths%29%29) module-path)

"} {"text": "# 15.2 Filesystem\nThis form is mainly for use by tools such as executable builders. It expands to a quoted list containing the run-time paths declared by module-path, returning the compile-time results of the declaration exprs, except that paths are converted to byte strings. The enclosing module must require (directly or indirectly) the module specified by module-path, which is an unquoted module path. The resulting list does not include module paths bound through [define-runtime-module-path](#%28form._%28%28lib._racket%2Fruntime-path..rkt%29._define-runtime-module-path%29%29)."} {"text": "#### 15.2.6 More File and Directory Utilities\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/file](#%28mod-path._racket%2Ffile%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/file](#%28mod-path._racket%2Ffile%29) and [racket](index.html) libraries, but not [racket/base](index.html).\n> ```\n(file → string path [#:mode mode-flag) → string?\n  path : path-string?\n  mode-flag : (or/c 'binary 'text) = 'binary"} {"text": "# 15.2 Filesystem\n```\nReads all characters from path and returns them as a string. The mode-flag argument is the same as for open-input-file.\n\n> ```\n(file → bytes path [#:mode mode-flag) → bytes?\n  path : path-string?\n  mode-flag : (or/c 'binary 'text) = 'binary```\n\n\nReads all characters from path and returns them as a [byte string](bytestrings.html#%28tech._byte._string%29). The mode-flag argument is the same as for [open-input-file](file-ports.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._open-input-file%29%29).\n\n> ```\n(file → value path [#:mode mode-flag) → any\n  path : path-string?\n  mode-flag : (or/c 'binary 'text) = 'binary\n```\nReads a single S-expression from path using read. The mode-flag argument is the same as for open-input-file.\n> ```\n(file → list path [proc #:mode mode-flag) → (listof any/c)\n  path : path-string?\n  proc : (input-port? . → . any/c) = read\n  mode-flag : (or/c 'binary 'text) = 'binary```\nRepeatedly calls proc to consume the contents of path, until [eof](port-ops.html#%28def._%28%28quote._~23~25kernel%29._eof%29%29) is produced. The mode-flag argument is the same as for [open-input-file](file-ports.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._open-input-file%29%29).\n> ```\n(file → lines path\n   [ #:mode mode-flag        \n    #:line-mode line-mode)   →   (listof string?)\n  path : path-string?\n  mode-flag : (or/c 'binary 'text) = 'binary\n   line-mode   :   (or/c 'linefeed 'return 'return-linefeed 'any 'any-one)\n      =   'any"} {"text": "# 15.2 Filesystem\n```\nRead all characters from path, breaking them into lines. The line-mode argument is the same as the second argument to read-line, but the default is 'any instead of 'linefeed. The mode-flag argument is the same as for open-input-file.\n\n> ```\n(file → bytes-lines path\n   [ #:mode mode-flag        \n    #:line-mode line-mode)   →   (listof bytes?)\n\n  path : path-string?\n  mode-flag : (or/c 'binary 'text) = 'binary\n   line-mode   :   (or/c 'linefeed 'return 'return-linefeed 'any 'any-one)\n      =   'any```\n\n\nLike [file->lines](#%28def._%28%28lib._racket%2Ffile..rkt%29._file-~3elines%29%29), but reading bytes and collecting them into lines like [read-bytes-line](Byte_and_String_Input.html#%28def._%28%28quote._~23~25kernel%29._read-bytes-line%29%29).\n\n> ```\n(parameter)\t→\t\n(-> or/c 'binary 'text)\n```\n(parameter)\t→\t\n(-> or/c 'binary 'text)```\nLike [display-to-file](#%28def._%28%28lib._racket%2Ffile..rkt%29._display-to-file%29%29), but using [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29) instead of [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29).\n> ```\n(parameter)\t→\t\n(-> or/c 'binary 'text)"} {"text": "# 15.2 Filesystem\n```\n(parameter)\t→```\n\n\nCopies the file or directory src to dest, raising [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) if the file or directory cannot be copied, possibly because dest exists already. If src is a directory, the copy applies recursively to the directory’s content. If a source is a link and preserve-links? is #f, the target of the link is copied rather than the link itself; if preserve-links? is #t, the link is copied.\n\nIf keep-modify-seconds? is #f, then file copies keep only the properties kept by [copy-file](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._copy-file%29%29). If keep-modify-seconds? is true, then each file copy also keeps the modification date of the original.\n\nChanged in version 6.3 of package base: Added the #:preserve-links? argument.\n\n> ```\n(parameter)\t→\n```\nDeletes the file or directory specified by path, raising exn:fail:filesystem if the file or directory cannot be deleted. If path is a directory, then delete-directory/files is first applied to each file and directory in path before the directory is deleted.\nIf must-exist? is true, then exn:fail:filesystem is raised if path does not exist. If must-exist? is false, then delete-directory/files succeeds if path does not exist (but a failure is possible if path initially exists and is removed by another thread or process before delete-directory/files deletes it)."} {"text": "# 15.2 Filesystem\nOn Windows, delete-directory/files attempts to move a file into the temporary-file directory before deleting it, which avoids problems caused by deleting a file that is currently open (e.g., by a search indexer running as a background process). If the move attempt fails (e.g., because the temporary directory is on a different drive than the file), then the file is deleted directly with delete-file.\nChanged in version 7.0 of package base: Added Windows-specific file deletion.\n> ```\n(find-files\n    predicate  \n   [ start-path  \n    #:skip-filtered-directory? skip-filtered-directory?  \n    #:follow-links? follow-links?)  \n  →  (listof path?)\n  predicate : (path? . → . any/c)\n  start-path : (or/c path-string? #f) = #f\n  skip-filtered-directory? : any/c = #f\n  follow-links? : any/c = #f```\nTraverses the filesystem starting at start-path and creates a list of all files and directories for which predicate returns true. If start-path is #f, then the traversal starts from ([current-directory](#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29)). In the resulting list, each directory precedes its content."} {"text": "# 15.2 Filesystem\nThe predicate procedure is called with a single argument for each file or directory. If start-path is #f, the argument is a pathname string that is relative to the current directory. Otherwise, it is a path building on start-path. Consequently, supplying ([current-directory](#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29)) for start-path is different from supplying #f, because predicate receives complete paths in the former case and relative paths in the latter. Another difference is that predicate is not called for the current directory when start-path is #f.\nIf skip-filtered-directory? is true, then when predicate returns #f for a directory, the directory’s content is not traversed.\nIf follow-links? is true, the [find-files](#%28def._%28%28lib._racket%2Ffile..rkt%29._find-files%29%29) traversal follows links, and links are not included in the result. If follow-links? is #f, then links are not followed, and links are included in the result.\nIf start-path does not refer to an existing file or directory, then predicate will be called exactly once with start-path as the argument.\nThe [find-files](#%28def._%28%28lib._racket%2Ffile..rkt%29._find-files%29%29) procedure raises an exception if it encounters a directory for which [directory-list](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._directory-list%29%29) fails.\nChanged in version 6.3.0.11 of package base: Added the #:skip-filtered-directory? argument.\n> ```\n(pathlist-closure path-list\n   [ #:path-filter path-filter  \n    #:follow-links? follow-links?)  "} {"text": "# 15.2 Filesystem\n  →  (listof path?)\n  path-list : (listof path-string?)\n  path-filter : (or/c #f (path? . → . any/c)) = #f\n  follow-links? : any/c = #f\n```\nGiven a list of paths, either absolute or relative to the current directory, returns a list such that\n\n- if a nested path is given, all of its ancestors are also included in the result (but the same ancestor is not added twice);\n\n- if a path refers to directory, all of its descendants are also included in the result, except as omitted by path-filter;\n\n- ancestor directories appear before their descendants in the result list, as long as they are not misordered in the given path-list.\n\nIf path-filter is a procedure, then it is applied to each descendant of a directory. If path-filter returns #f, then the descendant (and any of its descendants, in the case of a subdirectory) are omitted from the result.\n\nIf follow-links? is true, then the traversal of directories and files follows links, and the link paths are not included in the result. If follow-links? is #f, then the result list includes paths to link and the links are not followed.\n\nChanged in version 6.3.0.11 of package base: Added the #:path-filter argument.\n\n> ```\n(fold-files proc\n    init-val        \n   [ start-path        \n    follow-links?)   →   any\n\n   proc   :   ( or/c ( path? ( or/c ' file ' dir ' link ) any/c\n> . → . any/c )\n> ( path? ( or/c ' file ' dir ' link ) any/c\n> . → . ( values any/c any/c ) ) )\n\n  init-val : any/c\n  start-path : (or/c path-string? #f) = #f\n  follow-links? : any/c = #t```\n\n\nTraverses the filesystem starting at start-path, calling proc on each discovered file, directory, and link. If start-path is #f, then the traversal starts from ([current-directory](#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29)).\n\nThe proc procedure is called with three arguments for each file, directory, or link:\n\n- If start-path is #f, the first argument is a pathname string that is relative to the current directory. Otherwise, the first argument is a pathname that starts with start-path. Consequently, supplying ([current-directory](#%28def._%28%28quote._~23~25kernel%29._current-directory%29%29)) for start-path is different from supplying #f, because proc receives complete paths in the former case and relative paths in the latter. Another difference is that proc is not called for the current directory when start-path is #f.\n\n- The second argument is a symbol, either 'file, 'dir, or 'link. The second argument can be 'link when follow-links? is #f, in which case the filesystem traversal does not follow links. If follow-links? is #t, then proc will only get a 'link as a second argument when it encounters a dangling symbolic link (one that does not resolve to an existing file or directory).\n\n- The third argument is the accumulated result. For the first call to proc, the third argument is init-val. For the second call to proc (if any), the third argument is the result from the first call, and so on. The result of the last call to proc is the result of [fold-files](#%28def._%28%28lib._racket%2Ffile..rkt%29._fold-files%29%29).\n\nThe proc argument is used in an analogous way to the procedure argument of [foldl](pairs.html#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._foldl%29%29), where its result is used as the new accumulated result. There is an exception for the case of a directory (when the second argument is 'dir): in this case the procedure may return two values, the second indicating whether the recursive scan should include the given directory or not. If it returns a single value, the directory is scanned. In the cases of files or links (when the second argument is 'file or 'link), a second value is permitted but ignored.\n\nIf the start-path is provided but no such path exists, or if paths disappear during the scan, then an exception is raised.\n\n> ```\n(parameter)\t→\n```"} {"text": "# 15.2 Filesystem\n(parameter)\t→```\nCreates the parent directory of the path specified by path, creating intermediate directories as necessary, and never failing if an ancestor of path exists already.\nIf path is a filesystem root or a relative path with a single path element, then no directory is created. Like [make-directory*](#%28def._%28%28lib._racket%2Ffile..rkt%29._make-directory%2A%29%29), if path is a relative path and the current directory does not exist, then [make-parent-directory*](#%28def._%28%28lib._racket%2Ffile..rkt%29._make-parent-directory%2A%29%29) will not create it.\nAdded in version 6.1.1.3 of package base.\n> ```\n(make-temporary-file [template\n    #:copy-from copy-from  \n    #:base-dir base-dir  \n    compat-copy-from  \n    compat-base-dir)  \n  →  (and/c path? complete-path?)\n  template : string? = \"rkttmp~a\"\n  copy-from : (or/c path-string? #f 'directory) = #f\n  base-dir : (or/c path-string? #f) = #f\n   compat-copy-from   :   (or/c path-string? #f 'directory)\n      =   copy-from\n  compat-base-dir : (or/c path-string? #f) = base-dir"} {"text": "# 15.2 Filesystem\n```\n(current-directory)\t→\t\n(-> and/c path? complete-path?)```\n\n\nLike [make-temporary-file](#%28def._%28%28lib._racket%2Ffile..rkt%29._make-temporary-file%29%29), but creates a directory, rather than a regular file.\n\nAs with [make-temporary-file](#%28def._%28%28lib._racket%2Ffile..rkt%29._make-temporary-file%29%29), if the template argument is not provided, a template string is generated from the source location of the call to [make-temporary-directory](#%28def._%28%28lib._racket%2Ffile..rkt%29._make-temporary-directory%29%29) when possible: the default is \"rkttmp\\~a\" only when no source location information is available.\n\nAdded in version 8.4.0.3 of package base.\n\n> ```\n(make-temporary-file* prefix\n    suffix  \n   [ #:copy-from copy-from  \n    #:base-dir base-dir)  \n\n  →  (and/c path? complete-path?)\n  prefix : bytes?\n  suffix : bytes?\n  copy-from : (or/c path-string? #f) = #f\n  base-dir : (or/c path-string? #f) = #f\n\n(make-temporary-directory*   prefix  \n    suffix  \n   [ #:base-dir base-dir)  \n\n  →  (and/c path? complete-path?)\n  prefix : bytes?\n  suffix : bytes?\n  base-dir : (or/c path-string? #f) = #f\n```"} {"text": "# 15.2 Filesystem\nLike make-temporary-file and make-temporary-directory, respectively, but, rather than using a template for format, the path is based on (bytes-append prefix generated suffix), where generated is a byte string chosen by the implementation to produce a unique path. If there is source location information for the callsite of make-temporary-file* or make-temporary-directory*, generated will incorporate that information. The resulting path is combined with base-dir as with make-temorary-file.\nAdded in version 8.4.0.3 of package base.\n> ```\n(call-with-atomic-output-file\n    file  \n    proc  \n   [ #:security-guard security-guard  \n    #:rename-fail-handler rename-fail-handler)  \n  →  any\n  file : path-string?\n  proc : (output-port? path? . → . any)\n  security-guard : (or/c #f security-guard?) = #f\n   rename-fail-handler   :   (or/c #f (exn:fail:filesystem? path? . → . any))\n      =   #f```\nOpens a temporary file for writing in the same directory as file, calls proc to write to the temporary file, and then atomically (except on Windows) moves the temporary file in place of file. The move simply uses [rename-file-or-directory](#%28def._%28%28quote._~23~25kernel%29._rename-file-or-directory%29%29) on Unix and Mac OS, and it uses [rename-file-or-directory](#%28def._%28%28quote._~23~25kernel%29._rename-file-or-directory%29%29) on Windows if rename-fail-handler is provided; otherwise, on Windows, the moves uses an extra rename step (see below) on Windows to avoid problems due to concurrent readers of file."} {"text": "# 15.2 Filesystem\nThe proc function is called with an output port for the temporary file, plus the path of the temporary file. The result of proc is the result of [call-with-atomic-output-file](#%28def._%28%28lib._racket%2Ffile..rkt%29._call-with-atomic-output-file%29%29).\nThe [call-with-atomic-output-file](#%28def._%28%28lib._racket%2Ffile..rkt%29._call-with-atomic-output-file%29%29) function arranges to delete temporary files on exceptions.\nWindows prevents programs from deleting or replacing files that are open, but it allows renaming of open files. Therefore, on Windows, [call-with-atomic-output-file](#%28def._%28%28lib._racket%2Ffile..rkt%29._call-with-atomic-output-file%29%29) by default creates a second temporary file extra-tmp-file, renames file to extra-tmp-file, renames the temporary file written by proc to file, and finally deletes extra-tmp-file. Since that process is not atomic, however, [rename-file-or-directory](#%28def._%28%28quote._~23~25kernel%29._rename-file-or-directory%29%29) is used if rename-fail-handler is provided, where [rename-file-or-directory](#%28def._%28%28quote._~23~25kernel%29._rename-file-or-directory%29%29) has some chance of being atomic, since that the source and destination of the moves will be in the same directory; any filesystem exception while attempting to rename the file is send to rename-fail-handler, which can re-[raise](exns.html#%28def._%28%28quote._~23~25kernel%29._raise%29%29) the exception or simply return to try again, perhaps after a delay. In addition to a filesystem exception, the rename-fail-handler procedure also receives the temporary file path to be moved to path. The rename-fail-handler argument is used only on Windows."} {"text": "# 15.2 Filesystem\nChanged in version 7.1.0.6 of package base: Added the #:rename-fail-handler argument.\n> ```\n(parameter)\t→\t\n(-> any)\n```\n(weakly)\t→\t\n(-> the default)```\n\n\nInstalls a set of preference values and writes all current values to the preference file designated by ([find-system-path](#%28def._%28%28quote._~23~25kernel%29._find-system-path%29%29) 'pref-file), or filename if it is supplied and not #f.\n\nThe names argument supplies the preference names, and vals must have the same length as names. Each element of vals must be an instance of a built-in data type whose [write](Writing.html#%28def._%28%28quote._~23~25kernel%29._write%29%29) output is [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29)able (i.e., the [print-unreadable](Writing.html#%28def._%28%28quote._~23~25kernel%29._print-unreadable%29%29) parameter is set to #f while writing preferences).\n\nCurrent preference values are read from the preference file before updating, and a write lock is held starting before the file read, and lasting until after the preferences file is updated. The lock is implemented by the existence of a file in the same directory as the preference file; see [preferences-lock-file-mode](#%28def._%28%28lib._racket%2Ffile..rkt%29._preferences-lock-file-mode%29%29) for more information. If the directory of the preferences file does not already exist, it is created.\n\nIf the write lock is already held, then locked-proc is called with a single argument: the path of the lock file. The default locked-proc (used when the locked-proc argument is #f) reports an error; an alternative thunk might wait a while and try again, or give the user the choice to delete the lock file (in case a previous update attempt encountered disaster and locks are implemented by the presence of the lock file).\n\nIf filename is #f or not supplied, and the preference file does not already exist, then values read from the \"defaults\" collection (if any) are written for preferences that are not mentioned in names.\n\n> ```\n(preferences-lock-file-mode)  →  (or/c 'exists 'file-lock)\n```"} {"text": "# 15.2 Filesystem\n(parameter)\t→\t\n(-> path-string? . → . any)```\nCreates a procedure suitable for use as the #:lock-there argument to [get-preference](#%28def._%28%28lib._racket%2Ffile..rkt%29._get-preference%29%29), where the name, failure-thunk, flush-mode, and filename are all passed on to [get-preference](#%28def._%28%28lib._racket%2Ffile..rkt%29._get-preference%29%29) by the result procedure to retry the preferences lookup.\nBefore calling [get-preference](#%28def._%28%28lib._racket%2Ffile..rkt%29._get-preference%29%29), the result procedure uses ([sleep](threads.html#%28def._%28%28quote._~23~25kernel%29._sleep%29%29) delay) to pause. Then, if ([*](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._%2A%29%29) 2 delay) is less than max-delay, the result procedure calls [make-handle-get-preference-locked](#%28def._%28%28lib._racket%2Ffile..rkt%29._make-handle-get-preference-locked%29%29) to generate a new retry procedure to pass to [get-preference](#%28def._%28%28lib._racket%2Ffile..rkt%29._get-preference%29%29), but with a delay of ([*](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._%2A%29%29) 2 delay). If ([*](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._%2A%29%29) 2 delay) is not less than max-delay, then [get-preference](#%28def._%28%28lib._racket%2Ffile..rkt%29._get-preference%29%29) is called with the given lock-there, instead.\n> ```\n(call-with-file-lock/timeout filename\n    kind        \n    thunk        \n    failure-thunk        \n   [ #:lock-file lock-file        \n    #:delay delay        \n    #:max-delay max-delay)   →   any"} {"text": "# 15.2 Filesystem\n  filename : (or/c path-string? #f)\n  kind : (or/c 'shared 'exclusive)\n  thunk : ( →  any)\n  failure-thunk : ( →  any)\n  lock-file : (or/c #f path-string?) = #f\n  delay : (and/c real? (not/c negative?)) = 0.01\n  max-delay : (and/c real? (not/c negative?)) = 0.2\n```\nObtains a lock for the filename lock-file and then calls thunk. The filename argument specifies a file path prefix that is used only to generate the lock filename when lock-file is #f. Specifically, when lock-file is #f, then call-with-file-lock/timeout uses make-lock-file-name to build the lock filename. If the lock file does not yet exist, it is created; beware that the lock file is not deleted by call-with-file-lock/timeout.\n\nWhen thunk returns, call-with-file-lock/timeout releases the lock, returning the result of thunk. The call-with-file-lock/timeout function will retry after delay seconds and continue retrying with exponential backoff until delay reaches max-delay. If call-with-file-lock/timeout fails to obtain the lock, failure-thunk is called in tail position. The kind argument specifies whether the lock is 'shared or 'exclusive in the sense of port-try-file-lock?.\n\nExamples:\n\n> ```racket\n> > ( call-with-file-lock/timeout filename ' exclusive ( lambda ( ) ( printf \"File is locked\\n\" ) ) ( lambda ( ) ( printf \"Failed to obtain lock for file\\n\" ) ) )\n> File is locked\n> > ( call-with-file-lock/timeout #f ' exclusive ( lambda ( ) ( call-with-file-lock/timeout filename ' shared ( lambda ( ) ( printf \"Shouldn't get here\\n\" ) ) ( lambda ( ) ( printf \"Failed to obtain lock for file\\n\" ) ) ) ) ( lambda ( ) ( printf \"Shouldn't get here either\\n\" ) ) #:lock-file ( make-lock-file-name filename ) )\n> Failed to obtain lock for file\n> ```\n\n> ```\n(make-lock-file-name path)  →  path?\n  path : (or/c path-string? path-for-some-system?)\n(make-lock-file-name dir name)  →  path?\n  dir : (or/c path-string? path-for-some-system?)\n  name : path-element?```\n\n\nCreates a lock filename by prepending \"\\_LOCK\" on Windows (i.e., when [cross-system-type](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=cross-system.html%23%2528def._%2528%2528lib._setup%252Fcross-system..rkt%2529._cross-system-type%2529%2529&version=8.18.0.13) reports 'windows) or \".LOCK\" on other platforms to the file portion of the path.\n\nExample:\n\n> ```racket\n> > ( make-lock-file-name \"/home/george/project/important-file\" )\n> #\n> ```\n\n>
\n\n

value

\n\n

[file-type-bits](#%28def._%28%28lib._racket%2Ffile..rkt%29._file-type-bits%29%29) : #o170000

\n\n

value

\n\n

[socket-type-bits](#%28def._%28%28lib._racket%2Ffile..rkt%29._socket-type-bits%29%29) : #o140000

\n\n

value

\n\n

[symbolic-link-type-bits](#%28def._%28%28lib._racket%2Ffile..rkt%29._symbolic-link-type-bits%29%29) : #o120000

\n\n

value

\n\n

[regular-file-type-bits](#%28def._%28%28lib._racket%2Ffile..rkt%29._regular-file-type-bits%29%29) : #o100000

\n\n

value

\n\n

[block-device-type-bits](#%28def._%28%28lib._racket%2Ffile..rkt%29._block-device-type-bits%29%29) : #o060000

\n\n

value

\n\n

[directory-type-bits](#%28def._%28%28lib._racket%2Ffile..rkt%29._directory-type-bits%29%29) : #o040000

\n\n

value

\n\n

[character-device-type-bits](#%28def._%28%28lib._racket%2Ffile..rkt%29._character-device-type-bits%29%29) : #o020000

\n\n

value

\n\n

[fifo-type-bits](#%28def._%28%28lib._racket%2Ffile..rkt%29._fifo-type-bits%29%29) : #o010000

\n\n

value

\n\n

[set-user-id-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._set-user-id-bit%29%29) : #o004000

\n\n

value

\n\n

[set-group-id-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._set-group-id-bit%29%29) : #o002000

\n\n

value

\n\n

[sticky-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._sticky-bit%29%29) : #o001000

\n\n

value

\n\n

[user-permission-bits](#%28def._%28%28lib._racket%2Ffile..rkt%29._user-permission-bits%29%29) : #o000700

\n\n

value

\n\n

[user-read-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._user-read-bit%29%29) : #o000400

\n\n

value

\n\n

[user-write-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._user-write-bit%29%29) : #o000200

\n\n

value

\n\n

[user-execute-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._user-execute-bit%29%29) : #o000100

\n\n

value

\n\n

[group-permission-bits](#%28def._%28%28lib._racket%2Ffile..rkt%29._group-permission-bits%29%29) : #o000070

\n\n

value

\n\n

[group-read-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._group-read-bit%29%29) : #o000040

\n\n

value

\n\n

[group-write-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._group-write-bit%29%29) : #o000020

\n\n

value

\n\n

[group-execute-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._group-execute-bit%29%29) : #o000010

\n\n

value

\n\n

[other-permission-bits](#%28def._%28%28lib._racket%2Ffile..rkt%29._other-permission-bits%29%29) : #o000007

\n\n

value

\n\n

[other-read-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._other-read-bit%29%29) : #o000004

\n\n

value

\n\n

[other-write-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._other-write-bit%29%29) : #o000002

\n\n

value

\n\n

[other-execute-bit](#%28def._%28%28lib._racket%2Ffile..rkt%29._other-execute-bit%29%29) : #o000001

\n\nConstants that are useful with [file-or-directory-permissions](#%28def._%28%28quote._~23~25kernel%29._file-or-directory-permissions%29%29), [file-or-directory-stat](#%28def._%28%28quote._~23~25kernel%29._file-or-directory-stat%29%29) and bitwise operations such as [bitwise-ior](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._bitwise-ior%29%29), and [bitwise-and](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._bitwise-and%29%29).\n\n------------------------------------------------------------------------\n\n# 15.3 Networking\n\n### 15.3 Networking\n\n| |\n|-------------------------------------------------------|\n|     [15.3.1 TCP](tcp.html) |\n|     [15.3.2 UDP](udp.html) |\n\n------------------------------------------------------------------------\n\n# 15.3.1 TCP\n\n#### 15.3.1 TCP\n\n| | |\n|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/tcp]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/tcp]() and [racket](index.html) libraries, but not [racket/base](index.html).\n\nFor information about TCP in general, see TCP/IP Illustrated, Volume 1 by W. Richard Stevens.\n\n> ```\n(tcp-listen port-no\n   [ max-allow-wait        \n    reuse?        \n    hostname)   →   tcp-listener?\n\n  port-no : listen-port-number?\n  max-allow-wait : exact-nonnegative-integer? = 4\n  reuse? : any/c = #f\n  hostname : (or/c string? #f) = #f\n```"} {"text": "# 15.2 Filesystem\nCreates a “listening” server on the local machine at the port number specified by port-no. If port-no is 0 the socket binds to an ephemeral port, which can be determined by calling tcp-addresses. The max-allow-wait argument determines the maximum number of client connections that can be waiting for acceptance. (When max-allow-wait clients are awaiting acceptance, no new client connections can be made.)\nIf the reuse? argument is true, then tcp-listen will create a listener even if the port is involved in a TIME_WAIT state. Such a use of reuse? defeats certain guarantees of the TCP protocol; see Stevens’s book for details. Furthermore, on many modern platforms, a true value for reuse? overrides TIME_WAIT only if the listener was previously created with a true value for reuse?.\nIf hostname is #f (the default), then the listener accepts connections to all of the listening machine’s addresses. Otherwise, the listener accepts connections only at the interface(s) associated with the given hostname. For example, providing \"127.0.0.1\" as hostname creates a listener that accepts only connections to \"127.0.0.1\" (the loopback interface) from the local machine."} {"text": "# 15.2 Filesystem\nRacket implements a listener with multiple sockets, if necessary, to accommodate multiple addresses with different protocol families. On Linux, if hostname maps to both IPv4 and IPv6 addresses, then the behavior depends on whether IPv6 is supported and IPv6 sockets can be configured to listen to only IPv6 connections: if IPv6 is not supported or IPv6 sockets are not configurable, then the IPv6 addresses are ignored; otherwise, each IPv6 listener accepts only IPv6 connections.\nOn variants of Unix and MacOS that support FD_CLOEXEC, a listener socket is given that flag so that it is not shared with a subprocess created by subprocess.\nThe return value of tcp-listen is a TCP listener. This value can be used in future calls to tcp-accept, tcp-accept-ready?, and tcp-close. Each new TCP listener value is placed into the management of the current custodian (see Custodians).\nIf the server cannot be started by tcp-listen, the exn:fail:network exception is raised.\nA TCP listener can be used as a synchronizable event (see Events). A TCP listener is ready for synchronization when tcp-accept would not block; the synchronization result of a TCP listener is the TCP listener itself.\nChanged in version 8.11.1.6 of package base: Changed to use FD_CLOEXEC where supported by the operating system.\n> ```\n(tcp-connect hostname\n    port-no        \n   [ local-hostname        \n    local-port-no)   →   input-port?   output-port?\n  hostname : string?\n  port-no : port-number?\n  local-hostname : (or/c string? #f) = #f\n  local-port-no : (or/c port-number? #f) = #f```"} {"text": "# 15.2 Filesystem\nAttempts to connect as a client to a listening server. The hostname argument is the server host’s Internet address name, and port-no is the port number where the server is listening.\n(If hostname is associated with multiple addresses, they are tried one at a time until a connection succeeds. The name \"localhost\" generally specifies the local machine.)\nThe optional local-hostname and local-port-no specify the client’s address and port. If both are #f (the default), the client’s address and port are selected automatically. If local-hostname is not #f, then local-port-no must be non-#f. If local-port-no is non-#f and local-hostname is #f, then the given port is used but the address is selected automatically.\nTwo values are returned by [tcp-connect](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-connect%29%29): an input port and an output port. Data can be received from the server through the input port and sent to the server through the output port. If the server is a Racket program, it can obtain ports to communicate to the client with [tcp-accept](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-accept%29%29). These ports are placed into the management of the current custodian (see [Custodians](custodians.html))."} {"text": "# 15.2 Filesystem\nInitially, the returned input port is block-buffered, and the returned output port is block-buffered. Change the buffer mode using [file-stream-buffer-mode](port-buffers.html#%28def._%28%28quote._~23~25kernel%29._file-stream-buffer-mode%29%29). When a TCP output port is block-buffered, Nagle’s algorithm is disabled for the port, which corresponds to setting the TCP_NODELAY socket option.\nBoth of the returned ports must be closed to terminate the TCP connection. When both ports are still open, closing the output port with [close-output-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._close-output-port%29%29) sends a TCP close to the server (which is seen as an end-of-file if the server reads the connection through a port). In contrast, [tcp-abandon-port](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-abandon-port%29%29) (see below) closes the output port, but does not send a TCP close until the input port is also closed.\nNote that the TCP protocol does not support a state where one end is willing to send but not read, nor does it include an automatic message when one end of a connection is fully closed. Instead, the other end of a connection discovers that one end is fully closed only as a response to sending data; in particular, some number of writes on the still-open end may appear to succeed, though writes will eventually produce an error."} {"text": "# 15.2 Filesystem\nOn variants of Unix and MacOS that support FD_CLOEXEC, a connection socket is given that flag so that it is not shared with a subprocess created by [subprocess](subprocess.html#%28def._%28%28quote._~23~25kernel%29._subprocess%29%29).\nIf a connection cannot be established by [tcp-connect](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-connect%29%29), the [exn:fail:network](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3anetwork%29%29) exception is raised.\nChanged in version 8.8.0.8 of package base: Changed block buffering to imply TCP_NODELAY. \nChanged in version 8.11.1.6: Changed to use FD_CLOEXEC where supported by the operating system.\n> ```\n(tcp-connect/enable-break hostname\n    port-no  \n   [ local-hostname]  \n    local-port-no)  \n  →   input-port?   output-port?\n  hostname : string?\n  port-no : port-number?\n  local-hostname : (or/c string? #f) = #f\n  local-port-no : (or/c port-number? #f)"} {"text": "# 15.2 Filesystem\n```\nLike tcp-connect, but breaking is enabled (see Breaks) while trying to connect. If breaking is disabled when tcp-connect/enable-break is called, then either ports are returned or the exn:break exception is raised, but not both.\n\n> ```\n(tcp-accept listener)   →   input-port?   output-port?\n\n  listener : tcp-listener?```\n\n\nAccepts a client connection for the server associated with listener. If no client connection is waiting on the listening port, the call to [tcp-accept](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-accept%29%29) will block. (See also [tcp-accept-ready?](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-accept-ready~3f%29%29).)\n\nTwo values are returned by [tcp-accept](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-accept%29%29): an input port and an output port. Data can be received from the client through the input port and sent to the client through the output port. These ports are placed into the management of the current custodian (see [Custodians](custodians.html)).\n\nIn terms of buffering and connection states, the ports act the same as ports from [tcp-connect](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-connect%29%29).\n\nOn variants of Unix and MacOS that support FD_CLOEXEC, an accepted socket is given that flag so that it is not shared with a subprocess created by [subprocess](subprocess.html#%28def._%28%28quote._~23~25kernel%29._subprocess%29%29).\n\nIf a connection cannot be accepted by [tcp-accept](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-accept%29%29), or if the listener has been closed, the [exn:fail:network](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3anetwork%29%29) exception is raised.\n\nChanged in version 8.11.1.6 of package base: Changed to use FD_CLOEXEC where supported by the operating system.\n\n> ```\n(tcp-accept/enable-break listener)   →   input-port?   output-port?\n\n  listener : tcp-listener?\n```"} {"text": "# 15.2 Filesystem\nLike tcp-accept, but breaking is enabled (see Breaks) while trying to accept a connection. If breaking is disabled when tcp-accept/enable-break is called, then either ports are returned or the exn:break exception is raised, but not both.\n> ```\n(tcp-accept-ready? listener)  →  boolean?\n  listener : tcp-listener?```\nTests whether an unaccepted client has connected to the server associated with listener. If a client is waiting, the return value is #t, otherwise it is #f. A client is accepted with the [tcp-accept](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-accept%29%29) procedure, which returns ports for communicating with the client and removes the client from the list of unaccepted clients.\nIf the listener has been closed, the [exn:fail:network](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3anetwork%29%29) exception is raised.\n> ```\n(parameter)\t→"} {"text": "# 15.2 Filesystem\n```\nShuts down the server associated with listener. All unaccepted clients receive an end-of-file from the server; connections to accepted clients are unaffected.\n\nIf the listener has already been closed, the exn:fail:network exception is raised.\n\nThe listener’s port number may not become immediately available for new listeners (with the default reuse? argument of tcp-listen). For further information, see Stevens’s explanation of the TIME_WAIT TCP state.\n\n> ```\n(tcp-listener? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a [TCP listener](#%28tech._tcp._listener%29) created by [tcp-listen](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-listen%29%29), #f otherwise.\n\n> ```\n(tcp-accept-evt listener)  →  evt?\n  listener : tcp-listener?\n```\n(parameter)\t→```\nLike [close-output-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._close-output-port%29%29) or [close-input-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._close-input-port%29%29) (depending on whether tcp-port is an input or output port), but if tcp-port is an output port and its associated input port is not yet closed, then the other end of the TCP connection does not receive a TCP close message until the input port is also closed.\nThe TCP protocol does not include a “no longer reading” state on connections, so [tcp-abandon-port](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-abandon-port%29%29) is equivalent to [close-input-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._close-input-port%29%29) on input [TCP ports](#%28tech._tcp._port%29).\n> ```"} {"text": "# 15.2 Filesystem\n(tcp-addresses tcp-port [port-numbers?)\n  →   ( or/c ( values string? string? )\n> ( values string? port-number?\n> string? listen-port-number? ) )\n  tcp-port : (or/c tcp-port? tcp-listener? udp?)\n  port-numbers? : any/c = #f\n```\nReturns two strings when port-numbers? is #f (the default). The first string is the Internet address for the local machine as viewed by the given TCP port’s connection, for the TCP listener, or the UDP socket. (When a machine serves multiple addresses, as it usually does if you count the loopback device, the result is connection-specific or listener-specific.) If a listener or UDP socket is given and it has no specific host, the first string result is \"0.0.0.0\". The second string is the Internet address for the other end of the connection, or always \"0.0.0.0\" for a listener or unconnected UDP socket.\n\nIf port-numbers? is true, then four results are returned: a string for the local machine’s address, an exact integer between 1 and 65535 for the local machine’s port number, a string for the remote machine’s address, and an exact integer between 1 and 65535 for the remote machine’s port number or 0 for a listener.\n\nIf the given port, listener, or socket has been closed, the exn:fail:network exception is raised.\n\n> ```\n(tcp-port? v)  →  boolean?\n  v : any/c```\n\n\nReturns #t if v is a TCP port—which is a port returned by [tcp-accept](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-accept%29%29), [tcp-connect](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-connect%29%29), [tcp-accept/enable-break](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-accept%2Fenable-break%29%29), or [tcp-connect/enable-break](#%28def._%28%28lib._racket%2Ftcp..rkt%29._tcp-connect%2Fenable-break%29%29)—#f otherwise.\n\n>
\n\n

value

\n\n

[port-number?](#%28def._%28%28lib._racket%2Ftcp..rkt%29._port-number~3f%29%29) : [contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract~3f%29%29)

\n\nEquivalent to ([integer-in](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._integer-in%29%29) 1 65535).\n\nAdded in version 6.3 of package base.\n\n>
\n\n

value

\n\n

[listen-port-number?](#%28def._%28%28lib._racket%2Ftcp..rkt%29._listen-port-number~3f%29%29) : [contract?](contract-utilities.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fguts..rkt%29._contract~3f%29%29)

\n\nEquivalent to ([integer-in](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._integer-in%29%29) 0 65535).\n\nAdded in version 6.3 of package base.\n\n------------------------------------------------------------------------\n\n# 15.3.2 UDP\n\n#### 15.3.2 UDP\n\n| | |\n|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/udp]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/udp]() and [racket](index.html) libraries, but not [racket/base](index.html).\n\nFor information about UDP in general, see TCP/IP Illustrated, Volume 1 by W. Richard Stevens.\n\n> ```\n(udp-open-socket [family-hostname\n    family-port-no)   →   udp?\n\n  family-hostname : (or/c string? #f) = #f\n  family-port-no : (or/c port-number? #f) = #f\n```"} {"text": "# 15.2 Filesystem\n(parameter)\t→\t\n(-> or/c string? #f)```\nBinds an unbound udp-socket to the local port number port-no. If port-no is 0 the udp-socket is bound to an ephemeral port, which can be determined by calling [udp-addresses](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-addresses%29%29).\nIf hostname-string is #f, then the socket accepts connections to all of the listening machine’s IP addresses at port-no. Otherwise, the socket accepts connections only at the IP address associated with the given name. For example, providing \"127.0.0.1\" as hostname-string typically creates a listener that accepts only connections to \"127.0.0.1\" from the local machine.\nA socket cannot receive datagrams until it is bound to a local address and port. If a socket is not bound before it is used with a sending procedure [udp-send](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-send%29%29), [udp-send-to](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-send-to%29%29), etc., the sending procedure binds the socket to a random local port. Similarly, if an event from [udp-send-evt](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-send-evt%29%29) or [udp-send-to-evt](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-send-to-evt%29%29) is chosen for a synchronization (see [Events](sync.html)), the socket is bound; if the event is not chosen, the socket may or may not become bound."} {"text": "# 15.2 Filesystem\nThe binding of a bound socket cannot be changed, with one exception: on some systems, if the socket is bound automatically when sending, if the socket is disconnected via [udp-connect!](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-connect%21%29%29), and if the socket is later used again in a send, then the later send may change the socket’s automatic binding.\nIf udp-socket is already bound or closed, the [exn:fail:network](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3anetwork%29%29) exception is raised.\nIf the reuse? argument is true, then [udp-bind!](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-bind%21%29%29) will set the SO_REUSEADDR socket option before binding, permitting the sharing of access to a UDP port between many processes on a single machine when using UDP multicast.\n> ```\n(parameter)\t→\t\n(-> or/c string? #f)"} {"text": "# 15.2 Filesystem\n```\n(parameter)\t→\t\n(-> bytes-length bstr)```\n\n\nSends ([subbytes](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._subbytes%29%29) [bytes](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._bytes%29%29) start-pos end-pos) as a datagram from the unconnected udp-socket to the socket at the remote machine hostname-address on the port port-no. The udp-socket need not be bound or connected; if it is not bound, [udp-send-to](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-send-to%29%29) binds it to a random local port. If the socket’s outgoing datagram queue is too full to support the send, [udp-send-to](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-send-to%29%29) blocks until the datagram can be queued.\n\nIf start-pos is greater than the length of bstr, or if end-pos is less than start-pos or greater than the length of bstr, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n\nIf udp-socket is closed or connected, the [exn:fail:network](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3anetwork%29%29) exception is raised.\n\n> ```\n(parameter)\t→\t\n(-> bytes-length bstr)\n```\nLike udp-send-to, except that udp-socket must be connected, and the datagram goes to the connection target. If udp-socket is closed or unconnected, the exn:fail:network exception is raised.\n> ```\n(udp-send-to* udp-socket\n    hostname        \n    port-no        \n    bstr        \n   [ start-pos        \n    end-pos)   →   boolean?"} {"text": "# 15.2 Filesystem\n  udp-socket : udp?\n  hostname : string?\n  port-no : port-number?\n  bstr : bytes?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : exact-nonnegative-integer? = (bytes-length bstr)```\nLike [udp-send-to](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-send-to%29%29), but never blocks; if the socket’s outgoing queue is too full to support the send, #f is returned, otherwise the datagram is queued and the result is #t.\n> ```\n(udp-send* udp-socket bstr [start-pos end-pos) → boolean?\n  udp-socket : udp?\n  bstr : bytes?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : exact-nonnegative-integer? = (bytes-length bstr)\n```\n(parameter)\t→\t\n(-> bytes-length bstr)```\n\n\nLike [udp-send-to](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-send-to%29%29), but breaking is enabled (see [Breaks](breakhandler.html)) while trying to send the datagram. If breaking is disabled when [udp-send-to/enable-break](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-send-to%2Fenable-break%29%29) is called, then either the datagram is sent or the [exn:break](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak%29%29) exception is raised, but not both.\n\n> ```\n(parameter)\t→\t\n(-> bytes-length bstr)\n```\nLike udp-send, except that breaks are enabled like udp-send-to/enable-break.\n> ```\n(udp-receive! udp-socket\n    bstr        \n   [ start-pos        \n    end-pos)   →   exact-nonnegative-integer?\nstring?\nport-number?"} {"text": "# 15.2 Filesystem\n  udp-socket : udp?\n  bstr : (and/c bytes? (not immutable?))\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : exact-nonnegative-integer? = (bytes-length bstr)```\nAccepts up to end-pos-start-pos bytes of udp-socket’s next incoming datagram into bstr, writing the datagram bytes starting at position start-pos within bstr. The udp-socket must be bound to a local address and port (but need not be connected). If no incoming datagram is immediately available, [udp-receive!](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-receive%21%29%29) blocks until one is available.\nThree values are returned: the number of received bytes (between 0 and end-pos-start-pos, a hostname string indicating the source address of the datagram, and an integer indicating the source port of the datagram. If the received datagram is longer than end-pos-start-pos bytes, the remainder is discarded.\nIf start-pos is greater than the length of bstr, or if end-pos is less than start-pos or greater than the length of bstr, the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised.\n> ```\n(udp-receive!* udp-socket\n    bstr  \n   [ start-pos  \n    end-pos)  \n  →   (or/c exact-nonnegative-integer? #f)\n(or/c string? #f)\n(or/c port-number? #f)\n  udp-socket : udp?\n  bstr : (and/c bytes? (not immutable?))\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : exact-nonnegative-integer? = (bytes-length bstr)"} {"text": "# 15.2 Filesystem\n```\nLike udp-receive!, except that it never blocks. If no datagram is available, the three result values are all #f.\n\n> ```\n(udp-receive!/enable-break udp-socket\n    bstr  \n   [ start-pos  \n    end-pos)  \n\n  →   exact-nonnegative-integer?\nstring?\nport-number?\n\n  udp-socket : udp?\n  bstr : (and/c bytes? (not immutable?))\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : exact-nonnegative-integer? = (bytes-length bstr)```\n\n\nLike [udp-receive!](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-receive%21%29%29), but breaking is enabled (see [Breaks](breakhandler.html)) while trying to receive the datagram. If breaking is disabled when [udp-receive!/enable-break](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-receive%21%2Fenable-break%29%29) is called, then either a datagram is received or the [exn:break](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3abreak%29%29) exception is raised, but not both.\n\n> ```\n(parameter)\t→\n```\n(SO_RCVBUF)\t→```\nCloses udp-socket, discarding unreceived datagrams. If the socket is already closed, the [exn:fail:network](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3anetwork%29%29) exception is raised.\n> ```\n(udp? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a socket created by udp-open-socket, #f otherwise.\n\n> ```\n(udp-bound? udp-socket)  →  boolean?\n  udp-socket : udp?```\n\n\nReturns #t if udp-socket is bound to a local address and port, #f otherwise.\n\n> ```\n(udp-connected? udp-socket)  →  boolean?\n  udp-socket : udp?\n```"} {"text": "# 15.2 Filesystem\nReturns #t if udp-socket is connected to a remote address and port, #f otherwise.\n> ```\n(udp-send-ready-evt udp-socket)  →  evt?\n  udp-socket : udp?\n```\n\n\nReturns a [synchronizable event](sync.html#%28tech._synchronizable._event%29) (see [Events](sync.html)) that is in a blocking state when [udp-send-to](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-send-to%29%29) on udp-socket would block. The [synchronization result](sync.html#%28tech._synchronization._result%29) is the event itself.\n\n> ```\n(udp-receive-ready-evt udp-socket)  →  evt?\n  udp-socket : udp?\n```\nReturns a synchronizable event (see Events) that is in a blocking state when udp-receive! on udp-socket would block. The synchronization result is the event itself.\n> ```\n(udp-send-to-evt udp-socket\n    hostname        \n    port-no        \n    bstr        \n   [ start-pos        \n    end-pos)   →   evt?\n  udp-socket : udp?\n  hostname : string?\n  port-no : port-number?\n  bstr : bytes?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : exact-nonnegative-integer? = (bytes-length bstr)```"} {"text": "# 15.2 Filesystem\nReturns a [synchronizable event](sync.html#%28tech._synchronizable._event%29). The event is in a blocking state when [udp-send-to](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-send-to%29%29) on udp-socket would block. Otherwise, if the event is chosen in a synchronization, data is sent as for ([udp-send-to](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-send-to%29%29) udp-socket hostname-address port-no bstr start-pos end-pos), and the synchronization result is [#](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=void_undefined.html&version=8.18.0.13). (No bytes are sent if the event is not chosen.)\n> ```\n(udp-send-evt udp-socket\n    bstr        \n   [ start-pos        \n    end-pos)   →   evt?\n  udp-socket : udp?\n  bstr : bytes?\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : exact-nonnegative-integer? = (bytes-length bstr)"} {"text": "# 15.2 Filesystem\n```\nReturns a synchronizable event. The event is ready for synchronization when udp-send on udp-socket would not block. Otherwise, if the event is chosen in a synchronization, data is sent as for (udp-send-to udp-socket bstr start-pos end-pos), and the synchronization result is #. (No bytes are sent if the event is not chosen.) If udp-socket is closed or unconnected, the exn:fail:network exception is raised during a synchronization attempt.\n\n> ```\n(udp-receive!-evt udp-socket\n    bstr        \n   [ start-pos        \n    end-pos)   →   evt?\n\n  udp-socket : udp?\n  bstr : (and/c bytes? (not immutable?))\n  start-pos : exact-nonnegative-integer? = 0\n  end-pos : exact-nonnegative-integer? = (bytes-length bstr)```\n\n\nReturns a [synchronizable event](sync.html#%28tech._synchronizable._event%29). The event is [ready for synchronization](sync.html#%28tech._ready._for._synchronization%29) when udp-receive on udp-socket would not block. Otherwise, if the event is chosen in a synchronization, data is received into bstr as for ([udp-receive!](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-receive%21%29%29) udp-socket [bytes](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._bytes%29%29) start-pos end-pos), and the [synchronization result](sync.html#%28tech._synchronization._result%29) is a list of three values, corresponding to the three results from [udp-receive!](#%28def._%28%28lib._racket%2Fudp..rkt%29._udp-receive%21%29%29). (No bytes are received and the bstr content is not modified if the event is not chosen.)\n\n> ```\n(udp-addresses udp-port [port-numbers?)\n  →   ( or/c ( values string? string? )\n> ( values string? listen-port-number?\n> string? listen-port-number? ) )\n\n  udp-port : udp?\n  port-numbers? : any/c = #f\n```"} {"text": "# 15.2 Filesystem\n(parameter)\t→\t\n(-> udp-ttl udp-socket)```\n> > > Time-to-live settings correspond to the IP_TTL setting of the socket.\nSets or retrieves the current time-to-live setting of udp-socket.\nAdded in version 7.5.0.5 of package base.\n> ```\n(parameter)\t→\t\n(-> or/c string? #f)\n```\n(parameter)\t→\t\n(-> udp-multicast-set-interface! udp-socket\n hostname)```\n\n\nRetrieves or sets the interface that udp-socket uses to send (not receive) multicast datagrams. If the result or hostname is either #f or \"0.0.0.0\", the kernel automatically selects an interface when a multicast datagram is sent.\n\n> ```\n(parameter)\t→\t\n(-> udp-multicast-loopback? udp-socket)\n```\n(parameter)\t→\t\n(-> udp-multicast-ttl udp-socket)```\n> > > Time-to-live settings correspond to the IP_MULTICAST_TTL setting of the socket.\nSets or retrieves the current time-to-live setting of udp-socket.\nThe time-to-live setting should almost always be 1, and it is important that this number is as low as possible. In fact, these functions seldom should be used at all. See the documentation for your platform’s IP stack.\n------------------------------------------------------------------------"} {"text": "# 15.4 Processes"} {"text": "### 15.4 Processes\n> ```\n(subprocess stdout\n    stdin  \n    stderr  \n   [ group]  \n    command  \n    arg ...)  \n  →   subprocess?\n(or/c (and/c input-port? file-stream-port?) #f)\n(or/c (and/c output-port? file-stream-port?) #f)\n(or/c (and/c input-port? file-stream-port?) #f)\n  stdout : (or/c (and/c output-port? file-stream-port?) #f)\n  stdin : (or/c (and/c input-port? file-stream-port?) #f)\n  stderr : (or/c (and/c output-port? file-stream-port?) #f 'stdout)\n   group   :   (or/c #f 'new subprocess)\n      =   (and (subprocess-group-enabled) 'new)\n  command : path-string?\n  arg : (or/c path? string-no-nuls? bytes-no-nuls?)\n(subprocess   stdout  \n    stdin  \n    stderr  \n   [ group]  \n    command  \n    exact  \n    arg)  \n  →   subprocess?\n(or/c (and/c input-port? file-stream-port?) #f)\n(or/c (and/c output-port? file-stream-port?) #f)\n(or/c (and/c input-port? file-stream-port?) #f)\n  stdout : (or/c (and/c output-port? file-stream-port?) #f)\n  stdin : (or/c (and/c input-port? file-stream-port?) #f)\n  stderr : (or/c (and/c output-port? file-stream-port?) #f)\n   group   :   (or/c #f 'new subprocess)\n      =   (and (subprocess-group-enabled) 'new)\n  command : path-string?\n  exact : 'exact\n  arg : string?"} {"text": "# 15.4 Processes\n```\n(parameter)\t→\t\n(-> printf \"stderr:\\n~a\" (port → string err))```\n\n\nBlocks until the process represented by subproc terminates. The subproc value also can be used with [sync](sync.html#%28def._%28%28quote._~23~25kernel%29._sync%29%29) and [sync/timeout](sync.html#%28def._%28%28quote._~23~25kernel%29._sync%2Ftimeout%29%29).\n\n> ```\n(subprocess-status subproc)   →   ( or/c ' running\n> exact-nonnegative-integer? )\n\n  subproc : subprocess?\n```\n(parameter)\t→```\nTerminates the subprocess represented by subproc. The precise action depends on whether force? is true, whether the process was created in its own group by setting the [subprocess-group-enabled](#%28def._%28%28quote._~23~25kernel%29._subprocess-group-enabled%29%29) parameter to a true value, and the current platform:\n- force? is true, not a group, all platforms: Terminates the process if the process still running.\n- force? is false, not a group, on Unix or Mac OS: Sends the process an interrupt signal instead of a kill signal.\n- force? is false, not a group, on Windows: No action is taken."} {"text": "# 15.4 Processes\n- force? is true, a group, on Unix or Mac OS: Terminates all processes in the group, but only if [subprocess-status](#%28def._%28%28quote._~23~25kernel%29._subprocess-status%29%29) has never produced a non-'running result for the subprocess and only if functions like [subprocess-wait](#%28def._%28%28quote._~23~25kernel%29._subprocess-wait%29%29) and [sync](sync.html#%28def._%28%28quote._~23~25kernel%29._sync%29%29) have not detected the subprocess’s completion. Otherwise, no action is taken (because the immediate process is known to have terminated while the continued existence of the group is unknown).\n- force? is true, a group, on Windows: Terminates the process if the process still running.\n- force? is false, a group, on Unix or Mac OS: The same as when force? is #t, but when the group is sent a signal, it is an interrupt signal instead of a kill signal.\n- force? is false, a group, on Windows: All processes in the group receive a CTRL-BREAK signal (independent of whether the immediate subprocess has terminated).\nIf an error occurs during termination, the [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) exception is raised.\n> ```\n(subprocess-pid subproc)  →  exact-nonnegative-integer?\n  subproc : subprocess?\n```\n\n\nReturns the operating system’s numerical ID (if any) for the process represented by subproc. The result is valid only as long as the process is running.\n\n> ```\n(subprocess? v)  →  boolean?\n  v : any/c\n```\nReturns #t if v is a subprocess value, #f otherwise.\n> ```"} {"text": "# 15.4 Processes\n(current-subprocess-custodian-mode)\t→\t\n(-> or/c #f 'kill 'interrupt)\n(current-subprocess-custodian-mode mode) → void?\n mode\t:\t\n(-> or/c #f 'kill 'interrupt)\n```\n(subprocess-group-enabled)\t→\t\n(-> subprocess-group-enabled on?)```\n\n\nA [parameter](eval-model.html#%28tech._parameter%29) that determines whether a subprocess is created as a new process group by default. See [subprocess](#%28def._%28%28quote._~23~25kernel%29._subprocess%29%29) and [subprocess-kill](#%28def._%28%28quote._~23~25kernel%29._subprocess-kill%29%29) for more information.\n\n> ```\n(current-subprocess-keep-file-descriptors)\t→\t\n(-> or/c 'inherited 'all '())\n(current-subprocess-keep-file-descriptors keeps) → void?\n keeps\t:\t\n(-> or/c 'inherited 'all '())\n```\n(parameter)\t→\t\n(-> or/c string? #f)```\nPerforms the action specified by verb on target in Windows. For platforms other than Windows, the [exn:fail:unsupported](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aunsupported%29%29) exception is raised.\nFor example,\n> ```racket\n> ( shell-execute #f \"http://racket-lang.org\" \"\"\n> ( current-directory ) ' sw_shownormal )\n> ```\nOpens the Racket home page in a browser window.\nThe verb can be #f, in which case the operating system will use a default verb. Common verbs include \"open\", \"edit\", \"find\", \"explore\", and \"print\".\nThe target is the target for the action, usually a filename path. The file could be executable, or it could be a file with a recognized extension that can be handled by an installed application."} {"text": "# 15.4 Processes\nThe parameters argument is passed on to the system to perform the action. For example, in the case of opening an executable, the parameters is used as the command line (after the executable name).\nThe dir is used as the current directory when performing the action.\nThe show-mode sets the display mode for a Window affected by the action. It must be one of the following symbols; the description of each symbol’s meaning is taken from the Windows API documentation.\n- 'sw_hide or 'SW_HIDE — Hides the window and activates another window.\n- 'sw_maximize or 'SW_MAXIMIZE — Maximizes the window.\n- 'sw_minimize or 'SW_MINIMIZE — Minimizes the window and activates the next top-level window in the z-order.\n- 'sw_restore or 'SW_RESTORE — Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position.\n- 'sw_show or 'SW_SHOW — Activates the window and displays it in its current size and position.\n- 'sw_showdefault or 'SW_SHOWDEFAULT — Uses a default.\n- 'sw_showmaximized or 'SW_SHOWMAXIMIZED — Activates the window and displays it as a maximized window.\n- 'sw_showminimized or 'SW_SHOWMINIMIZED — Activates the window and displays it as a minimized window.\n- 'sw_showminnoactive or 'SW_SHOWMINNOACTIVE — Displays the window as a minimized window. The active window remains active.\n- 'sw_showna or 'SW_SHOWNA — Displays the window in its current state. The active window remains active."} {"text": "# 15.4 Processes\n- 'sw_shownoactivate or 'SW_SHOWNOACTIVATE — Displays a window in its most recent size and position. The active window remains active.\n- 'sw_shownormal or 'SW_SHOWNORMAL — Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position.\nIf the action fails, the [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) exception is raised. If the action succeeds, the result is #f.\nIn future versions of Racket, the result may be a subprocess value if the operating system did returns a process handle (but if a subprocess value is returned, its process ID will be 0 instead of the real process ID)."} {"text": "#### 15.4.1 Simple Subprocesses\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/system](#%28mod-path._racket%2Fsystem%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/system](#%28mod-path._racket%2Fsystem%29) and [racket](index.html) libraries, but not [racket/base](index.html).\n> ```\n(system command [#:set-pwd? set-pwd?) → boolean?\n  command : (or/c string-no-nuls? bytes-no-nuls?)\n  set-pwd? : any/c = (member (system-type) '(unix macosx))"} {"text": "# 15.4 Processes\n```\n(current-directory)\t→\t\n(-> or/c path? string-no-nuls? bytes-no-nuls?)```\n\n\nLike [system](#%28def._%28%28lib._racket%2Fsystem..rkt%29._system%29%29), except that command is a filename that is executed directly (instead of through a shell command; see [find-executable-path](Filesystem.html#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._find-executable-path%29%29) for locating an executable based on the PATH environment variable), and the args are the arguments. The executed file is passed the specified string arguments (which must contain no nul characters).\n\nOn Windows, the first argument after command can be 'exact, and the final arg is a complete command line. See [subprocess](#%28def._%28%28quote._~23~25kernel%29._subprocess%29%29) for details and for a specific warning about using a command that refers to a \".bat\" or \".cmd\" file.\n\n> ```\n(system/exit-code command\n   [ #:set-pwd? set-pwd?)   →   byte?\n\n  command : (or/c string-no-nuls? bytes-no-nuls?)\n  set-pwd? : any/c = (member (system-type) '(unix macosx))\n```\nLike system, except that the result is the exit code returned by the subprocess. A 0 result normally indicates success.\n> ```\n(system*/exit-code command\n    arg ...        \n   [ #:set-pwd? set-pwd?)   →   byte?\n  command : path-string?\n  arg : (or/c path? string-no-nuls? bytes-no-nuls?)\n  set-pwd? : any/c = (member (system-type) '(unix macosx))\n(system*/exit-code   command        \n    exact        \n    arg        \n   [ #:set-pwd? set-pwd?)   →   byte?"} {"text": "# 15.4 Processes\n  command : path-string?\n  exact : 'exact\n  arg : string?\n  set-pwd? : any/c = (member (system-type) '(unix macosx))```\nLike [system*](#%28def._%28%28lib._racket%2Fsystem..rkt%29._system%2A%29%29), but returns the exit code like [system/exit-code](#%28def._%28%28lib._racket%2Fsystem..rkt%29._system%2Fexit-code%29%29).\n> ```\n(process command [#:set-pwd? set-pwd?)\n  →   ( list input-port?\n> output-port?\n> exact-nonnegative-integer?\n> input-port?\n> ( ( or/c ' status ' wait ' interrupt ' kill ) . → . any ) )\n  command : (or/c string-no-nuls? bytes-no-nuls?)\n  set-pwd? : any/c = (member (system-type) '(unix macosx))"} {"text": "# 15.4 Processes\n```\n(system-type)\t→\t\n(-> or/c path? string-no-nuls? bytes-no-nuls?)```\n\n\nLike [process](#%28def._%28%28lib._racket%2Fsystem..rkt%29._process%29%29), except that command is a filename that is executed directly like [system*](#%28def._%28%28lib._racket%2Fsystem..rkt%29._system%2A%29%29), and the args are the arguments.\n\nOn Windows, as for [system*](#%28def._%28%28lib._racket%2Fsystem..rkt%29._system%2A%29%29), the first arg can be replaced with 'exact. See also [subprocess](#%28def._%28%28quote._~23~25kernel%29._subprocess%29%29) for a specific warning about using a command that refers to a \".bat\" or \".cmd\" file.\n\n> ```\n(process/ports out\n    in        \n    error-out        \n    command        \n   [ #:set-pwd? set-pwd?)   →   list?\n\n  out : (or/c #f output-port?)\n  in : (or/c #f input-port?)\n  error-out : (or/c #f output-port? 'stdout)\n  command : (or/c path? string-no-nuls? bytes-no-nuls?)\n  set-pwd? : any/c = (member (system-type) '(unix macosx))\n```\nLike process, except that out is used for the process’s standard output, in is used for the process’s standard input, and error-out is used for the process’s standard error. Any of the ports can be #f, in which case a system pipe is created and returned, as in process. If error-out is 'stdout, then standard error is redirected to standard output. For each port or 'stdout that is provided, no pipe is created, and the corresponding value in the returned list is #f.\n> ```\n(process*/ports out\n    in        \n    error-out        \n    command        \n    arg ...        \n   [ #:set-pwd? set-pwd?)   →   list?"} {"text": "# 15.4 Processes\n  out : (or/c #f output-port?)\n  in : (or/c #f input-port?)\n  error-out : (or/c #f output-port? 'stdout)\n  command : path-string?\n  arg : (or/c path? string-no-nuls? bytes-no-nuls?)\n  set-pwd? : any/c = (member (system-type) '(unix macosx))\n(process*/ports   out        \n    in        \n    error-out        \n    command        \n    exact        \n    arg        \n   [ #:set-pwd? set-pwd?)   →   list?\n  out : (or/c #f output-port?)\n  in : (or/c #f input-port?)\n  error-out : (or/c #f output-port? 'stdout)\n  command : path-string?\n  exact : 'exact\n  arg : string?\n  set-pwd? : any/c = (member (system-type) '(unix macosx))```\nLike [process*](#%28def._%28%28lib._racket%2Fsystem..rkt%29._process%2A%29%29), but with the port handling of [process/ports](#%28def._%28%28lib._racket%2Fsystem..rkt%29._process%2Fports%29%29).\nThe contracts of [system](#%28def._%28%28lib._racket%2Fsystem..rkt%29._system%29%29) and related functions may signal a contract error with references to the following functions.\n> ```\n(string-no-nuls? x)  →  boolean?\n  x : any/c\n```\n\n\nEnsures that x is a string and does not contain \"\\\\u0000\".\n\n> ```\n(bytes-no-nuls? x)  →  boolean?\n  x : any/c\n```\nEnsures that x is a byte-string and does not contain #\"\\\\0\".\n------------------------------------------------------------------------"} {"text": "# 15.5 Logging"} {"text": "### 15.5 Logging\nA logger accepts events that contain information to be logged for interested parties. A log receiver represents an interested party that receives logged events asynchronously. Each event has a topic and level of detail, and a [log receiver](#%28tech._log._receiver%29) subscribes to logging events at a certain level of detail (and lower) for a specific topic or for all topics. The levels, in increasing order of detail, are 'none, 'fatal, 'error, 'warning, 'info, and 'debug. The 'none level is intended for specifying receivers, and messages logged at that level are never sent to subscribers.\nTo help organize logged events, a [logger](#%28tech._logger%29) can have a default topic and/or a parent logger. Every event reported to a logger is propagated to its parent (if any), and the event message is prefixed with the logger’s topic (if any) if the message doesn’t already have a topic. Furthermore, events that are propagated from a logger to its parent can be filtered by level and topic."} {"text": "# 15.5 Logging\nOn start-up, Racket creates an initial logger that is used to record events from the core run-time system. For example, a 'debug event is reported for each garbage collection (see [Garbage Collection](eval-model.html#%28part._gc-model%29)). For this initial logger, two log receivers are also created: one that writes events to the process’s original error output port, and one that writes events to the system log. The level of written events in each case is system-specific, and the default can be changed through command-line flags (see [Command Line](running-sa.html#%28part._mz-cmdline%29)) or through environment variables:\n- If the PLTSTDERR environment variable is defined and is not overridden by a command-line flag, it determines the level of the [log receiver](#%28tech._log._receiver%29) that propagates events to the original error port.\n The environment variable’s value can be a ‹level›: none, fatal, error, warning, info, or debug (from low detail to high detail); all events at the corresponding level of detail or lower are printed. After an initial ‹level›, the value can contain whitespace-separated specifications of the form ‹level›@‹topic›, which prints events whose topics match ‹topic› only at the given ‹level› or higher (where a ‹topic› contains any character other than whitespace or @). Leading and trailing whitespace is ignored. For example, the value \"error debug@GC\" prints all events at the 'error level and higher, but prints events for the topic 'GC at the 'debug level and higher (which includes all levels).\n The default is \"error\"."} {"text": "# 15.5 Logging\n- If the PLTSTDOUT environment variable is defined and is not overridden by a command-line flag, it determines the level of the [log receiver](#%28tech._log._receiver%29) that propagates events to the original output port. The possible values are the same as for PLTSTDERR.\n The default is \"none\".\n- If the PLTSYSLOG environment variable is defined and is not overridden by a command-line flag, it determines the level of the [log receiver](#%28tech._log._receiver%29) that propagates events to the system log. The possible values are the same as for PLTSTDERR.\n The default is \"none\" for Unix or \"error\" for Windows and Mac OS.\nThe [current-logger](#%28def._%28%28quote._~23~25kernel%29._current-logger%29%29) [parameter](eval-model.html#%28tech._parameter%29) determines the current logger that is used by forms such as [log-warning](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._log-warning%29%29). On start-up, the initial value of this parameter is the initial logger. The run-time system sometimes uses the current logger to report events. For example, the bytecode compiler sometimes reports 'warning events when it detects an expression that would produce a run-time error if evaluated.\nChanged in version 6.6.0.2 of package base: Prior to version 6.6.0.2, parsing of PLTSTDERR and PLTSYSLOG was very strict. Leading and trailing whitespace was forbidden, and anything other than exactly one space character separating two specifications was rejected. \nChanged in version 6.90.0.17: Added PLTSTDOUT."} {"text": "#### 15.5.1 Creating Loggers\n> ```\n(logger? v)  →  boolean?\n  v : any/c\n```\n(parameter)\t→\t\n(-> or/c symbol? #f)```\n\n\nCreates a new [logger](#%28tech._logger%29) with an optional topic and parent.\n\nThe optional propagate-level and propagate-topic arguments constrain the events that are propagated from the new logger to parent (when parent is not #f) in the same way that events are described for a log receiver in [make-log-receiver](#%28def._%28%28quote._~23~25kernel%29._make-log-receiver%29%29). By default, all events are propagated to parent.\n\nChanged in version 6.1.1.3 of package base: Removed an optional argument to specify a notification callback, and added propagate-level and propagate-topic constraints for events to propagate.\n\n> ```\n(parameter)\t→\t\n(-> or/c symbol? #f)\n```\n(current-logger)\t→\t\n(-> current-logger logger)\n(current-logger logger) → void?\n logger\t:\t\n(-> current-logger logger)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the [current logger](#%28tech._current._logger%29).\n>
\n

syntax

"} {"text": "# 15.5 Logging\n

([define-logger](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._define-logger%29%29) id maybe-parent)

 
maybe-parent = 
  | #:parent parent-expr
 
  parent-expr : ([or/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._or%2Fc%29%29) [logger?](#%28def._%28%28quote._~23~25kernel%29._logger~3f%29%29) #f)
"} {"text": "# 15.5 Logging\nDefines log-id-fatal, log-id-error, log-id-warning, log-id-info, and log-id-debug as forms like [log-fatal](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._log-fatal%29%29), [log-error](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._log-error%29%29),[log-warning](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._log-warning%29%29), [log-info](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._log-info%29%29), and [log-debug](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._log-debug%29%29). The [define-logger](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._define-logger%29%29) form also defines id-logger, which is a logger with default topic 'id that is a child of the result of parent-expr (if parent-expr does not produce #f), or of ([current-logger](#%28def._%28%28quote._~23~25kernel%29._current-logger%29%29)) if parent-expr not provided; the log-id-fatal, etc. forms use this new logger. The new logger is created when [define-logger](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._define-logger%29%29) is evaluated.\nChanged in version 7.1.0.9 of package base: Added the #:parent option."} {"text": "#### 15.5.2 Logging Events\n> ```\n(parameter)\t→\t\n(-> or/c symbol? #f)\n```\n(parameter)\t→\t\n(-> or/c symbol? #f)```\n\n\nReports whether any [log receiver](#%28tech._log._receiver%29) attached to logger or one of its ancestors is interested in level events (or potentially lower) for topic. If topic is #f, the result indicates whether a [log receiver](#%28tech._log._receiver%29) is interested in events at level for any topic. If level is 'none, the result is always #f.\n\nUse this function to avoid work generating an event for [log-message](#%28def._%28%28quote._~23~25kernel%29._log-message%29%29) if no receiver is interested in the information; this shortcut is built into [log-fatal](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._log-fatal%29%29), [log-error](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._log-error%29%29), [log-warning](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._log-warning%29%29), [log-info](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._log-info%29%29), [log-debug](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._log-debug%29%29), and forms bound by [define-logger](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._define-logger%29%29), however, so it should not be used with those forms.\n\nThe result of this function can change if a garbage collection determines that a log receiver is no longer accessible (and therefore that any event information it receives will never become accessible).\n\nChanged in version 6.1.1.3 of package base: Added the topic argument. \nChanged in version 8.10.0.5: Changed the result for 'none to be consistently #f.\n\n> ```\n(parameter)\t→\t\n(-> or/c log-level/c #f)\n```"} {"text": "# 15.5 Logging\n(parameter)\t→\t\n(-> list/c (or/c #f log-level/c)\n (or/c #f symbol?)\n ... ...)```\nSummarizes the possible results of [log-max-level](#%28def._%28%28quote._~23~25kernel%29._log-max-level%29%29) on all possible [interned](reader.html#%28tech._interned%29) symbols. The result list contains a sequence of symbols and #f, where the first, third, etc., list element corresponds to a level, and the second, fourth, etc., list element indicates a corresponding topic. The level is the result that [log-max-level](#%28def._%28%28quote._~23~25kernel%29._log-max-level%29%29) would produce for the topic, where the level for the #f topic (which is always present in the result list) indicates the result for any [interned](reader.html#%28tech._interned%29)-symbol topic that does not appear in the list.\nThe result is suitable as a sequence of arguments to [make-log-receiver](#%28def._%28%28quote._~23~25kernel%29._make-log-receiver%29%29) (after a [logger](#%28tech._logger%29) argument) to create a new receiver for events that currently have receivers in logger.\nAdded in version 6.1.1.4 of package base.\n> ```\n(log-level-evt logger)  →  evt?\n  logger : logger?\n```\n(parameter)\t→```\n\n\nReturns #t if v is a [log receiver](#%28tech._log._receiver%29), #f otherwise.\n\n> ```\n(parameter)\t→\t\n(-> or/c #f symbol?)\n```\nCreates a log receiver to receive events of detail level and lower as reported to logger and its descendants, as long as either topic is #f or the event’s topic matches topic."} {"text": "# 15.5 Logging\nA log receiver is a synchronizable event. It becomes ready for synchronization when a logging event is received, so use sync to receive a logged event. The log receiver’s synchronization result is an immutable vector containing four values: the level of the event as a symbol, an immutable string for the event message, an arbitrary value that was supplied as the last argument to log-message when the event was logged, and a symbol or #f for the event topic.\nMultiple pairs of level and topic can be provided to indicate different specific levels for different topics (where topic defaults to #f only for the last given level). A level for a #f topic applies only to events whose topic does not match any other provided topic. If the same topic is provided multiple times, the level provided with the last instance in the argument list takes precedence."} {"text": "#### 15.5.4 Additional Logging Functions\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  (require racket/logging) |  package: base |\nThe bindings documented in this section are provided by the racket/logging library, not racket/base or racket.\n> ```\n(log-level/c v) → boolean?\n  v : any/c```\nReturns #t if v is a valid logging level ('none, 'fatal, 'error, 'warning, 'info, or 'debug), #f otherwise.\nAdded in version 6.3 of package base.\n> ```\n(parameter)\t→\t\n(-> (vector/c\n log-level/c\n string?\n any/c\n (or/c symbol? #f))\n any)"} {"text": "# 15.5 Logging\n```\n(parameter)\t→\t\n(-> any)```\n\n\nRuns proc, outputting any logging that the execution of proc emits to [current-logger](#%28def._%28%28quote._~23~25kernel%29._current-logger%29%29) at the specified levels and topics. If #:logger is specified, intercepts events sent to that logger, otherwise uses a new child logger of the current logger. Returns whatever proc returns.\n\nExample:\n\n> ```racket\n> > ( let ( [ my-log ( open-output-string ) ] ) ( with-logging-to-port my-log ( lambda ( ) ( log-warning \"Warning World!\" ) ( + 2 2 ) ) ' warning ) ( get-output-string my-log ) )\n> \"Warning World!\\n\"\n> ```\n\nAdded in version 6.3 of package base. \nChanged in version 6.7.0.1: Added #:logger argument.\n\n------------------------------------------------------------------------\n\n# 15.6 Time\n\n### 15.6 Time\n\n> ```\n(current-seconds)\t→\n```\n(current-inexact-milliseconds)\t→```\nReturns the current time in milliseconds since [the epoch](#%28tech._the._epoch%29). The result may contain fractions of a millisecond.\nExample:\n> ```racket\n> > ( current-inexact-milliseconds )\n> 1289513737015.418\n> ```\nIn this example, 1289513737015 is in milliseconds and 418 is in microseconds.\n> ```\n(current-inexact-monotonic-milliseconds)\t→"} {"text": "# 15.5 Logging\n```\n(parameter)\t→```\n\n\nTakes secs-n, a time in seconds since [the epoch](#%28tech._the._epoch%29) (like the value of ([current-seconds](#%28def._%28%28quote._~23~25kernel%29._current-seconds%29%29)), ([file-or-directory-modify-seconds](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._file-or-directory-modify-seconds%29%29) path), or ([/](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._%2F%29%29) ([current-inexact-milliseconds](#%28def._%28%28quote._~23~25kernel%29._current-inexact-milliseconds%29%29)) 1000)), and returns an instance of the [date*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%2A%29%29) structure type. Note that secs-n can include fractions of a second. If secs-n is too small or large, the [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) exception is raised.\n\nThe resulting [date*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%2A%29%29) reflects the time according to the local time zone if local-time? is #t, otherwise it reflects a date in UTC.\n\n>
\n\n

struct

\n\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [date](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%29%29) (second
    minute
    hour
    day
    month
    year
    week-day
    year-day
    dst?
    time-zone-offset)
    #:extra-constructor-name [make-date](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-date%29%29)
    #:transparent)
  second : ([integer-in](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._integer-in%29%29) 0 60)
  minute : ([integer-in](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._integer-in%29%29) 0 59)
  hour : ([integer-in](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._integer-in%29%29) 0 23)
  day : ([integer-in](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._integer-in%29%29) 1 31)
  month : ([integer-in](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._integer-in%29%29) 1 12)
  year : [exact-integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-integer~3f%29%29)
  week-day : ([integer-in](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._integer-in%29%29) 0 6)
  year-day : ([integer-in](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._integer-in%29%29) 0 365)
  dst? : [boolean?](booleans.html#%28def._%28%28quote._~23~25kernel%29._boolean~3f%29%29)
  time-zone-offset : [exact-integer?](number-types.html#%28def._%28%28quote._~23~25kernel%29._exact-integer~3f%29%29)
\n\nRepresents a date. The second field reaches 60 only for leap seconds. The week-day field is 0 for Sunday, 1 for Monday, etc. The year-day field is 0 for January 1, 1 for January 2, etc.; the year-day field reaches 365 only in leap years.\n\nThe dst? field is #t if the date reflects a daylight-saving adjustment. The time-zone-offset field reports the number of seconds east of UTC (GMT) for the current time zone (e.g., Pacific Standard Time is -28800), including any daylight-saving adjustment (e.g., Pacific Daylight Time is -25200). When a [date](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%29%29) record is generated by [seconds->date](#%28def._%28%28quote._~23~25kernel%29._seconds-~3edate%29%29) with #f as the second argument, then the dst? and time-zone-offset fields are #f and 0, respectively.\n\nThe [date](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%29%29) constructor accepts any value for dst? and converts any non-#f value to #t.\n\nThe value produced for the time-zone-offset field tends to be sensitive to the value of the TZ environment variable, especially on Unix platforms; consult the system documentation (usually under tzset) for details.\n\nSee also the [racket/date](#%28mod-path._racket%2Fdate%29) library.\n\n>
\n\n

struct

\n\n
([struct](define-struct.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._struct%29%29) [date*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%2A%29%29) [date](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%29%29) (nanosecond time-zone-name)
    #:extra-constructor-name [make-date*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._make-date%2A%29%29))
  nanosecond : ([integer-in](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._integer-in%29%29) 0 999999999)
  time-zone-name : ([and/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fbase..rkt%29._and%2Fc%29%29) [string?](strings.html#%28def._%28%28quote._~23~25kernel%29._string~3f%29%29) [immutable?](booleans.html#%28def._%28%28quote._~23~25kernel%29._immutable~3f%29%29))
\n\nExtends [date](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%29%29) with nanoseconds and a time zone name, such as \"MDT\", \"Mountain Daylight Time\", or \"UTC\".\n\nWhen a [date*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%2A%29%29) record is generated by [seconds->date](#%28def._%28%28quote._~23~25kernel%29._seconds-~3edate%29%29) with #f as the second argument, then the time-zone-name field is \"UTC\".\n\nThe [date*](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%2A%29%29) constructor accepts a mutable string for time-zone-name and converts it to an immutable one.\n\n> ```\n(current-milliseconds)\t→\n```"} {"text": "# 15.5 Logging\n(parameter)\t→\t\n(-> or/c #f thread? 'subprocesses)```\nReturns an amount of processor time in [fixnum](numbers.html#%28tech._fixnum%29) milliseconds that has been consumed by on the underlying operating system, including both user and system time.\n- If scope is #f, the reported time is for all Racket threads and [places](places.html#%28tech._place%29).\n- If scope is a thread, the result is specific to the time while the thread ran, but it may include time for other [places](places.html#%28tech._place%29). The more a thread synchronizes with other threads, the less precisely per-thread processor time is recorded.\n- If scope is 'subprocesses, the result is the sum of process times for known-completed subprocesses (see [Processes](subprocess.html))—and known-completed children of the subprocesses, etc., on Unix and Mac OS—across all [places](places.html#%28tech._place%29).\nThe precision of the result is platform-specific, and since the result is a [fixnum](numbers.html#%28tech._fixnum%29), the value increases only over a limited (though reasonably long) time on a 32-bit platform.\nChanged in version 6.1.1.4 of package base: Added 'subprocesses mode.\n> ```\n(current-gc-milliseconds)\t→"} {"text": "# 15.5 Logging\n```\n(current-process-milliseconds)\t→```\n\n\nCollects timing information for a procedure application.\n\nFour values are returned: a list containing the result(s) of applying proc to the arguments in lst, the number of milliseconds of CPU time required to obtain this result, the number of “real” milliseconds required for the result, and the number of milliseconds of CPU time (included in the first result) spent on garbage collection.\n\nThe reliability of the timing numbers depends on the platform. If multiple Racket threads are running, then the reported time may include work performed by other threads.\n\n>
\n\n

syntax

\n\n

([time](#%28form._%28%28lib._racket%2Fprivate%2Fmore-scheme..rkt%29._time%29%29) body ...+)

\n\nReports [time-apply](#%28def._%28%28quote._~23~25kernel%29._time-apply%29%29)-style timing information for the evaluation of expr directly to the current output port. The result is the result of the last body.\n\n#### 15.6.1 Date Utilities\n\n> > > For more date & time operations, see [the Gregor: Date and Time documentation](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?tag=%28part._%28.%27%28lib._gregor%2Fscribblings%2Fgregor..scrbl%29.%27._.%27top.%27%29%29&version=8.18.0.13) or [srfi/19](../srfi/srfi-19.html)\n\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/date](#%28mod-path._racket%2Fdate%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/date](#%28mod-path._racket%2Fdate%29) library, not [racket/base](index.html) or [racket](index.html).\n\n> ```\n(current-date)\t→\n```"} {"text": "# 15.5 Logging\n(current-inexact-milliseconds)\t→\t\n(-> * 0.001 (current-inexact-milliseconds))```\nConverts a date to a string. The returned string contains the time of day only if time?. See also [date-display-format](#%28def._%28%28lib._racket%2Fdate..rkt%29._date-display-format%29%29).\n> ```\n(date-display-format)\t→\t\n(-> or/c ' american\n ' chinese\n ' german\n ' indian\n ' irish\n ' iso-8601\n ' rfc2822\n ' julian)\n(date-display-format format) → void?\n format\t:\t\n(-> or/c ' american\n ' chinese\n ' german\n ' indian\n ' irish\n ' iso-8601\n ' rfc2822\n ' julian)\n```\nParameter that determines the date string format. The initial format is 'american.\n\n> ```\n(date → seconds date [local-time?) → exact-integer?\n  date : date?\n  local-time? : any/c = #t```\n\n\nFinds the representation of a date in platform-specific seconds. If the platform cannot represent the specified date, [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) exception is raised.\n\nThe week-day, year-day fields of date are ignored. The dst? and time-zone-offset fields of date are also ignored; the date is assumed to be in local time by default or in UTC if local-time? is #f.\n\n> ```\n(date* → seconds date [local-time?) → real?\n  date : date?\n  local-time? : any/c = #t\n```\nLike date → seconds, but returns an exact number that can include a fraction of a second based on (date*-nanosecond date) if date is a date* instance.\n> ```"} {"text": "# 15.5 Logging\n(find-seconds second\n    minute        \n    hour        \n    day        \n    month        \n    year        \n   [ local-time?)   →   exact-integer?\n  second : (integer-in 0 61)\n  minute : (integer-in 0 59)\n  hour : (integer-in 0 23)\n  day : (integer-in 1 31)\n  month : (integer-in 1 12)\n  year : exact-nonnegative-integer?\n  local-time? : any/c = #t```\nFinds the representation of a date in platform-specific seconds. The arguments correspond to the fields of the [date](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._date%29%29) structure—in local time by default or UTC if local-time? is #f. If the platform cannot represent the specified date, an error is signaled, otherwise an integer is returned.\n> ```\n(date → julian/scaliger date)  →  exact-integer?\n  date : date?\n```\n\n\nConverts a date structure (up to 2099 BCE Gregorian) into a Julian date number. The returned value is not a strict Julian number, but rather Scaliger’s version, which is off by one for easier calculations.\n\n> ```\n(julian/scaliger → string date-number)  →  string?\n  date-number : exact-integer?\n```\nConverts a Julian number (Scaliger’s off-by-one version) into a string.\n> ```\n(date → julian/scalinger date)  →  exact-integer?\n  date : date?\n(julian/scalinger → string date-number)  →  string?\n  date-number : exact-integer?"} {"text": "# 15.5 Logging\n```\n(parameter)\t→\t\n(-> environment-variables? v)```\n\n\nReturns #t if v is an [environment variable set](#%28tech._environment._variable._set%29), #f otherwise.\n\n> ```\n(current-environment-variables)\t→\t\n(-> current-environment-variables env)\n(current-environment-variables env) → void?\n env\t:\t\n(-> current-environment-variables env)\n```\nA parameter that determines the environment variable set that is propagated to a subprocess and that is used as the default set for getenv and putenv.\n> ```\n(bytes-environment-variable-name? v)  →  boolean?\n  v : any/c```\nReturns #t if v is a byte string and if it is valid for an environment variable name. An environment variable name must contain no bytes with the value 0 or 61, where 61 is ([char->integer](characters.html#%28def._%28%28quote._~23~25kernel%29._char-~3einteger%29%29) #\\\\=). On Windows, an environment variable name also must have a non-zero length.\n> ```\n(make-environment-variables name val ... ...)\n  →  environment-variables?\n  name : bytes-environment-variable-name?\n  val : bytes-no-nuls?"} {"text": "# 15.5 Logging\n```\nCreates a fresh environment variable set that is initialized with the given name to val mappings.\n\n> ```\n(environment-variables-ref env name)\n  →  (or/c #f (and/c bytes-no-nuls? immutable?))\n  env : environment-variables?\n  name : bytes-environment-variable-name?```\n\n\nReturns the mapping for name in env, returning #f if name has no mapping.\n\nNormally, name should be a byte-string encoding of a string using the default encoding of the current [locale](encodings.html#%28tech._locale%29). On Windows, name is coerced to a UTF-8 encoding and case-normalized.\n\n> ```\n(environment-variables-set! env\n    name        \n    maybe-bstr        \n   [ fail)   →   any\n\n  env : environment-variables?\n  name : bytes-environment-variable-name?\n  maybe-bstr : (or/c bytes-no-nuls? #f)\n   fail   :   ( →  any)   =   ( lambda ( )\n> ( raise ( make-exn:fail .... ) ) )\n```\nChanges the mapping for name in env to maybe-bstr. If maybe-bstr is #f and env is the initial environment variable set of the Racket process, then the operating system environment-variable mapping for name is removed.\nNormally, name and maybe-bstr should be a byte-string encoding of a string using the default encoding of the current locale. On Windows, name is coerced to a UTF-8 encoding and case-normalized, and maybe-bstr is coerced to a UTF-8 encoding if env is the initial environment variable set of the Racket process."} {"text": "# 15.5 Logging\nOn success, the result of environment-variables-set! is #. If env is the initial environment variable set of the Racket process, then attempting to adjust the operating system environment-variable mapping might fail for some reason, in which case fail is called in tail position with respect to the environment-variables-set!. The default fail raises an exception.\n> ```\n(environment-variables-names env)\n  →  (listof (and/c bytes-environment-variable-name? immutable?))\n  env : environment-variables?```\nReturns a list of byte strings that corresponds to names mapped by env.\n> ```\n(environment-variables-copy env)  →  environment-variables?\n  env : environment-variables?"} {"text": "# 15.5 Logging\n```\nReturns an environment variable set that is initialized with the same mappings as env.\n\n> ```\n(getenv name)  →  (or/c string-no-nuls? #f)\n  name : string-environment-variable-name?\n\n(putenv name value)  →  boolean?\n  name : string-environment-variable-name?\n  value : string-no-nuls?```\n\n\nConvenience wrappers for [environment-variables-ref](#%28def._%28%28quote._~23~25kernel%29._environment-variables-ref%29%29) and [environment-variables-set!](#%28def._%28%28quote._~23~25kernel%29._environment-variables-set%21%29%29) that convert between strings and byte strings using the current [locale](encodings.html#%28tech._locale%29)’s default encoding (using #\\\\? as the replacement character for encoding errors) and always using the current [environment variable set](#%28tech._environment._variable._set%29) from [current-environment-variables](#%28def._%28%28quote._~23~25kernel%29._current-environment-variables%29%29). The [putenv](#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._putenv%29%29) function returns #t for success and #f for failure.\n\n> ```\n(string-environment-variable-name? v)  →  boolean?\n  v : any/c\n```\n(parameter)\t→\t\n(-> or/c symbol? string? bytes? exact-positive-integer? vector? #f)```"} {"text": "# 15.5 Logging\nReturns information about the operating system, build mode, or machine for a running Racket. (Installation tools should use [cross-system-type](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=cross-system.html%23%2528def._%2528%2528lib._setup%252Fcross-system..rkt%2529._cross-system-type%2529%2529&version=8.18.0.13), instead, to support cross-installation.)\nIn 'os mode, the possible symbol results are:\n- 'unix\n- 'windows\n- 'macosx\n> > > Prior to the introduction of 'os\\* and 'arch modes, ([system-library-subpath](#%28def._%28%28quote._~23~25kernel%29._system-library-subpath%29%29) #f) could be used to obtain this information somewhat indirectly.\nIn 'os\\* mode, the result is similar to 'os mode, but refined to a specific operating system, such as 'linux or 'freebsd, instead of a generic 'unix classification.\nIn 'arch mode, the result is a symbol representing an architecture. Possible results include 'x86_64, 'i386, 'aarch64, 'arm (32-bit), and 'ppc (32-bit).\nIn 'word mode, the result is either 32 or 64 to indicate whether Racket is running as a 32-bit program or 64-bit program.\n> > > See [Racket Virtual Machine Implementations](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=guide&rel=performance.html%23%2528part._virtual-machines%2529&version=8.18.0.13) for more information about the 'vm and 'gc mode results.\nIn 'vm mode, the possible symbol results are (see also [Implementations](implementations.html)):\n- 'racket\n- 'chez-scheme"} {"text": "# 15.5 Logging\nIn 'gc mode, the possible symbol results are (see also [Implementations](implementations.html)):\n- 'cgc — when ([system-type](#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) 'vm) is 'racket\n- '3m — when ([system-type](#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) 'vm) is 'racket\n- 'cs — when ([system-type](#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) 'vm) is 'chez-scheme\nIn 'link mode, the possible symbol results are:\n- 'static (Unix)\n- 'shared (Unix)\n- 'dll (Windows)\n- 'framework (Mac OS)\nFuture ports of Racket may expand the list of 'os, 'os\\*, 'arch, 'vm, 'gc, and 'link results.\nIn 'machine mode, then the result is a string, which contains further details about the current machine in a platform-specific format.\nIn 'target-machine mode, the result is a symbol for the running Racket’s native bytecode format, or it is #f if there is no native format other than the machine-independent format. If the result is a symbol, then [compile-target-machine?](eval.html#%28def._%28%28quote._~23~25kernel%29._compile-target-machine~3f%29%29) returns #t when applied to the symbol; see also [current-compile-target-machine](eval.html#%28def._%28%28quote._~23~25kernel%29._current-compile-target-machine%29%29)."} {"text": "# 15.5 Logging\nIn 'so-suffix mode, then the result is a byte string that represents the file extension used for shared objects on the current platform. The byte string starts with a period, so it is suitable as a second argument to [path-replace-suffix](Manipulating_Paths.html#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._path-replace-suffix%29%29).\nIn 'so-mode mode, then the result is 'local if foreign libraries should be opened in “local” mode by default (as on most platforms) or 'global if foreign libraries should be opened in “global” mode.\nIn 'fs-change mode, the result is an immutable vector of four elements. Each element is either #f or a symbol, where a symbol indicates the presence of a property and #f indicates the absence of a property. The possible symbols, in order, are:\n- 'supported — [filesystem-change-evt](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._filesystem-change-evt%29%29) can produce a [filesystem change event](Filesystem.html#%28tech._filesystem._change._event%29) to monitor filesystem changes; if this symbol is not first in the vector, all other vector elements are #f\n- 'scalable — resources consumed by a [filesystem change event](Filesystem.html#%28tech._filesystem._change._event%29) are effectively limited only by available memory, as opposed to file-descriptor limits; this property is #f on Mac OS and BSD variants of Unix\n- 'low-latency — creation and checking of a [filesystem change event](Filesystem.html#%28tech._filesystem._change._event%29) is practically instantaneous; this property is #f on Linux"} {"text": "# 15.5 Logging\n- 'file-level — a [filesystem change event](Filesystem.html#%28tech._filesystem._change._event%29) can track changes at the level of a file, as opposed to the file’s directory; this property is #f on Windows\nIn 'cross mode, the result reports whether cross-platform build mode has been selected (through the -C or --cross argument to racket; see [Command Line](running-sa.html#%28part._mz-cmdline%29)). The possible symbols are:\n- 'infer — infer cross-platform mode based on whether ([system-type](#%28def._%28%28quote._~23~25kernel%29._system-type%29%29)) and ([cross-system-type](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=cross-system.html%23%2528def._%2528%2528lib._setup%252Fcross-system..rkt%2529._cross-system-type%2529%2529&version=8.18.0.13)) report the same symbol\n- 'force — use cross-platform mode, even if the current and target system types are the same, because the current and target executables can be different\nChanged in version 6.8.0.2 of package base: Added 'vm mode. \nChanged in version 6.9.0.1: Added 'cross mode. \nChanged in version 7.1.0.6: Added 'target-machine mode. \nChanged in version 7.9.0.6: Added 'os\\* and 'arch modes.\n> ```\n(system-language+country)  →  string?"} {"text": "# 15.5 Logging\n```\nReturns a string to identify the current user’s language and country.\n\nOn Unix and Mac OS, the string is five characters: two lowercase ASCII letters for the language, an underscore, and two uppercase ASCII letters for the country. On Windows, the string can be arbitrarily long, but the language and country are in English (all ASCII letters or spaces) separated by an underscore.\n\nOn Unix, the result is determined by checking the LC_ALL, LC_TYPE, and LANG environment variables, in that order (and the result is used if the environment variable’s value starts with two lowercase ASCII letters, an underscore, and two uppercase ASCII letters, followed by either nothing or a period). On Windows and Mac OS, the result is determined by system calls.\n\n> ```\n(system-library-subpath [mode) → path?\n  mode : (or/c 'cgc '3m 'cs #f) = (system-type 'gc)```\n\n\nReturns a relative directory path. This string can be used to build paths to system-specific files. For example, when Racket is running on Solaris on a Sparc architecture, the subpath starts \"sparc-solaris\", while the subpath for Windows on an i386 architecture starts \"win32\\\\\\\\i386\".\n\nThe optional mode argument specifies the relevant garbage-collection variant, which one of the possible results of ([system-type](#%28def._%28%28quote._~23~25kernel%29._system-type%29%29) 'gc): 'cgc, '3m, or 'cs. It can also be #f, in which case the result is independent of the garbage-collection variant.\n\nInstallation tools should use [cross-system-library-subpath](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=cross-system.html%23%2528def._%2528%2528lib._setup%252Fcross-system..rkt%2529._cross-system-library-subpath%2529%2529&version=8.18.0.13), instead, to support cross-installation.\n\nChanged in version 7.0 of package base: Added 'cs mode.\n\n> ```\n(version)  →  (and/c string? immutable?)\n```"} {"text": "# 15.5 Logging\nReturns an immutable string indicating the currently executing version of Racket.\n> ```\n(banner)  →  (and/c string? immutable?)\n```\n\n\nReturns an immutable string for Racket’s start-up banner text (or the banner text for an embedding program, such as GRacket). The banner string ends with a newline.\n\n> ```\n(current-command-line-arguments)\t→\t\n(-> vectorof (and/c string? immutable?))\n(current-command-line-arguments argv) → void?\n argv\t:\t\n(-> vectorof (and/c string? immutable?))\n```\n(current-thread-initial-stack-size)\t→\t\n(-> current-thread-initial-stack-size)\n(current-thread-initial-stack-size size) → void?\n size\t:\t\n(-> current-thread-initial-stack-size)```\nA [parameter](eval-model.html#%28tech._parameter%29) that provides a hint about how much space to reserve for a newly created thread’s local variables. The actual space used by a computation is affected by [JIT](eval.html#%28tech._jit%29) compilation, but it is otherwise platform-independent.\n> ```\n(parameter)\t→\t\n(-> and/c vector?\n (not/c immutable?))"} {"text": "# 15.5 Logging\n```\n(parameter)\t→```\n\n\nParses a command line according to the specification in the flag-clauses.\n\nThe name-expr, if provided, should produce a path or string to be used as the program name for reporting errors when the command-line is ill-formed. It defaults to ([find-system-path](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._find-system-path%29%29) 'run-file). When a path is provided, only the last element of the path is used to report an error.\n\nThe argv-expr, if provided, must evaluate to a list or a vector of strings. It defaults to ([current-command-line-arguments](runtime.html#%28def._%28%28quote._~23~25kernel%29._current-command-line-arguments%29%29)).\n\nThe command-line is disassembled into flags, each possibly with flag-specific arguments, followed by (non-flag) arguments. Command-line strings starting with - or + are parsed as flags, but arguments to flags are never parsed as flags, and integers and decimal numbers that start with - or + are not treated as flags. Non-flag arguments in the command-line must appear after all flags and the flags’ arguments. No command-line string past the first non-flag argument is parsed as a flag. The built-in -- flag signals the end of command-line flags; any command-line string past the -- flag is parsed as a non-flag argument.\n\nA #:multi, #:once-each, #:once-any, or #:final clause introduces a set of command-line flag specifications. The clause tag indicates how many times the flag can appear on the command line:\n\n- #:multi — Each flag specified in the set can be represented any number of times on the command line; i.e., the flags in the set are independent and each flag can be used multiple times.\n\n- #:once-each — Each flag specified in the set can be represented once on the command line; i.e., the flags in the set are independent, but each flag should be specified at most once. If a flag specification is represented in the command line more than once, the [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) exception is raised.\n\n- #:once-any — Only one flag specified in the set can be represented on the command line; i.e., the flags in the set are mutually exclusive. If the set is represented in the command line more than once, the [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) exception is raised.\n\n- #:final — Like #:multi, except that no argument after the flag is treated as a flag. Note that multiple #:final flags can be specified if they have short names; for example, if -a is a #:final flag, then -aa combines two instances of -a in a single command-line argument.\n\nA normal flag specification has four parts:\n\n- flags — a flag string, or a set of flag strings. If a set of flags is provided, all of the flags are equivalent. Each flag string must be of the form \"-x\" or \"+x\" for some character x, or \"--x\" or \"++x\" for some sequence of characters x. An x cannot contain only digits or digits plus a single decimal point, since simple (signed) numbers are not treated as flags. In addition, the flags \"--\", \"-h\", and \"--help\" are predefined and cannot be changed.\n\n- ids — identifier that are bound to the flag’s arguments. The number of identifiers determines how many arguments can be provided on the command line with the flag, and the names of these identifiers will appear in the help message describing the flag. The ids are bound to string values in the bodys for handling the flag.\n\n- help-spec — a string or sequence of strings that describes the flag. This string is used in the help message generated by the handler for the built-in -h (or --help) flag. A single literal string can be provided, or any number of expressions that produce strings; in the latter case, strings after the first one are displayed on subsequent lines.\n\n- bodys — expressions that are evaluated when one of the flags appears on the command line. The flags are parsed left-to-right, and each sequence of bodys is evaluated as the corresponding flag is encountered. When the bodys are evaluated, the preceding ids are bound to the arguments provided for the flag on the command line.\n\nA flag specification using [=>](if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._~3d~3e%29%29) escapes to a more general method of specifying the handler and help strings. In this case, the handler procedure and help string list returned by handler-expr and help-expr are used as in the table argument of [parse-command-line](#%28def._%28%28lib._racket%2Fcmdline..rkt%29._parse-command-line%29%29).\n\nA #:usage-help clause inserts text lines immediately after the usage line. Each string in the clause provides a separate line of text.\n\nA #:help-labels clause inserts text lines into the help table of command-line flags. Each string in the clause provides a separate line of text.\n\nA #:ps clause inserts text lines at the end of the help output. Each string in the clause provides a separate line of text.\n\nAfter the flag clauses, a final clause handles command-line arguments that are not parsed as flags:\n\n- Supplying no finish clause is the same as supplying #:args () ([void](void.html#%28def._%28%28quote._~23~25kernel%29._void%29%29)).\n\n- For an #:args finish clause, identifiers in arg-formals are bound to the leftover command-line strings in the same way that identifiers are bound for a [lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) expression. Thus, specifying a single id (without parentheses) collects all of the leftover arguments into a list. The effective arity of the arg-formals specification determines the number of extra command-line arguments that the user can provide, and the names of the identifiers in arg-formals are used in the help string. When the command-line is parsed, if the number of provided arguments cannot be matched to identifiers in arg-formals, the [exn:fail](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail%29%29) exception is raised. Otherwise, args clause’s bodys are evaluated to handle the leftover arguments, and the result of the last body is the result of the [command-line](#%28form._%28%28lib._racket%2Fcmdline..rkt%29._command-line%29%29) expression.\n\n- A #:handlers finish clause escapes to a more general method of handling the leftover arguments. In this case, the values of the expressions are used like the last two to four arguments [parse-command-line](#%28def._%28%28lib._racket%2Fcmdline..rkt%29._parse-command-line%29%29).\n\nExample:\n\n> ```racket\n> ( define verbose-mode ( make-parameter #f ) )\n> ( define profiling-on ( make-parameter #f ) )\n> ( define optimize-level ( make-parameter 0 ) )\n> ( define link-flags ( make-parameter null ) )\n> ( define file-to-compile\n> ( command-line\n> #:program \"compiler\"\n> #:once-each\n> [ ( \"-v\" \"--verbose\" ) \"Compile with verbose messages\"\n> ( verbose-mode #t ) ]\n> [ ( \"-p\" \"--profile\" ) \"Compile with profiling\"\n> ( profiling-on #t ) ]\n> #:once-any\n> [ ( \"-o\" \"--optimize-1\" ) \"Compile with optimization level 1\"\n> ( optimize-level 1 ) ]\n> [ \"--optimize-2\" ( ; show help on separate lines\n> \"Compile with optimization level 2,\"\n> \"which includes all of level 1\" )\n> ( optimize-level 2 ) ]\n> #:multi\n> [ ( \"-l\" \"--link-flags\" ) lf ; flag takes one argument\n> \"Add a flag for the linker\"\n> ( link-flags ( cons lf ( link-flags ) ) ) ]\n> #:args ( filename ) ; expect one command-line argument: \n> ; return the argument as a filename to compile\n> filename ) )\n> ```\n\n> ```\n(str)\t→\t\n(-> or/c string? path?)\n```"} {"text": "# 15.5 Logging\n(non-flag)\t→```\nReturns a string for the current machine’s hostname (including its domain).\n> ```\n(getpid)  →  exact-integer?\n```\nReturns an integer identifying the current process within the operating system.\n\n------------------------------------------------------------------------\n\n# 16 Memory Management\n\n8.18.0.13\n\n## 16 Memory Management\n\n| |\n|----------------------------------------------------------------------------------|\n|     16.1 Weak Boxes |\n|     16.2 Ephemerons |\n|     16.3 Wills and Executors |\n|     16.4 Garbage Collection |\n|     16.5 Phantom Byte Strings |\n\n------------------------------------------------------------------------\n\n# 16.1 Weak Boxes\n\n### 16.1 Weak Boxes\n\nA weak box is similar to a normal box (see Boxes), but when the garbage collector (see Garbage Collection) can prove that the content value of a weak box is only reachable via weak references, the content of the weak box is replaced with #f. A weak reference is a reference through a weak box, through a key reference in a weak hash table (see Hash Tables), through a value in an ephemeron where the value can be replaced by #f (see Ephemerons), or through a custodian (see Custodians).\n\n> ```\n(make-weak-box v) → weak-box?\n  v : any/c```\n\n\nReturns a new weak box that initially contains v.\n\n> ```\n(weak-box-value weak-box [gced-v) → any/c\n  weak-box : weak-box?\n  gced-v : any/c = #f\n```"} {"text": "# 15.5 Logging\nReturns the value contained in weak-box. If the garbage collector has proven that the previous content value of weak-box was reachable only through a weak reference, then gced-v (which defaults to #f) is returned.\n> ```\n(weak-box? v)  →  boolean?\n  v : any/c\n```\n\n\nReturns #t if v is a weak box, #f otherwise.\n\n------------------------------------------------------------------------\n\n# 16.2 Ephemerons\n\n### 16.2 Ephemerons\n\nAn ephemeron \\[[Hayes97](doc-bibliography.html#%28cite._.Hayes97%29)\\] is a generalization of a [weak box](weakbox.html#%28tech._weak._box%29) (see [Weak Boxes](weakbox.html)). Instead of just containing one value, an ephemeron holds two values: one that is considered the value of the ephemeron and another that is the ephemeron’s key. Like the value in a weak box, the value in an ephemeron may be replaced by #f, but when the key is no longer reachable (except possibly via weak references) instead of when the value is no longer reachable.\n\nAs long as an ephemeron’s value is retained, the reference is considered a non-weak reference. References to the key via the value are treated specially, however, in that the reference does not necessarily count toward the key’s reachability. A [weak box](weakbox.html#%28tech._weak._box%29) can be seen as a specialization of an ephemeron where the key and value are the same.\n\nOne particularly common use of ephemerons is to combine them with a weak hash table (see [Hash Tables](hashtables.html)) to produce a mapping where the memory manager can reclaim key–value pairs even when the value refers to the key; see [make-ephemeron-hash](hashtables.html#%28def._%28%28quote._~23~25kernel%29._make-ephemeron-hash%29%29). A related use is to retain a reference to a value as long as any value for which it is an [impersonator](chaperones.html#%28tech._impersonator%29) is reachable; see [impersonator-ephemeron](chaperones.html#%28def._%28%28quote._~23~25kernel%29._impersonator-ephemeron%29%29).\n\nMore precisely,\n\n- the value in an ephemeron is replaced by #f when the automatic memory manager can prove that either the ephemeron or the key is reachable only through weak references (see [Weak Boxes](weakbox.html)); and\n\n- nothing reachable from the value in an ephemeron counts toward the reachability of an ephemeron key (whether for the same ephemeron or another), unless the same value is reachable through a non-weak reference, or unless the value’s ephemeron key is reachable through a non-weak reference (see [Weak Boxes](weakbox.html) for information on weak references).\n\n> ```\n(make-ephemeron key v)  →  ephemeron?\n  key : any/c\n  v : any/c\n```"} {"text": "# 15.5 Logging\nReturns a new ephemeron whose key is key and whose value is initially v.\n> ```\n(ephemeron-value ephemeron [gced-v retain-v) → any/c\n  ephemeron : ephemeron?\n  gced-v : any/c = #f\n  retain-v : any/c = #f```\nReturns the value contained in ephemeron. If the garbage collector has proven that the key for ephemeron is only weakly reachable, then the result is gced-v (which defaults to #f).\nThe retain-v argument is retained as reachable until the ephemeron’s value is extracted. It is useful, for example, when ephemeron was obtained through a weak, [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29)-based mapping from key and ephemeron was created with key as the key; in that case, supplying key as retain-v ensures that ephemeron retains its value long enough for it to be extracted, even if key is otherwise unreachable.\nChanged in version 7.1.0.10 of package base: Added the retain-v argument.\n> ```\n(ephemeron? v)  →  boolean?\n  v : any/c"} {"text": "# 15.5 Logging\n```\nReturns #t if v is an ephemeron, #f otherwise.\n\n------------------------------------------------------------------------\n\n# 16.3 Wills and Executors\n\n### 16.3 Wills and Executors\n\nA will executor manages a collection of values and associated will procedures (a.k.a. finalizers). The will procedure for each value is ready to be executed when the value has been proven (by the garbage collector) to be unreachable, except through weak references (see Weak Boxes) or as the registrant for other will executors. A will is useful for triggering clean-up actions on data associated with an unreachable value, such as closing a port embedded in an object when the object is no longer used.\n\nCalling the will-execute or will-try-execute procedure executes a will that is ready in the specified will executor. A will executor is also a synchronizable event, so sync or sync/timeout can be used to detect when a will executor has ready wills. Wills are not executed automatically, because certain programs need control to avoid race conditions. However, a program can create a thread whose sole job is to execute wills for a particular executor.\n\nIf a value is registered with multiple wills (in one or multiple executors), the wills are readied in the reverse order of registration. Since readying a will procedure makes the value reachable again, the will must be executed and the value must be proven again unreachable through only weak references before another of the wills is readied or executed. However, wills for distinct unreachable values are readied at the same time, regardless of whether the values are reachable from each other.\n\nA will executor’s registrant is held non-weakly until after the corresponding will procedure is executed. Thus, if the content value of a weak box (see Weak Boxes) is registered with a will executor, the weak box’s content is not changed to #f until all wills have been executed for the value and the value has been proven again reachable through only weak references.\n\nA will executor can be used as a synchronizable event (see Events). A will executor is ready for synchronization when will-execute would not block; the synchronization result of a will executor is the will executor itself.\n\nThese examples show how to run cleanup actions when no synchronization is necessary. It simply runs the registered executors as they become ready in another thread.\n\nExamples:\n\n> ```racket\n> > ( define an-executor ( make-will-executor ) )\n> > ( void ( thread ( λ ( ) ( let loop ( ) ( will-execute an-executor ) ( loop ) ) ) ) )\n> > ( define ( executor-proc v ) ( printf \"a-box is now garbage\\n\" ) )\n> > ( define a-box-to-track ( box #f ) )\n> > ( will-register an-executor a-box-to-track executor-proc )\n> > ( collect-garbage )\n> > ( set! a-box-to-track #f )\n> > ( collect-garbage )\n> a-box is now garbage\n> ```\n\n> ```\n(make-will-executor)  →  will-executor?```\n\n\nReturns a new will executor with no managed values.\n\n> ```\n(will-executor? v)  →  boolean?\n  v : any/c\n```"} {"text": "# 15.5 Logging\n(parameter)\t→\t\n(-> any/c . → . any)```\nRegisters the value v with the will procedure proc in the will executor executor. When v is proven unreachable, then the procedure proc is ready to be called with v as its argument via [will-execute](#%28def._%28%28quote._~23~25kernel%29._will-execute%29%29) or [will-try-execute](#%28def._%28%28quote._~23~25kernel%29._will-try-execute%29%29). The proc argument is strongly referenced until the will procedure is executed.\n> ```\n(will-execute executor)  →  any\n  executor : will-executor?\n```\nInvokes the will procedure for a single “unreachable” value registered with the executor executor. The values returned by the will procedure are the result of the will-execute call. If no will is ready for immediate execution, will-execute blocks until one is ready.\n\n> ```\n(will-try-execute executor [v) → any\n  executor : any/c\n  v : any/c = #f```\n\n\nLike [will-execute](#%28def._%28%28quote._~23~25kernel%29._will-execute%29%29) if a will is ready for immediate execution. Otherwise, v is returned.\n\nChanged in version 6.90.0.4 of package base: Added the v argument.\n\n------------------------------------------------------------------------\n\n# 16.4 Garbage Collection\n\n### 16.4 Garbage Collection\n\nSet the PLTDISABLEGC environment variable (to any value) before Racket starts to disable [garbage collection](eval-model.html#%28tech._garbage._collection%29). Set the PLT_INCREMENTAL_GC environment variable to a value that starts with 1, y, or Y to request incremental mode at all times for the [3m](implementations.html#%28tech._3m%29) implementation of Racket, but calling ([collect-garbage](#%28def._%28%28quote._~23~25kernel%29._collect-garbage%29%29) 'incremental) in a program with a periodic task is generally a better mechanism for requesting incremental mode. Set the PLT_INCREMENTAL_GC environment variable to a value that starts with 0, n, or N to disable incremental-mode requests (in all implementations of Racket).\n\nEach garbage collection logs a message (see [Logging](logging.html)) at the 'debug level with topic 'GC. In the [CS](implementations.html#%28tech._c%29) and [3m](implementations.html#%28tech._3m%29) implementations of Racket, “major” collections are also logged at the 'debug level with the topic 'GC:major. In the [CS](implementations.html#%28tech._c%29) and [3m](implementations.html#%28tech._3m%29) implementations of Racket, the data portion of the message is an instance of a gc-info [prefab](structures.html#%28tech._prefab%29) structure type with 10 fields as follows, but future versions of Racket may use a gc-info [prefab](structures.html#%28tech._prefab%29) structure with additional fields:\n\n> ```racket\n> ( struct gc-info ( mode pre-amount pre-admin-amount code-amount\n> post-amount post-admin-amount\n> start-process-time end-process-time\n> start-time end-time )\n> #:prefab )\n> ```\n\n- The mode field is a symbol 'major, 'minor, or 'incremental; 'major indicates a collection that inspects all memory, 'minor indicates collection that mostly inspects just recent allocations, and 'incremental indicates a minor collection that performs extra work toward the next major collection.\n\n Changed in version 6.3.0.7 of package base: Changed first field from a boolean (#t for 'major, #f for 'minor) to a mode symbol.\n\n- The pre-amount field reports place-local memory use (i.e., not counting the memory use of child places) in bytes at the time that the [garbage collection](eval-model.html#%28tech._garbage._collection%29) started. Additional bytes registered via [make-phantom-bytes](phantom-bytes.html#%28def._%28%28quote._~23~25kernel%29._make-phantom-bytes%29%29) are included.\n\n- The pre-admin-amount is a larger number that includes memory use for the garbage collector’s overhead, such as space on memory pages that are mapped but not currently used.\n\n- The code-amount field reports additional memory use for generated native code (which is the same just before and after a garbage collection, since it is released via finalization).\n\n- The post-amount and post-admin-amount fields correspond to pre-amount and pre-admin-amount, but after garbage collection. In typical configurations, the difference between post-amount and pre-amount contributes to post-admin-amount, since reclaimed pages tend to stay in reserve with the expectation that they’ll be needed again (but the pages are released if multiple collections pass without need for the pages).\n\n- The start-process-time and end-process-time fields report processor time (in the sense of [current-process-milliseconds](time.html#%28def._%28%28quote._~23~25kernel%29._current-process-milliseconds%29%29)) at the start and end of garbage collection. The difference between the times is the processor time consumed by collection.\n\n- The start-time and end-time fields report real time (in the sense of [current-inexact-milliseconds](time.html#%28def._%28%28quote._~23~25kernel%29._current-inexact-milliseconds%29%29)) at the start and end of garbage collection. The difference between the times is the real time consumed by garbage collection.\n\nThe format of the logged message’s text is subject to change. Currently, after a prefix that indicates the [place](places.html#%28tech._place%29) and collection mode, the text has the format\n\n> ‹used›(‹admin›)\\[‹code›\\]; free ‹reclaimed›(‹adjust›) ‹elapsed› @ ‹timestamp›\n>\n> | | | |\n> |-------------|-----|---------------------------------------------------------------|\n> | ‹used› |   | Collectable memory in use just prior to garbage collection |\n> | ‹admin› |   | Additional memory used as to manage collectable memory |\n> | ‹code› |   | Additional memory used for generated machine code |\n> | ‹reclaimed› |   | Collectable memory reclaimed by garbage collection |\n> | ‹adjust› |   | Negation of change to administrative memory minus ‹reclaimed› |\n> | ‹elapsed› |   | Processor time used to perform garbage collection |\n> | ‹timestamp› |   | Processor time since startup of garbage collection’s start |\n\nChanged in version 6.3.0.7 of package base: Added PLT_INCREMENTAL_GC. \nChanged in version 7.6.0.9: Added major-collection logging for the topic 'GC:major.\n\n> ```\n(parameter)\t→\t\n(-> or/c 'major 'minor 'incremental)\n```"} {"text": "# 15.5 Logging\n(parameter)\t→\t\n(-> or/c #f 'cumulative 'peak custodian?)```\nReturns information about memory use:\n- If mode is #f (the default), the result is an estimate of the number of bytes reachable from any custodian.\n- If mode is 'cumulative, returns an estimate of the total number of bytes allocated since start up, including bytes that have since been reclaimed by garbage collection.\n- If mode is 'peak, returns the maximum number of allocated bytes just before any garbage collection in the Racket process since its start.\n- If mode is a custodian, returns an estimate of the number of bytes of memory occupied by reachable data from mode. This estimate is calculated by the last garbage collection, and can be 0 if none occurred (or if none occurred since the given custodian was created). The [current-memory-use](#%28def._%28%28quote._~23~25kernel%29._current-memory-use%29%29) function does not perform a collection by itself; doing one before the call will generally decrease the result (or increase it from 0 if no collections happened yet).\n When Racket is compiled without support for memory accounting, the estimate is the same as when mode is #f (i.e., all memory) for any individual custodian. See also [custodian-memory-accounting-available?](custodians.html#%28def._%28%28quote._~23~25kernel%29._custodian-memory-accounting-available~3f%29%29).\nSee also [vector-set-performance-stats!](runtime.html#%28def._%28%28quote._~23~25kernel%29._vector-set-performance-stats%21%29%29)."} {"text": "# 15.5 Logging\nChanged in version 6.6.0.3 of package base: Added 'cumulative mode. \nChanged in version 8.10.0.3: Added 'peak mode.\n> ```\n(dump-memory-stats v ...) → any\n  v : any/c\n```\n(parameter)\t→```\n\n\nReturns #t if v is a [phantom byte string](#%28tech._phantom._byte._string%29), #f otherwise.\n\n> ```\n(make-phantom-bytes k)  →  phantom-bytes?\n  k : exact-nonnegative-integer?\n```\nCreates a phantom byte string that is treated by the Racket memory manager as being k bytes in size. For a large enough k, the exn:fail:out-of-memory exception is raised—either because the size is implausibly large, or because a memory limit has been installed with custodian-limit-memory.\n> ```\n(set-phantom-bytes! phantom-bstr k)  →  phantom-bytes?\n  phantom-bstr : phantom-bytes?\n  k : exact-nonnegative-integer?```\nAdjusts the size of a [phantom byte string](#%28tech._phantom._byte._string%29) as it is treated by the Racket memory manager.\nFor example, if the memory that phantom-bstr represents is released through a foreign library, then ([set-phantom-bytes!](#%28def._%28%28quote._~23~25kernel%29._set-phantom-bytes%21%29%29) phantom-bstr 0) can reflect the change in memory use.\nWhen k is larger than the current size of phantom-bstr, then this function can raise [exn:fail:out-of-memory](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3aout-of-memory%29%29), like [make-phantom-bytes](#%28def._%28%28quote._~23~25kernel%29._make-phantom-bytes%29%29).\n------------------------------------------------------------------------"} {"text": "# 17 Unsafe Operations"} {"text": "## 17 Unsafe Operations\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/unsafe/ops]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nAll functions and forms provided by [racket/base](index.html) and [racket](index.html) check their arguments to ensure that the arguments conform to contracts and other constraints. For example, [vector-ref](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector-ref%29%29) checks its arguments to ensure that the first argument is a vector, that the second argument is an exact integer, and that the second argument is between 0 and one less than the vector’s length, inclusive."} {"text": "# 17 Unsafe Operations\nFunctions provided by [racket/unsafe/ops]() are unsafe. They have certain constraints, but the constraints are not checked, which allows the system to generate and execute faster code. If arguments violate an unsafe function’s constraints, the function’s behavior and result is unpredictable, and the entire system can crash or become corrupted.\nAll of the exported bindings of [racket/unsafe/ops]() are protected in the sense of [protect-out](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._protect-out%29%29), so access to unsafe operations can be prevented by adjusting the code inspector (see [Code Inspectors](modprotect.html))."} {"text": "### 17.1 Unsafe Numeric Operations\n> ```\n(unsafe-fx+ a ...) → fixnum?\n  a : fixnum?\n(unsafe-fx- a b ...)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n(unsafe-fx* a ...)  →  fixnum?\n  a : fixnum?\n(unsafe-fxquotient a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n(unsafe-fxremainder a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n(unsafe-fxmodulo a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n(unsafe-fxabs a)  →  fixnum?\n  a : fixnum?\n```\nFor fixnums: Unchecked versions of fx+, fx-, fx*, fxquotient, fxremainder, fxmodulo, and fxabs.\n\nChanged in version 7.0.0.13 of package base: Allow zero or more arguments for unsafe-fx+ and unsafe-fx* and allow one or more arguments for unsafe-fx-.\n\n> ```\n(unsafe-fxand a ...) → fixnum?\n  a : fixnum?\n\n(unsafe-fxior a ...)  →  fixnum?\n  a : fixnum?\n\n(unsafe-fxxor a ...)  →  fixnum?\n  a : fixnum?\n\n(unsafe-fxnot a)  →  fixnum?\n  a : fixnum?\n\n(unsafe-fxlshift a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n\n(unsafe-fxrshift a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n\n(unsafe-fxrshift/logical a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?```\n\n\nFor [fixnums](numbers.html#%28tech._fixnum%29): Unchecked versions of [fxand](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxand%29%29), [fxior](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxior%29%29), [fxxor](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxxor%29%29), [fxnot](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxnot%29%29), [fxlshift](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxlshift%29%29), [fxrshift](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxrshift%29%29), and [fxrshift/logical](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxrshift%2Flogical%29%29).\n\nChanged in version 7.0.0.13 of package base: Allow zero or more arguments for [unsafe-fxand](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fxand%29%29), [unsafe-fxior](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fxior%29%29), and [unsafe-fxxor](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fxxor%29%29). \nChanged in version 8.8.0.5: Added [unsafe-fxrshift/logical](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fxrshift%2Flogical%29%29).\n\n> ```\n(unsafe-fxpopcount a)  →  fixnum?\n  a : (and/c fixnum? (not/c negative?))\n\n(unsafe-fxpopcount32 a)  →  fixnum?\n  a : (and/c fixnum? (integer-in 0 #xFFFFFFFF))\n\n(unsafe-fxpopcount16 a)  →  fixnum?\n  a : (and/c fixnum? (integer-in 0 #xFFFF))\n```"} {"text": "### 17.1 Unsafe Numeric Operations\nFor fixnums: Unchecked versions of fxpopcount, fxpopcount32, and fxpopcount16.\nAdded in version 8.5.0.6 of package base.\n> ```\n(unsafe-fx+/wraparound a b) → fixnum?\n  a : fixnum?\n  b : fixnum?\n(unsafe-fx-/wraparound [a] b)  →  fixnum?\n  a : fixnum? = 0\n  b : fixnum?\n(unsafe-fx*/wraparound a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n(unsafe-fxlshift/wraparound a b)  →  fixnum?\n  a : fixnum?\n  b : fixnum?```\nFor [fixnums](numbers.html#%28tech._fixnum%29): Unchecked versions of [fx+/wraparound](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fx%2B%2Fwraparound%29%29), [fx-/wraparound](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fx-%2Fwraparound%29%29), [fx*/wraparound](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fx%2A%2Fwraparound%29%29), and [fxlshift/wraparound](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxlshift%2Fwraparound%29%29).\nAdded in version 7.9.0.6 of package base. \nChanged in version 8.15.0.12: Changed [unsafe-fx-/wraparound](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fx-%2Fwraparound%29%29) to accept a single argument.\n> ```\n(unsafe-fx= a b ...) → boolean?\n  a : fixnum?\n  b : fixnum?\n([unsafe-fx\n(unsafe-fx> a b ...)  →  boolean?\n  a : fixnum?\n  b : fixnum?\n([unsafe-fx\n(unsafe-fx>= a b ...)  →  boolean?\n  a : fixnum?\n  b : fixnum?\n(unsafe-fxmin a b ...)  →  fixnum?\n  a : fixnum?\n  b : fixnum?\n(unsafe-fxmax a b ...)  →  fixnum?\n  a : fixnum?\n  b : fixnum?"} {"text": "### 17.1 Unsafe Numeric Operations\n```\nFor fixnums: Unchecked versions of fx=, fx<, fx>, fx<=, fx>=, fxmin, and fxmax.\n\nChanged in version 7.0.0.13 of package base: Allow one or more argument, instead of allowing just two.\n\n> ```\n(unsafe-fl+ a ...) → flonum?\n  a : flonum?\n\n(unsafe-fl- a b ...)  →  flonum?\n  a : flonum?\n  b : flonum?\n\n(unsafe-fl* a ...)  →  flonum?\n  a : flonum?\n\n(unsafe-fl/ a b ...)  →  flonum?\n  a : flonum?\n  b : flonum?\n\n(unsafe-flabs a)  →  flonum?\n  a : flonum?```\n\n\nFor [flonums](numbers.html#%28tech._flonum%29): Unchecked versions of [fl+](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl%2B%29%29), [fl-](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl-%29%29), [fl*](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl%2A%29%29), [fl/](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fl%2F%29%29), and [flabs](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flabs%29%29).\n\nChanged in version 7.0.0.13 of package base: Allow zero or more arguments for [unsafe-fl+](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fl%2B%29%29) and [unsafe-fl*](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fl%2A%29%29) and one or more arguments for [unsafe-fl-](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fl-%29%29) and [unsafe-fl/](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fl%2F%29%29).\n\n> ```\n(unsafe-fl= a b ...) → boolean?\n  a : flonum?\n  b : flonum?\n\n([unsafe-fl\n\n(unsafe-fl> a b ...)  →  boolean?\n  a : flonum?\n  b : flonum?\n\n([unsafe-fl\n\n(unsafe-fl>= a b ...)  →  boolean?\n  a : flonum?\n  b : flonum?\n\n(unsafe-flmin a b ...)  →  flonum?\n  a : flonum?\n  b : flonum?\n\n(unsafe-flmax a b ...)  →  flonum?\n  a : flonum?\n  b : flonum?\n```"} {"text": "### 17.1 Unsafe Numeric Operations\nFor flonums: Unchecked versions of fl=, fl<, fl>, fl<=, fl>=, flmin, and flmax.\nChanged in version 7.0.0.13 of package base: Allow one or more argument, instead of allowing just two.\n> ```\n(unsafe-flround a) → flonum?\n  a : flonum?\n(unsafe-flfloor a)  →  flonum?\n  a : flonum?\n(unsafe-flceiling a)  →  flonum?\n  a : flonum?\n(unsafe-fltruncate a)  →  flonum?\n  a : flonum?```\nFor [flonums](numbers.html#%28tech._flonum%29): Unchecked (potentially) versions of [flround](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flround%29%29), [flfloor](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flfloor%29%29), [flceiling](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flceiling%29%29), and [fltruncate](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._fltruncate%29%29). Currently, these bindings are simply aliases for the corresponding safe bindings.\n> ```\n(unsafe-flsingle a)  →  flonum?\n  a : flonum?"} {"text": "### 17.1 Unsafe Numeric Operations\n```\nFor flonums: Unchecked (potentially) version of flsingle.\n\nAdded in version 7.8.0.7 of package base.\n\n> ```\n(flbit-field a start end)  →  exact-nonnegative-integer?\n  a : flonum?\n  start : (integer-in 0 64)\n  end : (integer-in 0 64)```\n\n\nFor [flonums](numbers.html#%28tech._flonum%29): Unchecked version of [flbit-field](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flbit-field%29%29).\n\nAdded in version 7.8.0.7 of package base.\n\n> ```\n(unsafe-flsin a)  →  flonum?\n  a : flonum?\n\n(unsafe-flcos a)  →  flonum?\n  a : flonum?\n\n(unsafe-fltan a)  →  flonum?\n  a : flonum?\n\n(unsafe-flasin a)  →  flonum?\n  a : flonum?\n\n(unsafe-flacos a)  →  flonum?\n  a : flonum?\n\n(unsafe-flatan a)  →  flonum?\n  a : flonum?\n\n(unsafe-fllog a)  →  flonum?\n  a : flonum?\n\n(unsafe-flexp a)  →  flonum?\n  a : flonum?\n\n(unsafe-flsqrt a)  →  flonum?\n  a : flonum?\n\n(unsafe-flexpt a b)  →  flonum?\n  a : flonum?\n  b : flonum?\n```\nFor flonums: Unchecked (potentially) versions of flsin, flcos, fltan, flasin, flacos, flatan, fllog, flexp, flsqrt, and flexpt. Currently, some of these bindings are simply aliases for the corresponding safe bindings.\n> ```\n(unsafe-make-flrectangular a b)\n  →   ( and/c complex?\n> ( lambda ( c ) ( flonum? ( real-part c ) ) )\n> ( lambda ( c ) ( flonum? ( imag-part c ) ) ) )\n  a : flonum?\n  b : flonum?\n(unsafe-flreal-part a)  →  flonum?\n   a   :   ( and/c complex?\n> ( lambda ( c ) ( flonum? ( real-part c ) ) )\n> ( lambda ( c ) ( flonum? ( imag-part c ) ) ) )\n(unsafe-flimag-part a)  →  flonum?\n   a   :   ( and/c complex?"} {"text": "### 17.1 Unsafe Numeric Operations\n> ( lambda ( c ) ( flonum? ( real-part c ) ) )\n> ( lambda ( c ) ( flonum? ( imag-part c ) ) ) )```\nFor [flonums](numbers.html#%28tech._flonum%29): Unchecked versions of [make-flrectangular](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._make-flrectangular%29%29), [flreal-part](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flreal-part%29%29), and [flimag-part](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flimag-part%29%29).\n> ```\n(unsafe-fx → fl a)  →  flonum?\n  a : fixnum?\n(unsafe-fl → fx a)  →  fixnum?\n  a : flonum?\n```\nUnchecked versions of fx → fl and fl → fx.\n\nChanged in version 7.7.0.8 of package base: Changed unsafe-fl → fx to truncate.\n\n> ```\n(unsafe-flrandom rand-gen)  →  (and flonum? (>/c 0) ([```\n\n\nUnchecked version of [flrandom](flonums.html#%28def._%28%28lib._racket%2Fflonum..rkt%29._flrandom%29%29).\n\n### 17.2 Unsafe Character Operations\n\n> ```\n(unsafe-char=? a b ...) → boolean?\n  a : char?\n  b : char?\n\n([unsafe-char\n\n(unsafe-char>? a b ...)  →  boolean?\n  a : char?\n  b : char?\n\n([unsafe-char\n\n(unsafe-char>=? a b ...)  →  boolean?\n  a : char?\n  b : char?\n\n(unsafe-char → integer a)  →  fixnum?\n  a : char?\n```\n(parameter)\t→\t\n(-> parameter)```"} {"text": "### 17.1 Unsafe Numeric Operations\nUnsafe variants of [car](pairs.html#%28def._%28%28quote._~23~25kernel%29._car%29%29), [cdr](pairs.html#%28def._%28%28quote._~23~25kernel%29._cdr%29%29), [mcar](mpairs.html#%28def._%28%28quote._~23~25kernel%29._mcar%29%29), [mcdr](mpairs.html#%28def._%28%28quote._~23~25kernel%29._mcdr%29%29), [set-mcar!](mpairs.html#%28def._%28%28quote._~23~25kernel%29._set-mcar%21%29%29), and [set-mcdr!](mpairs.html#%28def._%28%28quote._~23~25kernel%29._set-mcdr%21%29%29).\n> ```\n(unsafe-cons-list v rest)  →  (and/c pair? list?)\n  v : any/c\n  rest : list?\n```\nUnsafe variant of cons that produces a pair that claims to be a list—without checking whether rest is a list.\n\n> ```\n(unsafe-list-ref lst pos)  →  any/c\n  lst : pair?\n  pos : (and/c exact-nonnegative-integer? fixnum?)\n\n(unsafe-list-tail lst pos)  →  any/c\n  lst : any/c\n  pos : (and/c exact-nonnegative-integer? fixnum?)```\n\n\nUnsafe variants of [list-ref](pairs.html#%28def._%28%28quote._~23~25kernel%29._list-ref%29%29) and [list-tail](pairs.html#%28def._%28%28quote._~23~25kernel%29._list-tail%29%29), where pos must be a [fixnum](numbers.html#%28tech._fixnum%29), and lst must start with at least ([add1](generic-numbers.html#%28def._%28%28quote._~23~25kernel%29._add1%29%29) pos) (for [unsafe-list-ref](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-list-ref%29%29)) or pos (for [unsafe-list-tail](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-list-tail%29%29)) pairs.\n\n> ```\n(parameter)\t→\t\n(-> unsafe-set-immutable-cdr! p v)\n```\n(parameter)\t→\t\n(-> unsafe-set-box! b k)```"} {"text": "### 17.1 Unsafe Numeric Operations\nUnsafe versions of [unbox](boxes.html#%28def._%28%28quote._~23~25kernel%29._unbox%29%29) and [set-box!](boxes.html#%28def._%28%28quote._~23~25kernel%29._set-box%21%29%29), where the box\\* variants can be faster but do not work on [impersonators](chaperones.html#%28tech._impersonator%29).\n> ```\n(unsafe-box*-cas! loc old new)  →  boolean?\n  loc : box?\n  old : any/c\n  new : any/c\n```\n(parameter)\t→\t\n(-> unsafe-vector-ref v k)```\n\n\nUnsafe versions of [vector-length](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector-length%29%29), [vector-ref](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector-ref%29%29), [vector-set!](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector-set%21%29%29), [vector-cas!](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector-cas%21%29%29), [vector-copy](vectors.html#%28def._%28%28lib._racket%2Fvector..rkt%29._vector-copy%29%29), [vector-set/copy](vectors.html#%28def._%28%28lib._racket%2Fvector..rkt%29._vector-set%2Fcopy%29%29), and [vector-append](vectors.html#%28def._%28%28lib._racket%2Fvector..rkt%29._vector-append%29%29), where the vector\\* variants can be faster but do not work on [impersonators](chaperones.html#%28tech._impersonator%29).\n\nA vector’s size can never be larger than a [fixnum](numbers.html#%28tech._fixnum%29), so even [vector-length](vectors.html#%28def._%28%28quote._~23~25kernel%29._vector-length%29%29) always returns a fixnum.\n\nChanged in version 6.11.0.2 of package base: Added [unsafe-vector*-cas!](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-vector%2A-cas%21%29%29). \nChanged in version 8.11.1.9: Added [unsafe-vector-copy](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-vector-copy%29%29), [unsafe-vector*-copy](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-vector%2A-copy%29%29), [unsafe-vector-set/copy](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-vector-set%2Fcopy%29%29), [unsafe-vector*-set/copy](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-vector%2A-set%2Fcopy%29%29), [unsafe-vector-append](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-vector-append%29%29), and [unsafe-vector*-append](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-vector%2A-append%29%29).\n\n> ```\n(unsafe-vector* → immutable-vector! v)\n  →  (and/c vector? immutable?)\n  v : (and/c vector? (not/c impersonator?))\n```"} {"text": "### 17.1 Unsafe Numeric Operations\nSimilar to vector → immutable-vector, but potentially destroys v and reuses it space, so v must not be used after calling unsafe-vector* → immutable-vector!.\nAdded in version 7.7.0.6 of package base.\n> ```\n(ch)\t → \t\n( → unsafe-string-ref str k)```\nUnsafe versions of [string-length](strings.html#%28def._%28%28quote._~23~25kernel%29._string-length%29%29), [string-ref](strings.html#%28def._%28%28quote._~23~25kernel%29._string-ref%29%29), and [string-set!](strings.html#%28def._%28%28quote._~23~25kernel%29._string-set%21%29%29). The [unsafe-string-ref](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-string-ref%29%29) procedure can be used only when the result will be a Latin-1 character. A string’s size can never be larger than a [fixnum](numbers.html#%28tech._fixnum%29) (so even [string-length](strings.html#%28def._%28%28quote._~23~25kernel%29._string-length%29%29) always returns a fixnum).\n> ```\n(unsafe-string → immutable-string! str)\n  →  (and/c string? immutable?)\n  str : string?"} {"text": "### 17.1 Unsafe Numeric Operations\n```\n(parameter)\t→\t\n(-> parameter)```\n\n\nUnsafe versions of [bytes-length](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._bytes-length%29%29), [bytes-ref](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._bytes-ref%29%29), [bytes-set!](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._bytes-set%21%29%29), and [bytes-copy!](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._bytes-copy%21%29%29). A bytes’s size can never be larger than a [fixnum](numbers.html#%28tech._fixnum%29) (so even [bytes-length](bytestrings.html#%28def._%28%28quote._~23~25kernel%29._bytes-length%29%29) always returns a fixnum).\n\nChanged in version 7.5.0.15 of package base: Added [unsafe-bytes-copy!](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-bytes-copy%21%29%29).\n\n> ```\n(unsafe-bytes → immutable-bytes! bstr)\n  →  (and/c bytes? immutable?)\n  bstr : bytes?\n```\n(parameter)\t→\t\n(-> parameter)```\nUnsafe versions of [fxvector-length](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxvector-length%29%29), [fxvector-ref](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxvector-ref%29%29), and [fxvector-set!](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxvector-set%21%29%29). A [fxvector](fixnums.html#%28tech._fxvector%29)’s size can never be larger than a [fixnum](numbers.html#%28tech._fixnum%29) (so even [fxvector-length](fixnums.html#%28def._%28%28lib._racket%2Ffixnum..rkt%29._fxvector-length%29%29) always returns a fixnum).\n> ```\n(parameter)\t→\t\n(-> unsafe-flvector-ref v k)"} {"text": "### 17.1 Unsafe Numeric Operations\n```\n(parameter)\t→\t\n(-> unsafe-f64vector-set! vec k n)```\n\n\nUnsafe versions of [f64vector-ref](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=foreign&rel=homogeneous-vectors.html%23%2528def._%2528%2528lib._ffi%252Fvector..rkt%2529._f64vector-ref%2529%2529&version=8.18.0.13) and [f64vector-set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=foreign&rel=homogeneous-vectors.html%23%2528def._%2528%2528lib._ffi%252Fvector..rkt%2529._f64vector-set%2521%2529%2529&version=8.18.0.13).\n\n> ```\n(parameter)\t→\t\n(-> integer-in -32768 32767)\n```\n(parameter)\t→\t\n(-> integer-in 0 65535)```\nUnsafe versions of [u16vector-ref](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=foreign&rel=homogeneous-vectors.html%23%2528def._%2528%2528lib._ffi%252Fvector..rkt%2529._u16vector-ref%2529%2529&version=8.18.0.13) and [u16vector-set!](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=foreign&rel=homogeneous-vectors.html%23%2528def._%2528%2528lib._ffi%252Fvector..rkt%2529._u16vector-set%2521%2529%2529&version=8.18.0.13).\n> ```\n(stencil-vector-mask-width)\t→\t\n(-> integer-in 0 (sub1 (expt 2 (stencil-vector-mask-width))))"} {"text": "### 17.1 Unsafe Numeric Operations\n```\n(parameter)\t→\t\n(-> unsafe-struct-set! v k val)```\n\n\nUnsafe field access and update for an instance of a structure type, where the struct\\* variants can be faster but do not work on [impersonators](chaperones.html#%28tech._impersonator%29). The index k must be between 0 (inclusive) and the number of fields in the structure (exclusive). In the case of [unsafe-struct-set!](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-struct-set%21%29%29), [unsafe-struct*-set!](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-struct%2A-set%21%29%29), and [unsafe-struct*-cas!](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-struct%2A-cas%21%29%29), the field must be mutable. The [unsafe-struct*-cas!](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-struct%2A-cas%21%29%29) operation is analogous to [box-cas!](boxes.html#%28def._%28%28quote._~23~25kernel%29._box-cas%21%29%29) to perform an atomic compare-and-set.\n\nChanged in version 6.11.0.2 of package base: Added [unsafe-struct*-cas!](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-struct%2A-cas%21%29%29).\n\n> ```\n(unsafe-struct*-type v)  →  struct-type?\n  v : any/c\n```\nSimilar to struct-info, but without an inspector check, returning only the first result, and without support for impersonators.\nAdded in version 8.8.0.3 of package base.\n> ```\n(unsafe-mutable-hash-iterate-first hash)  →  (or/c #f any/c)\n  hash : (and/c hash? (not/c immutable?) hash-strong?)"} {"text": "### 17.1 Unsafe Numeric Operations\n(unsafe-mutable-hash-iterate-next hash pos)  →  (or/c #f any/c)\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  pos : any/c\n(unsafe-mutable-hash-iterate-key hash pos)  →  any/c\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  pos : any/c\n(unsafe-mutable-hash-iterate-key   hash        \n    pos        \n    bad-index-v)   →   any/c\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-mutable-hash-iterate-value   hash        \n    pos)   →   any/c\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  pos : any/c\n(unsafe-mutable-hash-iterate-value   hash        \n    pos        \n    bad-index-v)   →   any/c\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-mutable-hash-iterate-key+value   hash        \n    pos)   →   any/c   any/c\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  pos : any/c\n(unsafe-mutable-hash-iterate-key+value   hash  \n    pos  \n    bad-index-v)  \n  →   any/c   any/c\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-mutable-hash-iterate-pair hash pos)  →  pair?\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  pos : any/c\n(unsafe-mutable-hash-iterate-pair   hash        \n    pos        \n    bad-index-v)   →   pair?\n  hash : (and/c hash? (not/c immutable?) hash-strong?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-immutable-hash-iterate-first hash)  →  (or/c #f any/c)\n  hash : (and/c hash? immutable?)"} {"text": "### 17.1 Unsafe Numeric Operations\n(unsafe-immutable-hash-iterate-next   hash        \n    pos)   →   (or/c #f any/c)\n  hash : (and/c hash? immutable?)\n  pos : any/c\n(unsafe-immutable-hash-iterate-key   hash        \n    pos)   →   any/c\n  hash : (and/c hash? immutable?)\n  pos : any/c\n(unsafe-immutable-hash-iterate-key   hash        \n    pos        \n    bad-index-v)   →   any/c\n  hash : (and/c hash? immutable?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-immutable-hash-iterate-value   hash        \n    pos)   →   any/c\n  hash : (and/c hash? immutable?)\n  pos : any/c\n(unsafe-immutable-hash-iterate-value   hash        \n    pos        \n    bad-index-v)   →   any/c\n  hash : (and/c hash? immutable?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-immutable-hash-iterate-key+value   hash        \n    pos)   →   any/c   any/c\n  hash : (and/c hash? immutable?)\n  pos : any/c\n(unsafe-immutable-hash-iterate-key+value   hash  \n    pos  \n    bad-index-v)  \n  →   any/c   any/c\n  hash : (and/c hash? immutable?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-immutable-hash-iterate-pair   hash        \n    pos)   →   pair?\n  hash : (and/c hash? immutable?)\n  pos : any/c\n(unsafe-immutable-hash-iterate-pair   hash        \n    pos        \n    bad-index-v)   →   pair?\n  hash : (and/c hash? immutable?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-weak-hash-iterate-first hash)  →  (or/c #f any/c)\n  hash : (and/c hash? hash-weak?)\n(unsafe-weak-hash-iterate-next hash pos)  →  (or/c #f any/c)\n  hash : (and/c hash? hash-weak?)\n  pos : any/c"} {"text": "### 17.1 Unsafe Numeric Operations\n(unsafe-weak-hash-iterate-key hash pos)  →  any/c\n  hash : (and/c hash? hash-weak?)\n  pos : any/c\n(unsafe-weak-hash-iterate-key   hash        \n    pos        \n    bad-index-v)   →   any/c\n  hash : (and/c hash? hash-weak?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-weak-hash-iterate-value hash pos)  →  any/c\n  hash : (and/c hash? hash-weak?)\n  pos : any/c\n(unsafe-weak-hash-iterate-value   hash        \n    pos        \n    bad-index-v)   →   any/c\n  hash : (and/c hash? hash-weak?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-weak-hash-iterate-key+value   hash        \n    pos)   →   any/c   any/c\n  hash : (and/c hash? hash-weak?)\n  pos : any/c\n(unsafe-weak-hash-iterate-key+value   hash        \n    pos        \n    bad-index-v)   →   any/c   any/c\n  hash : (and/c hash? hash-weak?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-weak-hash-iterate-pair hash pos)  →  pair?\n  hash : (and/c hash? hash-weak?)\n  pos : any/c\n(unsafe-weak-hash-iterate-pair   hash        \n    pos        \n    bad-index-v)   →   pair?\n  hash : (and/c hash? hash-weak?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-ephemeron-hash-iterate-first hash)  →  (or/c #f any/c)\n  hash : (and/c hash? hash-ephemeron?)\n(unsafe-ephemeron-hash-iterate-next   hash        \n    pos)   →   (or/c #f any/c)\n  hash : (and/c hash? hash-ephemeron?)\n  pos : any/c\n(unsafe-ephemeron-hash-iterate-key   hash        \n    pos)   →   any/c\n  hash : (and/c hash? hash-ephemeron?)\n  pos : any/c\n(unsafe-ephemeron-hash-iterate-key   hash        \n    pos        \n    bad-index-v)   →   any/c"} {"text": "### 17.1 Unsafe Numeric Operations\n  hash : (and/c hash? hash-ephemeron?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-ephemeron-hash-iterate-value   hash        \n    pos)   →   any/c\n  hash : (and/c hash? hash-ephemeron?)\n  pos : any/c\n(unsafe-ephemeron-hash-iterate-value   hash        \n    pos        \n    bad-index-v)   →   any/c\n  hash : (and/c hash? hash-ephemeron?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-ephemeron-hash-iterate-key+value   hash        \n    pos)   →   any/c   any/c\n  hash : (and/c hash? hash-ephemeron?)\n  pos : any/c\n(unsafe-ephemeron-hash-iterate-key+value   hash  \n    pos  \n    bad-index-v)  \n  →   any/c   any/c\n  hash : (and/c hash? hash-ephemeron?)\n  pos : any/c\n  bad-index-v : any/c\n(unsafe-ephemeron-hash-iterate-pair   hash        \n    pos)   →   pair?\n  hash : (and/c hash? hash-ephemeron?)\n  pos : any/c\n(unsafe-ephemeron-hash-iterate-pair   hash        \n    pos        \n    bad-index-v)   →   pair?\n  hash : (and/c hash? hash-ephemeron?)\n  pos : any/c\n  bad-index-v : any/c```\nUnsafe versions of [hash-iterate-key](hashtables.html#%28def._%28%28quote._~23~25kernel%29._hash-iterate-key%29%29) and similar procedures. These operations support [chaperones](chaperones.html#%28tech._chaperone%29) and [impersonators](chaperones.html#%28tech._impersonator%29)."} {"text": "### 17.1 Unsafe Numeric Operations\nEach unsafe ...-first and ...-next procedure may return, instead of a number index, an internal representation of a view into the hash structure, enabling faster iteration. The result of these ...-first and ...-next functions should be given as pos to the corresponding unsafe accessor functions.\nIf the pos provided to an accessor function for a mutable hash was formerly a [valid hash index](hashtables.html#%28tech._valid._hash._index%29) but is no longer a [valid hash index](hashtables.html#%28tech._valid._hash._index%29) for hash, and if bad-index-v is not provided, then the [exn:fail:contract](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3acontract%29%29) exception is raised. No behavior is specified for a pos that was never a [valid hash index](hashtables.html#%28tech._valid._hash._index%29) for hash. Note that bad-index-v argument is technically not useful for the unsafe-immutable-hash-iterate- functions, since an index cannot become invalid for an immutable hash.\nAdded in version 6.4.0.6 of package base. \nChanged in version 7.0.0.10: Added the optional bad-index-v argument. \nChanged in version 8.0.0.10: Added ephemeron variants.\n> ```\n(unsafe-make-srcloc   source        \n    line        \n    column        \n    position        \n    span)   →   srcloc?\n  source : any/c\n  line : (or/c exact-positive-integer? #f)\n  column : (or/c exact-nonnegative-integer? #f)\n  position : (or/c exact-positive-integer? #f)\n  span : (or/c exact-nonnegative-integer? #f)"} {"text": "### 17.1 Unsafe Numeric Operations\n```\nUnsafe version of srcloc.\n\nAdded in version 7.2.0.10 of package base.\n\n### 17.4 Unsafe Extflonum Operations\n\n> ```\n(unsafe-extfl+ a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?\n\n(unsafe-extfl- a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?\n\n(unsafe-extfl* a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?\n\n(unsafe-extfl/ a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?\n\n(unsafe-extflabs a)  →  extflonum?\n  a : extflonum?```\n\n\nUnchecked versions of [extfl+](extflonums.html#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extfl%2B%29%29), [extfl-](extflonums.html#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extfl-%29%29), [extfl*](extflonums.html#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extfl%2A%29%29), [extfl/](extflonums.html#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extfl%2F%29%29), and [extflabs](extflonums.html#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extflabs%29%29).\n\n> ```\n(unsafe-extfl= a b) → boolean?\n  a : extflonum?\n  b : extflonum?\n\n([unsafe-extfl\n\n(unsafe-extfl> a b)  →  boolean?\n  a : extflonum?\n  b : extflonum?\n\n([unsafe-extfl\n\n(unsafe-extfl>= a b)  →  boolean?\n  a : extflonum?\n  b : extflonum?\n\n(unsafe-extflmin a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?\n\n(unsafe-extflmax a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?\n```\nUnchecked versions of extfl=, extfl<, extfl>, extfl<=, extfl>=, extflmin, and extflmax.\n> ```\n(unsafe-extflround a) → extflonum?\n  a : extflonum?\n(unsafe-extflfloor a)  →  extflonum?\n  a : extflonum?"} {"text": "### 17.1 Unsafe Numeric Operations\n(unsafe-extflceiling a)  →  extflonum?\n  a : extflonum?\n(unsafe-extfltruncate a)  →  extflonum?\n  a : extflonum?```\nUnchecked (potentially) versions of [extflround](extflonums.html#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extflround%29%29), [extflfloor](extflonums.html#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extflfloor%29%29), [extflceiling](extflonums.html#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extflceiling%29%29), and [extfltruncate](extflonums.html#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extfltruncate%29%29). Currently, these bindings are simply aliases for the corresponding safe bindings.\n> ```\n(unsafe-extflsin a)  →  extflonum?\n  a : extflonum?\n(unsafe-extflcos a)  →  extflonum?\n  a : extflonum?\n(unsafe-extfltan a)  →  extflonum?\n  a : extflonum?\n(unsafe-extflasin a)  →  extflonum?\n  a : extflonum?\n(unsafe-extflacos a)  →  extflonum?\n  a : extflonum?\n(unsafe-extflatan a)  →  extflonum?\n  a : extflonum?\n(unsafe-extfllog a)  →  extflonum?\n  a : extflonum?\n(unsafe-extflexp a)  →  extflonum?\n  a : extflonum?\n(unsafe-extflsqrt a)  →  extflonum?\n  a : extflonum?\n(unsafe-extflexpt a b)  →  extflonum?\n  a : extflonum?\n  b : extflonum?"} {"text": "### 17.1 Unsafe Numeric Operations\n```\nUnchecked (potentially) versions of extflsin, extflcos, extfltan, extflasin, extflacos, extflatan, extfllog, extflexp, extflsqrt, and extflexpt. Currently, some of these bindings are simply aliases for the corresponding safe bindings.\n\n> ```\n(unsafe-fx → extfl a)  →  extflonum?\n  a : fixnum?\n\n(unsafe-extfl → fx a)  →  fixnum?\n  a : extflonum?```\n\n\nUnchecked (potentially) versions of [fx->extfl](extflonums.html#%28def._%28%28lib._racket%2Fextflonum..rkt%29._fx-~3eextfl%29%29) and [extfl->fx](extflonums.html#%28def._%28%28lib._racket%2Fextflonum..rkt%29._extfl-~3efx%29%29).\n\nChanged in version 7.7.0.8 of package base: Changed [unsafe-fl->fx](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-fl-~3efx%29%29) to truncate.\n\n> ```\n(parameter)\t→\t\n(-> unsafe-extflvector-ref v k)\n```\nUnchecked versions of extflvector-length, extflvector-ref, and extflvector-set!. A extflvector’s size can never be larger than a fixnum (so even extflvector-length always returns a fixnum)."} {"text": "### 17.5 Unsafe Impersonators and Chaperones\n> ```\n(unsafe-impersonate-procedure proc\n    replacement-proc  \n    prop  \n    prop-val ...  \n    ...)  \n  →  (and/c procedure? impersonator?)\n  proc : procedure?\n  replacement-proc : procedure?\n  prop : impersonator-property?\n  prop-val : any```\nLike [impersonate-procedure](chaperones.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%29%29), but assumes that replacement-proc calls proc itself. When the result of [unsafe-impersonate-procedure](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-impersonate-procedure%29%29) is applied to arguments, the arguments are passed on to replacement-proc directly, ignoring proc. At the same time, [impersonator-of?](chaperones.html#%28def._%28%28quote._~23~25kernel%29._impersonator-of~3f%29%29) reports #t when given the result of [unsafe-impersonate-procedure](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-impersonate-procedure%29%29) and proc."} {"text": "### 17.5 Unsafe Impersonators and Chaperones\nIf proc is itself an impersonator that is derived from [impersonate-procedure*](chaperones.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%2A%29%29) or [chaperone-procedure*](chaperones.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._chaperone-procedure%2A%29%29), beware that replacement-proc will not be able to call it correctly. Specifically, the impersonator produced by [unsafe-impersonate-procedure](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-impersonate-procedure%29%29) will not get passed to a wrapper procedure that was supplied to [impersonate-procedure*](chaperones.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%2A%29%29) or [chaperone-procedure*](chaperones.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._chaperone-procedure%2A%29%29) to generate proc.\nFinally, unlike [impersonate-procedure](chaperones.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%29%29), [unsafe-impersonate-procedure](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-impersonate-procedure%29%29) does not specially handle [impersonator-prop:application-mark](chaperones.html#%28def._%28%28quote._~23~25kernel%29._impersonator-prop~3aapplication-mark%29%29) as a prop."} {"text": "### 17.5 Unsafe Impersonators and Chaperones\nThe unsafety of [unsafe-impersonate-procedure](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-impersonate-procedure%29%29) is limited to the above differences from [impersonate-procedure](chaperones.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%29%29). The contracts on the arguments of [unsafe-impersonate-procedure](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-impersonate-procedure%29%29) are checked when the arguments are supplied.\nAs an example, assuming that f accepts a single argument and is not derived from [impersonate-procedure*](chaperones.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%2A%29%29) or [chaperone-procedure*](chaperones.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._chaperone-procedure%2A%29%29), then\n> ```racket\n> ( λ ( f )\n> ( unsafe-impersonate-procedure\n> f\n> ( λ ( x )\n> ( if ( number? x )\n> ( error ' no-numbers! )\n> ( f x ) ) ) ) )\n> ```\nis equivalent to\n> ```racket\n> ( λ ( f )\n> ( impersonate-procedure\n> f\n> ( λ ( x )\n> ( if ( number? x )\n> ( error ' no-numbers! )\n> x ) ) ) )\n> ```"} {"text": "### 17.5 Unsafe Impersonators and Chaperones\nSimilarly, with the same assumptions about f, the following two procedures wrap-f1 and wrap-f2 are almost equivalent; they differ only in the error message produced when their arguments are functions that return multiple values (and that they update different global variables). The version using [unsafe-impersonate-procedure](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-impersonate-procedure%29%29) will signal an error in the [let](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._let%29%29) expression about multiple return values, whereas the one using [impersonate-procedure](chaperones.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%29%29) signals an error from [impersonate-procedure](chaperones.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._impersonate-procedure%29%29) about multiple return values.\n> ```racket\n> ( define log1-args ' ( ) )\n> ( define log1-results ' ( ) )\n> ( define wrap-f1\n> ( λ ( f )\n> ( impersonate-procedure\n> f\n> ( λ ( arg )\n> ( set! log1-args ( cons arg log1-args ) )\n> ( values ( λ ( res )\n> ( set! log1-results ( cons res log1-results ) )\n> res )\n> arg ) ) ) ) )\n> ( define log2-args ' ( ) )\n> ( define log2-results ' ( ) )\n> ( define wrap-f2\n> ( λ ( f )\n> ( unsafe-impersonate-procedure\n> f\n> ( λ ( arg )\n> ( set! log2-args ( cons arg log2-args ) )\n> ( let ( [ res ( f arg ) ] )\n> ( set! log2-results ( cons res log2-results ) )\n> res ) ) ) ) )\n> ```\nAdded in version 6.4.0.4 of package base.\n> ```"} {"text": "### 17.5 Unsafe Impersonators and Chaperones\n(unsafe-chaperone-procedure proc\n    wrapper-proc  \n    prop  \n    prop-val ...  \n    ...)  \n  →  (and/c procedure? chaperone?)\n  proc : procedure?\n  wrapper-proc : procedure?\n  prop : impersonator-property?\n  prop-val : any\n```\nLike unsafe-impersonate-procedure, but creates a chaperone. Since wrapper-proc will be called in lieu of proc, wrapper-proc is assumed to return a chaperone of the value that proc would return.\n\nAdded in version 6.4.0.4 of package base.\n\n> ```\n(unsafe-impersonate-vector vec\n    replacement-vec  \n    prop  \n    prop-val ...  \n    ...)  \n\n  →  (and/c vector? impersonator?)\n  vec : vector?\n  replacement-vec : (and/c vector? (not/c impersonator?))\n  prop : impersonator-property?\n  prop-val : any/c```\n\n\nLike [impersonate-vector](chaperones.html#%28def._%28%28quote._~23~25kernel%29._impersonate-vector%29%29), but instead of going through interposition procedures, all accesses to the impersonator are dispatched to replacement-vec.\n\nThe result of [unsafe-impersonate-vector](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-impersonate-vector%29%29) is an impersonator of vec.\n\nAdded in version 6.9.0.2 of package base.\n\n> ```\n(unsafe-chaperone-vector vec\n    replacement-vec  \n    prop  \n    prop-val ...  \n    ...)  \n\n  →  (and/c vector? chaperone?)\n  vec : vector?\n  replacement-vec : (and/c vector? (not/c impersonator?))\n  prop : impersonator-property?\n  prop-val : any/c\n```\nLike unsafe-impersonate-vector, but the result of unsafe-chaperone-vector is a chaperone of vec."} {"text": "### 17.5 Unsafe Impersonators and Chaperones\nAdded in version 6.9.0.2 of package base."} {"text": "### 17.6 Unsafe Assertions\n> ```\n(unsafe-assert-unreachable)  →  none/c```\nLike [assert-unreachable](unreachable.html#%28def._%28%28quote._~23~25kernel%29._assert-unreachable%29%29), but the contract of [unsafe-assert-unreachable](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-assert-unreachable%29%29) is never satisfied, and the “unsafe” implication is that anything at all can happen if a call to [unsafe-assert-unreachable](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-assert-unreachable%29%29) is reached.\nThe compiler may take advantage of its liberty to pick convenient or efficient behavior in place of a call to [unsafe-assert-unreachable](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-assert-unreachable%29%29). For example, the expression\n> ```racket\n> ( lambda ( x )\n> ( if ( pair? x )\n> ( car x )\n> ( unsafe-assert-unreachable ) ) )\n> ```\nmay be compiled to code equivalent to\n> ([lambda](lambda.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._lambda%29%29) (x) ([unsafe-car](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-car%29%29) x))\nbecause choosing to make ([unsafe-assert-unreachable](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-assert-unreachable%29%29)) behave the same as ([unsafe-car](#%28def._%28%28lib._racket%2Funsafe%2Fops..rkt%29._unsafe-car%29%29) x) makes both branches of the [if](if.html#%28form._%28%28quote._~23~25kernel%29._if%29%29) the same, and then [pair?](pairs.html#%28def._%28%28quote._~23~25kernel%29._pair~3f%29%29) test can be eliminated."} {"text": "### 17.6 Unsafe Assertions\nAdded in version 8.0.0.11 of package base."} {"text": "### 17.7 Unsafe Undefined\n| | |\n|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/unsafe/undefined](#%28mod-path._racket%2Funsafe%2Fundefined%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/unsafe/undefined](#%28mod-path._racket%2Funsafe%2Fundefined%29) library, not [racket/base](index.html) or [racket](index.html)."} {"text": "### 17.7 Unsafe Undefined\nThe constant [unsafe-undefined](#%28def._%28%28lib._racket%2Funsafe%2Fundefined..rkt%29._unsafe-undefined%29%29) is used internally as a placeholder value. For example, it is used by [letrec](let.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._letrec%29%29) as a value for a variable that has not yet been assigned a value. Unlike the undefined value exported by [racket/undefined](undefined.html), however, the [unsafe-undefined](#%28def._%28%28lib._racket%2Funsafe%2Fundefined..rkt%29._unsafe-undefined%29%29) value should not leak as the result of a safe expression, and it should not be passed as an optional argument to a procedure (because it may count as “no value provided”). Expression results that potentially produce [unsafe-undefined](#%28def._%28%28lib._racket%2Funsafe%2Fundefined..rkt%29._unsafe-undefined%29%29) can be guarded by [check-not-unsafe-undefined](#%28def._%28%28lib._racket%2Funsafe%2Fundefined..rkt%29._check-not-unsafe-undefined%29%29), so that an exception can be raised instead of producing an undefined value.\nThe [unsafe-undefined](#%28def._%28%28lib._racket%2Funsafe%2Fundefined..rkt%29._unsafe-undefined%29%29) value is always [eq?](Equality.html#%28def._%28%28quote._~23~25kernel%29._eq~3f%29%29) to itself.\nAdded in version 6.0.1.2 of package base. \nChanged in version 6.90.0.29: Procedures with optional arguments sometimes use the [unsafe-undefined](#%28def._%28%28lib._racket%2Funsafe%2Fundefined..rkt%29._unsafe-undefined%29%29) value internally to mean “no argument supplied.”"} {"text": "### 17.7 Unsafe Undefined\n>
\n

value

\n

[unsafe-undefined](#%28def._%28%28lib._racket%2Funsafe%2Fundefined..rkt%29._unsafe-undefined%29%29) : [any/c](data-structure-contracts.html#%28def._%28%28lib._racket%2Fcontract%2Fprivate%2Fmisc..rkt%29._any%2Fc%29%29)

\nThe unsafe “undefined” constant.\nSee above for important constraints on the use of [unsafe-undefined](#%28def._%28%28lib._racket%2Funsafe%2Fundefined..rkt%29._unsafe-undefined%29%29).\n> ```\n(parameter)\t→\n```\n(parameter)\t→```\n\n\nThe same as [check-not-unsafe-undefined](#%28def._%28%28lib._racket%2Funsafe%2Fundefined..rkt%29._check-not-unsafe-undefined%29%29), except that the error message (if any) is along the lines of “sym: undefined; assignment before initialization.”\n\n> ```\n(chaperone-struct-unsafe-undefined v)  →  any/c\n  v : any/c\n```\n(find-config-dir)\t→\t\n(-> such as current-load-relative-directory)```\nProduces a list of paths, which is normally used to initialize [current-library-collection-paths](#%28def._%28%28quote._~23~25kernel%29._current-library-collection-paths%29%29), as follows:"} {"text": "### 17.7 Unsafe Undefined\n- The path produced by ([build-path](Manipulating_Paths.html#%28def._%28%28quote._~23~25kernel%29._build-path%29%29) ([find-system-path](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._find-system-path%29%29) 'addon-dir) name \"collects\") is the first element of the default collection path list, unless the value of the [use-user-specific-search-paths](#%28def._%28%28quote._~23~25kernel%29._use-user-specific-search-paths%29%29) parameter is #f.\n- Extra directories provided in pre-extras are included next to the default collection path list, converted to complete paths relative to the executable.\n- If the directory specified by ([find-system-path](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._find-system-path%29%29) 'collects-dir) is absolute, or if it is relative (to the executable) and it exists, then it is added to the end of the default collection path list.\n- Extra directories provided in post-extras are included last in the default collection path list, converted to complete paths relative to the executable.\n- If config has a value for 'collects-search-dirs, then it is used in place of the default collection path list (as constructed by the preceding three bullets), and the default is spliced in place of any #f within the 'collects-search-dirs list. If config does not have a 'collects-search-dirs value, then the default collection path list is used."} {"text": "### 17.7 Unsafe Undefined\n- If the PLTCOLLECTS environment variable is defined, it is combined with the default list using [path-list-string->path-list](Filesystem.html#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._path-list-string-~3epath-list%29%29), as long as the value of [use-user-specific-search-paths](#%28def._%28%28quote._~23~25kernel%29._use-user-specific-search-paths%29%29) is true. If it is not defined or if the value [use-user-specific-search-paths](#%28def._%28%28quote._~23~25kernel%29._use-user-specific-search-paths%29%29) is #f, the collection path list as constructed by the preceding four bullets is used directly.\n Note that on Unix and Mac OS, paths are separated by :, and on Windows by ;. Also, [path-list-string->path-list](Filesystem.html#%28def._%28%28lib._racket%2Fprivate%2Fmisc..rkt%29._path-list-string-~3epath-list%29%29) splices the default paths at an empty path, for example, with many Unix shells you can set PLTCOLLECTS to \":‘pwd‘\", \"‘pwd‘:\", or \"‘pwd‘\" to specify search the current directory after, before, or instead of the default paths, respectively.\nChanged in version 8.4.0.3 of package base: Added the config and name arguments.\n> ```\n(find-library-collection-links [config] name)\n  →  (listof (or/c #f (and/c path? complete-path?)))\n  config : hash? = (read-installation-configuration-table)\n  name : (get-installation-name config)"} {"text": "### 17.7 Unsafe Undefined\n```\n(find-config-dir)\t→\t\n(-> regexp-match? #rx\"[.]rkt$\" file)```\n\n\nReturns the path to the file indicated by file in the collection specified by the collections, where the second collection (if any) names a sub-collection, and so on. The search uses the values of [current-library-collection-links](#%28def._%28%28quote._~23~25kernel%29._current-library-collection-links%29%29) and [current-library-collection-paths](#%28def._%28%28quote._~23~25kernel%29._current-library-collection-paths%29%29).\n\n> > > See also [collection-search](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=collection-search.html%23%2528def._%2528%2528lib._setup%252Fcollection-search..rkt%2529._collection-search%2529%2529&version=8.18.0.13) in [setup/collection-search](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=collection-search.html&version=8.18.0.13).\n\nIf file is not found, but file ends in \".rkt\" and a file with the suffix \".ss\" exists, then the directory of the \".ss\" file is used. If file is not found and the \".rkt\"/\".ss\" conversion does not apply, but a directory corresponding to the collections is found, then a path using the first such directory is returned.\n\nIf check-compiled? is true, then the search also depends on [use-compiled-file-paths](eval.html#%28def._%28%28quote._~23~25kernel%29._use-compiled-file-paths%29%29) and [current-compiled-file-roots](eval.html#%28def._%28%28quote._~23~25kernel%29._current-compiled-file-roots%29%29); if file is not found, then a compiled form of file with the suffix \".zo\" is checked in the same way as the default [compiled-load handler](eval.html#%28tech._compiled._load._handler%29). If a compiled file is found, the result from [collection-file-path](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._collection-file-path%29%29) reports the location that file itself would occupy (if it existed) for the found compiled file.\n\nFinally, if the collection is not found, and if fail-proc is provided, then fail-proc is applied to an error message (that does not start \"collection-file-path:\" or otherwise claim a source), and its result is the result of [collection-file-path](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._collection-file-path%29%29). If fail-proc is not provided and the collection is not found, then the [exn:fail:filesystem](exns.html#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._exn~3afail~3afilesystem%29%29) exception is raised.\n\nExamples:\n\n> ```racket\n> > ( collection-file-path \"main.rkt\" \"racket\" \"base\" )\n> #\n> > ( collection-file-path \"sandwich.rkt\" \"bologna\" )\n> collection-file-path: collection not found\n> collection: \"bologna\"\n> in collection directories:\n> /Users/robby/snapshot/racket/racket/collects/\n> ... [260 additional linked and package directories]\n> ```\n\nChanged in version 6.0.1.12 of package base: Added the check-compiled? argument.\n\n> ```\n(collection-path collection ...+) → path?\n  collection : path-string?\n(collection-path   collection        \n    ...+        \n    #:fail fail-proc)   →   any\n\n  collection : path-string?\n  fail-proc : (string? . → . any)\n```"} {"text": "### 17.7 Unsafe Undefined\n(current-library-collection-paths)\t→\t\n(-> listof (and/c path? complete-path?))\n(current-library-collection-paths paths) → void?\n paths\t:\t\n(-> listof (and/c path? complete-path?))```\nParameter that determines a list of complete directory paths for finding libraries (as referenced in [require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29), for example) through the default [module name resolver](Module_Names_and_Loading.html#%28tech._module._name._resolver%29) and for finding paths through [collection-path](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._collection-path%29%29) and [collection-file-path](#%28def._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._collection-file-path%29%29). See [Collection Search Configuration](#%28part._collects-search%29) for more information.\n> ```\n(current-library-collection-links)\t→\t\n(-> listof (or/c #f\n (and/c path? complete-path?)\n (hash/c (or/c (and/c symbol? module-path?) #f)\n (listof (and/c path? complete-path?)))))\n(current-library-collection-links paths) → void?\n paths\t:\t\n(-> listof (or/c #f\n (and/c path? complete-path?)\n (hash/c (or/c (and/c symbol? module-path?) #f)\n (listof (and/c path? complete-path?)))))"} {"text": "### 17.7 Unsafe Undefined\n```\n(use-user-specific-search-paths)\t→\t\n(-> use-user-specific-search-paths on?)```\n\n\nParameter that determines whether user-specific paths, which are in the directory produced by ([find-system-path](Filesystem.html#%28def._%28%28quote._~23~25kernel%29._find-system-path%29%29) 'addon-dir), are included in search paths for collections and other files. For example, the initial value of [find-library-collection-paths](#%28def._%28%28quote._~23~25kernel%29._find-library-collection-paths%29%29) omits the user-specific collection directory when this parameter’s value is #f.\n\nIf -U or --no-user-path argument to racket, then [use-user-specific-search-paths](#%28def._%28%28quote._~23~25kernel%29._use-user-specific-search-paths%29%29) is initialized to #f.\n\n> ```\n(use-collection-link-paths)\t→\t\n(-> use-collection-link-paths on?)\n```\n(read-installation-configuration-table)\t→\t\n(-> and/c hash? immutable?)```\nReturns the content of the installation’s \"config.rktd\" file (see [Installation Configuration and Search Paths](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=raco&rel=config-file.html&version=8.18.0.13)) as long as that content is a [hash table](hashtables.html#%28tech._hash._table%29), and otherwise returns an empty hash table.\nAdded in version 8.4.0.3 of package base.\n------------------------------------------------------------------------"} {"text": "# 18.3 Interactive Help"} {"text": "### 18.3 Interactive Help\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/help]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/help]() and [racket/init](running-sa.html#%28mod-path._racket%2Finit%29) libraries, which means that they are available when the Racket executable is started with no command-line arguments. They are not provided by [racket/base](index.html) or [racket](index.html).\n>
\n

syntax

"} {"text": "# 18.3 Interactive Help\n

[help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29)

([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) string ...)
([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) id)
([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) id #:from module-path)
([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) #:search datum ...)
\nFor general help, see the [main documentation page](../index.html).\nThe [help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) form searches the documentation and opens a web browser (using the user’s selected browser) to display the results.\n> > > See [net/sendurl](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=net&rel=sendurl.html&version=8.18.0.13) for information on how the user’s browser is launched to display help information.\nA simple [help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) or ([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29)) form opens the main documentation page.\nThe ([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) string [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) form—using literal strings, as opposed to expressions that produce strings—performs a string-matching search. For example,\n> ([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) \"web browser\" \"firefox\")"} {"text": "# 18.3 Interactive Help\nsearches the documentation index for references that include the phrase “web browser” or “firefox.”\nA ([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) id) form looks for documentation specific to the current binding of id. For example,\n> ```racket\n> ( require net/url )\n> ( help url->string )\n> ```\nopens a web browser to show the documentation for [url->string](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=net&rel=url.html%23%2528def._%2528%2528lib._net%252Furl..rkt%2529._url-%7E3estring%2529%2529&version=8.18.0.13) from the [net/url](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=net&rel=url.html&version=8.18.0.13) library.\nFor the purposes of [help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29), a [for-label](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-label%29%29) require introduces a binding without actually executing the [net/url](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=net&rel=url.html&version=8.18.0.13) library—for cases when you want to check documentation, but cannot or do not want to run the providing module.\n> ```racket\n> ( require racket/gui ) ; does not work in racket\n> ( require ( for-label racket/gui ) ) ; ok in racket\n> ( help frame% )\n> ```\nIf id has no for-label and normal binding, then [help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) lists all libraries that are known to export a binding for id."} {"text": "# 18.3 Interactive Help\nThe ([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) id #:from module-path) variant is similar to ([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) id), but using only the exports of module-path. (The module-path module is required [for-label](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._for-label%29%29) in a temporary namespace.)\n> ([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) [frame%](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?doc=gui&rel=frame_.html&version=8.18.0.13) #:from racket/gui) ; equivalent to the above\nThe ([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) #:search datum [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)) form is similar to ([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) string [...](stx-patterns.html#%28form._%28%28lib._racket%2Fprivate%2Fstxcase-scheme..rkt%29._......%29%29)), where any non-string form of datum is converted to a string using [display](Writing.html#%28def._%28%28quote._~23~25kernel%29._display%29%29). No datum is evaluated as an expression.\nFor example,\n> ([help](#%28form._%28%28lib._racket%2Fhelp..rkt%29._help%29%29) #:search \"web browser\" firefox)\nalso searches the documentation index for references that include the phrase “web browser” or “firefox.”\n------------------------------------------------------------------------"} {"text": "# 18.4 Interaction Configuration"} {"text": "### 18.4 Interaction Configuration\n| | |\n|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/interaction-info]()) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\nThe bindings documented in this section are provided by the [racket/interaction-info]() library, not [racket/base](index.html) or [racket](index.html).\nThe [racket/interaction-info]() library provides a way to register a langauge’s configuration for a [read](Reading.html#%28def._%28%28quote._~23~25kernel%29._read%29%29)-[eval](eval.html#%28def._%28%28quote._~23~25kernel%29._eval%29%29)-[print](Writing.html#%28def._%28%28quote._~23~25kernel%29._print%29%29) loop and editor.\n> ```\n(current-interaction-info)\t→\t\n(-> or/c #f (vector/c module-path? symbol? any/c))\n(current-interaction-info info) → void?\n info\t:\t\n(-> or/c #f (vector/c module-path? symbol? any/c))"} {"text": "# 18.4 Interaction Configuration\n```\n(parameter)\t→\t\n(-> e.g., in a tool that uses racket/enter)```\n\n\nProcedure variant of [enter!](#%28form._%28%28lib._racket%2Fenter..rkt%29._enter%21%29%29), where verbosity is passed along to [dynamic-rerequire](#%28def._%28%28lib._racket%2Frerequire..rkt%29._dynamic-rerequire%29%29) and re-require-enter? determines whether [dynamic-enter!](#%28def._%28%28lib._racket%2Fenter..rkt%29._dynamic-enter%21%29%29) requires racket/enter in a newly entered namespace.\n\nAdded in version 6.0.0.1 of package base.\n\n#### 18.5.2 Loading and Reloading Modules\n\n| | |\n|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------:|\n|  ([require](require.html#%28form._%28%28lib._racket%2Fprivate%2Fbase..rkt%29._require%29%29) [racket/rerequire](#%28mod-path._racket%2Frerequire%29)) |  package: [base](https://pkgs.racket-lang.org/package/base \"Install this package using `raco pkg install base`\") |\n\nThe bindings documented in this section are provided by the [racket/rerequire](#%28mod-path._racket%2Frerequire%29) library, not [racket/base](index.html) or [racket](index.html).\n\n> ```\n(dynamic-rerequire module-path\n   [ #:verbosity verbosity)   →   (listof path?)\n\n  module-path : module-path?\n  verbosity : (or/c 'all 'reload 'none) = 'reload\n```"} {"text": "# 18.4 Interaction Configuration\n(current-error-port)\t→\t\n(-> string? . → . any)```\nA [parameter](eval-model.html#%28tech._parameter%29) that determines the way that trace output is displayed. The string given to proc is a trace; it does not end with a newline, but it may contain internal newlines. Each call or result is converted into a string using [pretty-print](pretty-print.html#%28def._%28%28lib._racket%2Fpretty..rkt%29._pretty-print%29%29). The parameter’s default value prints the given string followed by a newline to ([current-output-port](port-ops.html#%28def._%28%28quote._~23~25kernel%29._current-output-port%29%29)).\n> ```\n(parameter)\t→"} {"text": "# 18.4 Interaction Configuration\n```\n(current-trace-print-args)\t→\t\n(-> symbol?\n list?\n (listof keyword?)\n list?\n number?\n void?)\n(current-trace-print-args trace-print-args) → void?\n trace-print-args\t:\t\n(-> symbol?\n list?\n (listof keyword?)\n list?\n number?\n void?)```\n\n\nThe value of this parameter is invoked to print out the arguments of a traced call. It receives the name of the function, the function’s ordinary arguments, its keywords, the values of the keywords, and a number indicating the depth of the call.\n\nModifying this and [current-trace-print-results](#%28def._%28%28lib._racket%2Ftrace..rkt%29._current-trace-print-results%29%29) is useful to to get more readable or additional output when tracing syntax transformers. For example, we can use [debug-scopes](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?tag=%28mod-path._.%27debug-scopes.%27%29&version=8.18.0.13) to add scopes information to the trace, (see [debug-scopes](https://plt.cs.northwestern.edu/new-snapshots/new-snapshots/doc/local-redirect/index.html?tag=%28mod-path._.%27debug-scopes.%27%29&version=8.18.0.13) for an example), or remove source location information to just display the shape of the syntax object\n\nIn this example, we update the printers [current-trace-print-args](#%28def._%28%28lib._racket%2Ftrace..rkt%29._current-trace-print-args%29%29) and [current-trace-print-results](#%28def._%28%28lib._racket%2Ftrace..rkt%29._current-trace-print-results%29%29) by storing the current printers (ctpa and ctpr) to cast syntax objects to datum using [syntax->datum](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-~3edatum%29%29) and then pass the transformed arguments and results to the previous printer. When tracing, syntax arguments will be displayed without source location information, shortening the output.\n\nExamples:\n\n> ```racket\n> > ( require ( for-syntax racket/trace ) )\n> > ( begin-for-syntax ( current-trace-print-args ( let ( [ ctpa ( current-trace-print-args ) ] ) ( lambda ( s l kw l2 n ) ( ctpa s ( map syntax->datum l ) kw l2 n ) ) ) ) ( current-trace-print-results ( let ( [ ctpr ( current-trace-print-results ) ] ) ( lambda ( s r n ) ( ctpr s ( map syntax->datum r ) n ) ) ) ) )\n> > ( trace-define-syntax fact ( syntax-rules ( ) [ ( _ x ) 120 ] ) )\n> > ( fact 5 )\n> >(fact '(fact 5)) <120> 120\n> ```\n\nWe must take care when modifying these parameters, especially when the transformation makes assumptions about or changes the type of the argument/result of the traced identifier. This modification of [current-trace-print-args](#%28def._%28%28lib._racket%2Ftrace..rkt%29._current-trace-print-args%29%29) and [current-trace-print-results](#%28def._%28%28lib._racket%2Ftrace..rkt%29._current-trace-print-results%29%29) is an imperative update, and will affect all traced identifiers. This example assumes all arguments and results to all traced functions will be syntax objects, which is the case only if you are only tracing syntax transformers. If used as-is, the above code could result in type errors when tracing both functions and syntax transformers. It would be better to use [syntax->datum](stxops.html#%28def._%28%28quote._~23~25kernel%29._syntax-~3edatum%29%29) only when the argument or result is actually a syntax object, for example, by defining maybe-syntax->datum as follows.\n\nExamples:\n\n> ```racket\n> > ( require ( for-syntax racket/trace ) )\n> > ( begin-for-syntax ( define ( maybe-syntax->datum syn? ) ( if ( syntax? syn? ) ( syntax->datum syn? ) syn? ) ) ( current-trace-print-args ( let ( [ ctpa ( current-trace-print-args ) ] ) ( lambda ( s l kw l2 n ) ( ctpa s ( map maybe-syntax->datum l ) kw l2 n ) ) ) ) ( current-trace-print-results ( let ( [ ctpr ( current-trace-print-results ) ] ) ( lambda ( s l n ) ( ctpr s ( map maybe-syntax->datum l ) n ) ) ) ) ( trace-define ( precompute-fact syn n ) ( datum->syntax syn ( apply * ( build-list n add1 ) ) ) ) )\n> > ( trace-define ( run-time-fact n ) ( apply * ( build-list n add1 ) ) )\n> > ( require ( for-syntax syntax/parse ) )\n> > ( trace-define-syntax ( fact syn ) ( syntax-parse syn [ ( _ x:nat ) ( precompute-fact syn ( syntax->datum #' x ) ) ] [ ( _ x ) #' ( run-time-fact x ) ] ) )\n> > ( fact 5 )\n> >(fact '(fact 5)) >(precompute-fact '(fact 5) 5) <120> 120\n> > ( fact ( + 2 3 ) )\n> >(fact '(fact (+ 2 3))) <'(run-time-fact (+ 2 3))>(run-time-fact 5) <120> 120\n> ```\n\n> ```\n(current-trace-print-results)\t→\t\n(-> symbol?\n list?\n number?\n any)\n(current-trace-print-results trace-print-results) → void?\n trace-print-results\t:\t\n(-> symbol?\n list?\n number?\n any)\n```"} {"text": "# 18.4 Interaction Configuration\n(current-prefix-in)\t→\t\n(-> current-prefix-in prefix)\n(current-prefix-in prefix) → void?\n prefix\t:\t\n(-> current-prefix-in prefix)```\nThis string is used by the default value of [current-trace-print-args](#%28def._%28%28lib._racket%2Ftrace..rkt%29._current-trace-print-args%29%29) indicating that the current line is showing the a call to a traced function.\nIt defaults to \">\".\n> ```\n(current-prefix-out)\t→\t\n(-> current-prefix-out prefix)\n(current-prefix-out prefix) → void?\n prefix\t:\t\n(-> current-prefix-out prefix)\n```\n(E)\t→```\n(struct)\t→\t\n(-> if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._~3d~3e%29%29)\n```\n------------------------------------------------------------------------"}