Dataset Viewer
Auto-converted to Parquet
text
stringlengths
12
127k
# The Racket Guide 8.18.0.13
# The Racket Guide This 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). [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. > > > The source of this manual is available on [GitHub](https://github.com/racket/racket/tree/master/pkgs/racket-doc/scribblings/guide).
# The Racket Guide | | |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| |     [1 Welcome to Racket](intro.html) | |       [1.1 Interacting with Racket](intro.html#%28part._.Interacting_with_.Racket%29) | |       [1.2 Definitions and Interactions](intro.html#%28part._.Definitions_and_.Interactions%29) | |       [1.3 Creating Executables](intro.html#%28part._.Creating_.Executables%29) | |       [1.4 A Note to Readers with Lisp/Scheme Experience](intro.html#%28part._use-module%29) | | | |     [2 Racket Essentials](to-scheme.html) | |       [2.1 Simple Values](Simple_Values.html) | |       [2.2 Simple Definitions and Expressions](syntax-overview.html) | |         [2.2.1 Definitions](syntax-overview.html#%28part._.Definitions%29) | |         [2.2.2 An Aside on Indenting Code](syntax-overview.html#%28part._indentation%29) | |         [2.2.3 Identifiers](syntax-overview.html#%28part._.Identifiers%29) | |         [2.2.4 Function Calls (Procedure Applications)](syntax-overview.html#%28part._.Function_.Calls__.Procedure_.Applications_%29) | |         [2.2.5 Conditionals with if, and, or, and cond](syntax-overview.html#%28part._.Conditionals_with_if__and__or__and_cond%29) | |         [2.2.6 Function Calls, Again](syntax-overview.html#%28part._.Function_.Calls__.Again%29) | |         [2.2.7 Anonymous Functions with lambda](syntax-overview.html#%28part._.Anonymous_.Functions_with_lambda%29) | |         [2.2.8 Local Binding with define, let, and let*](syntax-overview.html#%28part._local-binding-intro%29) | |       [2.3 Lists, Iteration, and Recursion](Lists__Iteration__and_Recursion.html) | |         [2.3.1 Predefined List Loops](Lists__Iteration__and_Recursion.html#%28part._.Predefined_.List_.Loops%29) | |         [2.3.2 List Iteration from Scratch](Lists__Iteration__and_Recursion.html#%28part._.List_.Iteration_from_.Scratch%29) | |         [2.3.3 Tail Recursion](Lists__Iteration__and_Recursion.html#%28part._tail-recursion%29) | |         [2.3.4 Recursion versus Iteration](Lists__Iteration__and_Recursion.html#%28part._.Recursion_versus_.Iteration%29) | |       [2.4 Pairs, Lists, and Racket Syntax](Pairs__Lists__and_Racket_Syntax.html) | |         [2.4.1 Quoting Pairs and Symbols with quote](Pairs__Lists__and_Racket_Syntax.html#%28part._quoting-lists%29) | |         [2.4.2 Abbreviating quote with '](Pairs__Lists__and_Racket_Syntax.html#%28part._.Abbreviating_quote_with__%29) | |         [2.4.3 Lists and Racket Syntax](Pairs__Lists__and_Racket_Syntax.html#%28part._lists-and-syntax%29) | | | |     [3 Built-In Datatypes](datatypes.html) | |       [3.1 Booleans](booleans.html) | |       [3.2 Numbers](numbers.html) | |       [3.3 Characters](characters.html) | |       [3.4 Strings (Unicode)](strings.html) | |       [3.5 Bytes and Byte Strings](bytestrings.html) | |       [3.6 Symbols](symbols.html) | |       [3.7 Keywords](keywords.html) | |       [3.8 Pairs and Lists](pairs.html) | |       [3.9 Vectors](vectors.html) | |       [3.10 Hash Tables](hash-tables.html) | |       [3.11 Boxes](boxes.html) | |       [3.12 Void and Undefined](void_undefined.html) | | | |     [4 Expressions and Definitions](scheme-forms.html) | |       [4.1 Notation](syntax-notation.html) | |       [4.2 Identifiers and Binding](binding.html) | |       [4.3 Function Calls (Procedure Applications)](application.html) | |         [4.3.1 Evaluation Order and Arity](application.html#%28part._.Evaluation_.Order_and_.Arity%29) | |         [4.3.2 Keyword Arguments](application.html#%28part._keyword-args%29) | |         [4.3.3 The apply Function](application.html#%28part._apply%29) | |       [4.4 Functions (Procedures): lambda](lambda.html) | |         [4.4.1 Declaring a Rest Argument](lambda.html#%28part._rest-args%29) | |         [4.4.2 Declaring Optional Arguments](lambda.html#%28part._.Declaring_.Optional_.Arguments%29) | |         [4.4.3 Declaring Keyword Arguments](lambda.html#%28part._lambda-keywords%29) | |         [4.4.4 Arity-Sensitive Functions: case-lambda](lambda.html#%28part._case-lambda%29) | |       [4.5 Definitions: define](define.html) | |         [4.5.1 Function Shorthand](define.html#%28part._.Function_.Shorthand%29) | |         [4.5.2 Curried Function Shorthand](define.html#%28part._.Curried_.Function_.Shorthand%29) | |         [4.5.3 Multiple Values and define-values](define.html#%28part._multiple-values%29) | |         [4.5.4 Internal Definitions](define.html#%28part._intdefs%29) | |       [4.6 Local Binding](let.html) | |         [4.6.1 Parallel Binding: let](let.html#%28part._.Parallel_.Binding__let%29) | |         [4.6.2 Sequential Binding: let*](let.html#%28part._.Sequential_.Binding__let_%29) | |         [4.6.3 Recursive Binding: letrec](let.html#%28part._.Recursive_.Binding__letrec%29) | |         [4.6.4 Named let](let.html#%28part._.Named_let%29) | |         [4.6.5 Multiple Values: let-values, let*-values, letrec-values](let.html#%28part._.Multiple_.Values__let-values__let_-values__letrec-values%29) | |       [4.7 Conditionals](conditionals.html) | |         [4.7.1 Simple Branching: if](conditionals.html#%28part._.Simple_.Branching__if%29) | |         [4.7.2 Combining Tests: and and or](conditionals.html#%28part._and%2Bor%29) | |         [4.7.3 Chaining Tests: cond](conditionals.html#%28part._cond%29) | |       [4.8 Sequencing](begin.html) | |         [4.8.1 Effects Before: begin](begin.html#%28part._.Effects_.Before__begin%29) | |         [4.8.2 Effects After: begin0](begin.html#%28part._.Effects_.After__begin0%29) | |         [4.8.3 Effects If...: when and unless](begin.html#%28part._when%2Bunless%29) | |       [4.9 Assignment: set!](set_.html) | |         [4.9.1 Guidelines for Using Assignment](set_.html#%28part._using-set%21%29) | |         [4.9.2 Multiple Values: set!-values](set_.html#%28part._.Multiple_.Values__set_-values%29) | |       [4.10 Quoting: quote and ’](quote.html) | |       [4.11 Quasiquoting: quasiquote and ‘](qq.html) | |       [4.12 Simple Dispatch: case](case.html) | |       [4.13 Dynamic Binding: parameterize](parameterize.html) | | | |     [5 Programmer-Defined Datatypes](define-struct.html) | |       [5.1 Simple Structure Types: struct](define-struct.html#%28part._.Simple_.Structure_.Types__struct%29) | |       [5.2 Copying and Update](define-struct.html#%28part._struct-copy%29) | |       [5.3 Structure Subtypes](define-struct.html#%28part._struct-subtypes%29) | |       [5.4 Opaque versus Transparent Structure Types](define-struct.html#%28part._trans-struct%29) | |       [5.5 Structure Comparisons](define-struct.html#%28part._struct-equal%29) | |       [5.6 Structure Type Generativity](define-struct.html#%28part._.Structure_.Type_.Generativity%29) | |       [5.7 Prefab Structure Types](define-struct.html#%28part._prefab-struct%29) | |       [5.8 More Structure Type Options](define-struct.html#%28part._struct-options%29) | | | |     [6 Modules](modules.html) | |       [6.1 Module Basics](module-basics.html) | |         [6.1.1 Organizing Modules](module-basics.html#%28part._module-org%29) | |         [6.1.2 Library Collections](module-basics.html#%28part._.Library_.Collections%29) | |         [6.1.3 Packages and Collections](module-basics.html#%28part._packages-and-collections%29) | |         [6.1.4 Adding Collections](module-basics.html#%28part._link-collection%29) | |         [6.1.5 Module References Within a Collection](module-basics.html#%28part._intracollection%29) | |       [6.2 Module Syntax](Module_Syntax.html) | |         [6.2.1 The module Form](Module_Syntax.html#%28part._module-syntax%29) | |         [6.2.2 The #lang Shorthand](Module_Syntax.html#%28part._hash-lang%29) | |         [6.2.3 Submodules](Module_Syntax.html#%28part._submodules%29) | |         [6.2.4 Main and Test Submodules](Module_Syntax.html#%28part._main-and-test%29) | |       [6.3 Module Paths](module-paths.html) | |       [6.4 Imports: require](module-require.html) | |       [6.5 Exports: provide](module-provide.html) | |       [6.6 Assignment and Redefinition](module-set.html) | |       [6.7 Modules and Macros](module-macro.html) | |       [6.8 Protected Exports](protect-out.html) | | | |     [7 Contracts](contracts.html) | |       [7.1 Contracts and Boundaries](contract-boundaries.html) | |         [7.1.1 Contract Violations](contract-boundaries.html#%28part._contracts-amount0%29) | |         [7.1.2 Experimenting with Contracts and Modules](contract-boundaries.html#%28part._.Experimenting_with_.Contracts_and_.Modules%29) | |         [7.1.3 Experimenting with Nested Contract Boundaries](contract-boundaries.html#%28part._contracts-intro-nested%29) | |       [7.2 Simple Contracts on Functions](contract-func.html) | |         [7.2.1 Styles of ->](contract-func.html#%28part._.Styles_of_-_%29) | |         [7.2.2 Using define/contract and ->](contract-func.html#%28part._simple-nested%29) | |         [7.2.3 any and any/c](contract-func.html#%28part._any_and_any_c%29) | |         [7.2.4 Rolling Your Own Contracts](contract-func.html#%28part._contracts-own%29) | |         [7.2.5 Contracts on Higher-order Functions](contract-func.html#%28part._.Contracts_on_.Higher-order_.Functions%29) | |         [7.2.6 Contract Messages with “???”](contract-func.html#%28part._contracts-flat-named-contracts%29) | |         [7.2.7 Dissecting a contract error message](contract-func.html#%28part._contracts-dissecting-contract-errors%29) | |       [7.3 Contracts on Functions in General](contracts-general-functions.html) | |         [7.3.1 Optional Arguments](contracts-general-functions.html#%28part._contracts-optional%29) | |         [7.3.2 Rest Arguments](contracts-general-functions.html#%28part._contracts-rest-args%29) | |         [7.3.3 Keyword Arguments](contracts-general-functions.html#%28part._contracts-keywords%29) | |         [7.3.4 Optional Keyword Arguments](contracts-general-functions.html#%28part._contracts-optional-keywords%29) | |         [7.3.5 Contracts for case-lambda](contracts-general-functions.html#%28part._contracts-case-lambda%29) | |         [7.3.6 Argument and Result Dependencies](contracts-general-functions.html#%28part._contracts-arrow-d%29) | |         [7.3.7 Checking State Changes](contracts-general-functions.html#%28part._contracts-arrow-d-eval-order%29) | |         [7.3.8 Multiple Result Values](contracts-general-functions.html#%28part._contracts-multiple%29) | |         [7.3.9 Fixed but Statically Unknown Arities](contracts-general-functions.html#%28part._contracts-no-domain%29) | |       [7.4 Contracts: A Thorough Example](contracts-first.html) | |       [7.5 Contracts on Structures](contracts-struct.html) | |         [7.5.1 Guarantees for a Specific Value](contracts-struct.html#%28part._contracts-single-struct%29) | |         [7.5.2 Guarantees for All Values](contracts-struct.html#%28part._contracts-define-struct%29) | |         [7.5.3 Checking Properties of Data Structures](contracts-struct.html#%28part._contracts-lazy-contracts%29) | |       [7.6 Abstract Contracts using #:exists and #:∃](contracts-exists.html) | |       [7.7 Additional Examples](contracts-examples.html) | |         [7.7.1 A Customer-Manager Component](contracts-examples.html#%28part._.A_.Customer-.Manager_.Component%29) | |         [7.7.2 A Parameteric (Simple) Stack](contracts-examples.html#%28part._.A_.Parameteric__.Simple__.Stack%29) | |         [7.7.3 A Dictionary](contracts-examples.html#%28part._.A_.Dictionary%29) | |         [7.7.4 A Queue](contracts-examples.html#%28part._.A_.Queue%29) | |       [7.8 Building New Contracts](Building_New_Contracts.html) | |         [7.8.1 Contract Struct Properties](Building_New_Contracts.html#%28part._.Contract_.Struct_.Properties%29) | |         [7.8.2 With all the Bells and Whistles](Building_New_Contracts.html#%28part._.With_all_the_.Bells_and_.Whistles%29) | |       [7.9 Gotchas](contracts-gotchas.html) | |         [7.9.1 Contracts and eq?](contracts-gotchas.html#%28part._.Contracts_and_eq_%29) | |         [7.9.2 Contract boundaries and define/contract](contracts-gotchas.html#%28part._contracts-gotcha-nested%29) | |         [7.9.3 Exists Contracts and Predicates](contracts-gotchas.html#%28part._contracts-exists-gotcha%29) | |         [7.9.4 Defining Recursive Contracts](contracts-gotchas.html#%28part._.Defining_.Recursive_.Contracts%29) | |         [7.9.5 Mixing set! and contract-out](contracts-gotchas.html#%28part._.Mixing_set__and_contract-out%29) | | | |     [8 Input and Output](i_o.html) | |       [8.1 Varieties of Ports](ports.html) | |       [8.2 Default Ports](default-ports.html) | |       [8.3 Reading and Writing Racket Data](read-write.html) | |       [8.4 Datatypes and Serialization](serialization.html) | |       [8.5 Bytes, Characters, and Encodings](encodings.html) | |       [8.6 I/O Patterns](io-patterns.html) | | | |     [9 Regular Expressions](regexp.html) | |       [9.1 Writing Regexp Patterns](regexp-intro.html) | |       [9.2 Matching Regexp Patterns](regexp-match.html) | |       [9.3 Basic Assertions](regexp-assert.html) | |       [9.4 Characters and Character Classes](regexp-chars.html) | |         [9.4.1 Some Frequently Used Character Classes](regexp-chars.html#%28part._.Some_.Frequently_.Used_.Character_.Classes%29) | |         [9.4.2 POSIX character classes](regexp-chars.html#%28part._.P.O.S.I.X_character_classes%29) | |       [9.5 Quantifiers](regexp-quant.html) | |       [9.6 Clusters](regexp-clusters.html) | |         [9.6.1 Backreferences](regexp-clusters.html#%28part._.Backreferences%29) | |         [9.6.2 Non-capturing Clusters](regexp-clusters.html#%28part._.Non-capturing_.Clusters%29) | |         [9.6.3 Cloisters](regexp-clusters.html#%28part._regexp-cloister%29) | |       [9.7 Alternation](regexp-alternation.html) | |       [9.8 Backtracking](Backtracking.html) | |       [9.9 Looking Ahead and Behind](Looking_Ahead_and_Behind.html) | |         [9.9.1 Lookahead](Looking_Ahead_and_Behind.html#%28part._.Lookahead%29) | |         [9.9.2 Lookbehind](Looking_Ahead_and_Behind.html#%28part._.Lookbehind%29) | |       [9.10 An Extended Example](An_Extended_Example.html) | | | |     [10 Exceptions and Control](control.html) | |       [10.1 Exceptions](exns.html) | |       [10.2 Prompts and Aborts](prompt.html) | |       [10.3 Continuations](conts.html) | | | |     [11 Iterations and Comprehensions](for.html) | |       [11.1 Sequence Constructors](for.html#%28part._sequences%29) | |       [11.2 for and for*](for.html#%28part._for_and_for_%29) | |       [11.3 for/list and for*/list](for.html#%28part._for_list_and_for__list%29) | |       [11.4 for/vector and for*/vector](for.html#%28part._for_vector_and_for__vector%29) | |       [11.5 for/and and for/or](for.html#%28part._for_and_and_for_or%29) | |       [11.6 for/first and for/last](for.html#%28part._for_first_and_for_last%29) | |       [11.7 for/fold and for*/fold](for.html#%28part._for%2Ffold%29) | |       [11.8 Multiple-Valued Sequences](for.html#%28part._.Multiple-.Valued_.Sequences%29) | |       [11.9 Breaking an Iteration](for.html#%28part._.Breaking_an_.Iteration%29) | |       [11.10 Iteration Performance](for.html#%28part._for-performance%29) | | | |     [12 Pattern Matching](match.html) | | | |     [13 Classes and Objects](classes.html) | |       [13.1 Methods](classes.html#%28part._methods%29) | |       [13.2 Initialization Arguments](classes.html#%28part._initargs%29) | |       [13.3 Internal and External Names](classes.html#%28part._intnames%29) | |       [13.4 Interfaces](classes.html#%28part._.Interfaces%29) | |       [13.5 Final, Augment, and Inner](classes.html#%28part._inner%29) | |       [13.6 Controlling the Scope of External Names](classes.html#%28part._extnames%29) | |       [13.7 Mixins](classes.html#%28part._.Mixins%29) | |         [13.7.1 Mixins and Interfaces](classes.html#%28part._.Mixins_and_.Interfaces%29) | |         [13.7.2 The mixin Form](classes.html#%28part._.The_mixin_.Form%29) | |         [13.7.3 Parameterized Mixins](classes.html#%28part._parammixins%29) | |       [13.8 Traits](classes.html#%28part._.Traits%29) | |         [13.8.1 Traits as Sets of Mixins](classes.html#%28part._.Traits_as_.Sets_of_.Mixins%29) | |         [13.8.2 Inherit and Super in Traits](classes.html#%28part._.Inherit_and_.Super_in_.Traits%29) | |         [13.8.3 The trait Form](classes.html#%28part._.The_trait_.Form%29) | |       [13.9 Class Contracts](classes.html#%28part._.Class_.Contracts%29) | |         [13.9.1 External Class Contracts](classes.html#%28part._.External_.Class_.Contracts%29) | |         [13.9.2 Internal Class Contracts](classes.html#%28part._.Internal_.Class_.Contracts%29) | | | |     [14 Units (Components)](units.html) | |       [14.1 Signatures and Units](Signatures_and_Units.html) | |       [14.2 Invoking Units](Invoking_Units.html) | |       [14.3 Linking Units](Linking_Units.html) | |       [14.4 First-Class Units](firstclassunits.html) | |       [14.5 Whole-module Signatures and Units](Whole-module_Signatures_and_Units.html) | |       [14.6 Contracts for Units](Contracts_for_Units.html) | |         [14.6.1 Adding Contracts to Signatures](Contracts_for_Units.html#%28part._.Adding_.Contracts_to_.Signatures%29) | |         [14.6.2 Adding Contracts to Units](Contracts_for_Units.html#%28part._.Adding_.Contracts_to_.Units%29) | |       [14.7 unit versus module](unit_versus_module.html) | | | |     [15 Reflection and Dynamic Evaluation](reflection.html) | |       [15.1 eval](eval.html) | |         [15.1.1 Local Scopes](eval.html#%28part._.Local_.Scopes%29) | |         [15.1.2 Namespaces](eval.html#%28part._namespaces%29) | |         [15.1.3 Namespaces and Modules](eval.html#%28part._.Namespaces_and_.Modules%29) | |       [15.2 Manipulating Namespaces](mk-namespace.html) | |         [15.2.1 Creating and Installing Namespaces](mk-namespace.html#%28part._.Creating_and_.Installing_.Namespaces%29) | |         [15.2.2 Sharing Data and Code Across Namespaces](mk-namespace.html#%28part._.Sharing_.Data_and_.Code_.Across_.Namespaces%29) | |       [15.3 Scripting Evaluation and Using load](load.html) | |       [15.4 Code Inspectors for Trusted and Untrusted Code](code-inspectors_protect.html) | | | |     [16 Macros](macros.html) | |       [16.1 Pattern-Based Macros](pattern-macros.html) | |         [16.1.1 define-syntax-rule](pattern-macros.html#%28part._define-syntax-rule%29) | |         [16.1.2 Lexical Scope](pattern-macros.html#%28part._.Lexical_.Scope%29) | |         [16.1.3 define-syntax and syntax-rules](pattern-macros.html#%28part._define-syntax_and_syntax-rules%29) | |         [16.1.4 Matching Sequences](pattern-macros.html#%28part._.Matching_.Sequences%29) | |         [16.1.5 Identifier Macros](pattern-macros.html#%28part._.Identifier_.Macros%29) | |         [16.1.6 set! Transformers](pattern-macros.html#%28part._set__.Transformers%29) | |         [16.1.7 Macro-Generating Macros](pattern-macros.html#%28part._.Macro-.Generating_.Macros%29) | |         [16.1.8 Extended Example: Call-by-Reference Functions](pattern-macros.html#%28part._pattern-macro-example%29) | |       [16.2 General Macro Transformers](proc-macros.html) | |         [16.2.1 Syntax Objects](stx-obj.html) | |         [16.2.2 Macro Transformer Procedures](macro-transformers.html) | |         [16.2.3 Mixing Patterns and Expressions: syntax-case](syntax-case.html) | |         [16.2.4 with-syntax and generate-temporaries](with-syntax.html) | |         [16.2.5 Compile and Run-Time Phases](stx-phases.html) | |         [16.2.6 General Phase Levels](phases.html) | |           [16.2.6.1 Phases and Bindings](phases.html#%28part._.Phases_and_.Bindings%29) | |           [16.2.6.2 Phases and Modules](phases.html#%28part._.Phases_and_.Modules%29) | |         [16.2.7 Tainted Syntax](stx-certs.html) | |       [16.3 Module Instantiations and Visits](macro-module.html) | |         [16.3.1 Declaration versus Instantiation](macro-module.html#%28part._.Declaration_versus_.Instantiation%29) | |         [16.3.2 Compile-Time Instantiation](macro-module.html#%28part._compile-time-instantiation%29) | |         [16.3.3 Visiting Modules](macro-module.html#%28part._.Visiting_.Modules%29) | |         [16.3.4 Lazy Visits via Available Modules](macro-module.html#%28part._stx-available-module%29) | | | |     [17 Creating Languages](languages.html) | |       [17.1 Module Languages](module-languages.html) | |         [17.1.1 Implicit Form Bindings](module-languages.html#%28part._implicit-forms%29) | |         [17.1.2 Using #lang s-exp](module-languages.html#%28part._s-exp%29) | |       [17.2 Reader Extensions](hash-reader.html) | |         [17.2.1 Source Locations](hash-reader.html#%28part._.Source_.Locations%29) | |         [17.2.2 Readtables](hash-reader.html#%28part._readtable%29) | |       [17.3 Defining new #lang Languages](hash-languages.html) | |         [17.3.1 Designating a #lang Language](hash-lang_syntax.html) | |         [17.3.2 Using #lang reader](hash-lang_reader.html) | |         [17.3.3 Using #lang s-exp syntax/module-reader](syntax_module-reader.html) | |         [17.3.4 Installing a Language](language-collection.html) | |         [17.3.5 Source-Handling Configuration](language-get-info.html) | |         [17.3.6 Module-Handling Configuration](module-runtime-config.html) | | | |     [18 Concurrency and Synchronization](concurrency.html) | |       [18.1 Threads](concurrency.html#%28part._.Threads%29) | |       [18.2 Thread Mailboxes](concurrency.html#%28part._.Thread_.Mailboxes%29) | |       [18.3 Semaphores](concurrency.html#%28part._.Semaphores%29) | |       [18.4 Channels](concurrency.html#%28part._.Channels%29) | |       [18.5 Buffered Asynchronous Channels](concurrency.html#%28part._.Buffered_.Asynchronous_.Channels%29) | |       [18.6 Synchronizable Events and sync](concurrency.html#%28part._.Synchronizable_.Events_and_sync%29) | |       [18.7 Building Your Own Synchronization Patterns](concurrency.html#%28part._.Building_.Your_.Own_.Synchronization_.Patterns%29) | | | |     [19 Performance](performance.html) | |       [19.1 Performance in DrRacket](performance.html#%28part._.Dr.Racket-perf%29) | |       [19.2 Racket Virtual Machine Implementations](performance.html#%28part._virtual-machines%29) | |       [19.3 Bytecode, Machine Code, and Just-in-Time (JIT) Compilers](performance.html#%28part._.J.I.T%29) | |       [19.4 Modules and Performance](performance.html#%28part._modules-performance%29) | |       [19.5 Function-Call Optimizations](performance.html#%28part._func-call-performance%29) | |       [19.6 Mutation and Performance](performance.html#%28part._.Mutation_and_.Performance%29) | |       [19.7 letrec Performance](performance.html#%28part._letrec-performance%29) | |       [19.8 Fixnum and Flonum Optimizations](performance.html#%28part._fixnums%2Bflonums%29) | |       [19.9 Unchecked, Unsafe Operations](performance.html#%28part._unchecked-unsafe%29) | |       [19.10 Foreign Pointers](performance.html#%28part._ffi-pointer-access%29) | |       [19.11 Regular Expression Performance](performance.html#%28part._regexp-perf%29) | |       [19.12 Memory Management](performance.html#%28part._gc-perf%29) | |       [19.13 Reachability and Garbage Collection](performance.html#%28part._.Reachability._and._.Garbage._.Collection%29) | |       [19.14 Weak Boxes and Testing](performance.html#%28part._.Weak_.Boxes_and_.Testing%29) | |       [19.15 Reducing Garbage Collection Pauses](performance.html#%28part._.Reducing_.Garbage_.Collection_.Pauses%29) | | | |     [20 Parallelism](parallelism.html) | |       [20.1 Parallel Threads](parallelism.html#%28part._parallel-threads%29) | |       [20.2 Parallelism with Futures](parallelism.html#%28part._effective-futures%29) | |       [20.3 Parallelism with Places](parallelism.html#%28part._effective-places%29) | |       [20.4 Distributed Places](parallelism.html#%28part._distributed-places%29) | | | |     [21 Running and Creating Executables](running.html) | |       [21.1 Running racket and gracket](racket.html) | |         [21.1.1 Interactive Mode](racket.html#%28part._start-interactive-mode%29) | |         [21.1.2 Module Mode](racket.html#%28part._start-module-mode%29) | |         [21.1.3 Load Mode](racket.html#%28part._start-load-mode%29) | |       [21.2 Scripts](scripts.html) | |         [21.2.1 Unix Scripts](scripts.html#%28part._.Unix_.Scripts%29) | |         [21.2.2 Windows Batch Files](scripts.html#%28part._.Windows_.Batch_.Files%29) | |       [21.3 Creating Stand-Alone Executables](exe.html) | | | |     [22 More Libraries](More_Libraries.html) | |       [22.1 Graphics and GUIs](More_Libraries.html#%28part._graphics%29) | |       [22.2 The Web Server](More_Libraries.html#%28part._.The_.Web_.Server%29) | |       [22.3 Using Foreign Libraries](More_Libraries.html#%28part._.Using_.Foreign_.Libraries%29) | |       [22.4 And More](More_Libraries.html#%28part._.And_.More%29) | | | |     [23 Dialects of Racket and Scheme](dialects.html) | |       [23.1 More Rackets](more-hash-lang.html) | |       [23.2 Standards](standards.html) | |         [23.2.1 R5RS](standards.html#%28part._r5rs%29) | |         [23.2.2 R6RS](standards.html#%28part._.R6.R.S%29) | |       [23.3 Teaching](teaching-langs.html) | | | |     [24 Command-Line Tools and Your Editor of Choice](other-editors.html) | |       [24.1 Command-Line Tools](cmdline-tools.html) | |         [24.1.1 Compilation and Configuration: raco](cmdline-tools.html#%28part._compile%29) | |         [24.1.2 Interactive evaluation](cmdline-tools.html#%28part._.Interactive_evaluation%29) | |         [24.1.3 Shell completion](cmdline-tools.html#%28part._.Shell_completion%29) | |       [24.2 Emacs](Emacs.html) | |         [24.2.1 Major Modes](Emacs.html#%28part._.Major_.Modes%29) | |         [24.2.2 Minor Modes](Emacs.html#%28part._.Minor_.Modes%29) | |         [24.2.3 Packages specific to Evil Mode](Emacs.html#%28part._.Packages_specific_to_.Evil_.Mode%29) | |       [24.3 Vim](Vim.html) | |         [24.3.1 Enhanced Racket Support](Vim.html#%28part._vim-racket%29) | |         [24.3.2 Indentation](Vim.html#%28part._.Indentation%29) | |         [24.3.3 Highlighting](Vim.html#%28part._.Highlighting%29) | |         [24.3.4 Structured Editing](Vim.html#%28part._.Structured_.Editing%29) | |         [24.3.5 REPLs](Vim.html#%28part._.R.E.P.Ls%29) | |         [24.3.6 Scribble](Vim.html#%28part._.Scribble%29) | |         [24.3.7 Miscellaneous](Vim.html#%28part._.Miscellaneous%29) | |         [24.3.8 Older Versions of Vim](Vim.html#%28part._vim-versions%29) | |       [24.4 Sublime Text](Sublime_Text.html) | |       [24.5 Visual Studio Code](Visual_Studio_Code.html) | | | |     [Bibliography](doc-bibliography.html) | | | |     [Index](doc-index.html) |
# The Racket Guide ------------------------------------------------------------------------
# 1 Welcome to Racket
## 1 Welcome to Racket Depending on how you look at it, Racket is - a programming language—a dialect of Lisp and a descendant of Scheme; > > > See [Dialects of Racket and Scheme](dialects.html) for more information on other dialects of Lisp and how they relate to Racket. - a family of programming languages—variants of Racket, and more; or - a set of tools—for using a family of programming languages. Where there is no room for confusion, we use simply Racket. Racket’s main tools are - racket, the core compiler, interpreter, and run-time system; - DrRacket, the programming environment; and - raco, a command-line tool for executing Racket commands that install packages, build libraries, and more. Most 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. If 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 > [#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)
# 1 Welcome to Racket in 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). > > > [More Rackets](more-hash-lang.html) describes some of the other possibilities. If 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.
### 1.1 Interacting with Racket DrRacket’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. A number by itself is an expression, and the answer is just the number: > ```racket > > 5 > 5 > ``` A string is also an expression that evaluates to itself. A string is written with double quotes at the start and end of the string: > ```racket > > "Hello, world!" > "Hello, world!" > ``` Racket 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: > ```racket > > ( substring "the boy out of the country" 4 7 ) > "boy" > ```
### 1.2 Definitions and Interactions You 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: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define ( extract str ) > ( substring str 4 7 ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>&gt; ( extract &quot;the boy out of the country&quot; ) > &quot;boy&quot; > &gt; ( extract &quot;the country out of the boy&quot; ) > &quot;cou&quot;</code></pre></td></tr></tbody></table> Although 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:
### 1.2 Definitions and Interactions > ```racket > #lang racket > ( define ( extract str ) > ( substring str 4 7 ) ) > ``` If 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). When 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: > > > 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). > ```racket > > ( enter! "extract.rkt" ) > > ( extract "the gal out of the city" ) > "gal" > ``` The [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.
### 1.3 Creating Executables If your file (or [definitions area](#%28tech._definitions._area%29) in DrRacket) contains > ```racket > #lang racket > ( define ( extract str ) > ( substring str 4 7 ) ) > ( extract "the cat out of the bag" ) > ``` then 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   racket ‹src-filename› To package the program as an executable, you have a few options: - In DrRacket, you can select the Racket\|Create Executable... menu item. - 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. - With Unix or Mac OS, you can turn the program file into an executable script by inserting the line > > > See [Scripts](scripts.html) for more information on script files. | | |--------------------------| |   #! /usr/bin/env racket | at the very beginning of the file. Also, change the file permissions to executable using chmod +x ‹filename› on the command line.
### 1.3 Creating Executables 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.
### 1.4 A Note to Readers with Lisp/Scheme Experience If you already know something about Scheme or Lisp, you might be tempted to put just > ```racket > ( define ( extract str ) > ( substring str 4 7 ) ) > ``` into "extract.rktl" and run racket with > ```racket > > ( load "extract.rktl" ) > > ( extract "the dog out" ) > "dog" > ``` That 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. Writing 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. ------------------------------------------------------------------------
# 2 Racket Essentials
## 2 Racket Essentials This 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). | | |----------------------------------------------------------------------------------------------------------------------------------------------------------------| |     [2.1 Simple Values](Simple_Values.html) | |     [2.2 Simple Definitions and Expressions](syntax-overview.html) | |       [2.2.1 Definitions](syntax-overview.html#%28part._.Definitions%29) | |       [2.2.2 An Aside on Indenting Code](syntax-overview.html#%28part._indentation%29) | |       [2.2.3 Identifiers](syntax-overview.html#%28part._.Identifiers%29) | |       [2.2.4 Function Calls (Procedure Applications)](syntax-overview.html#%28part._.Function_.Calls__.Procedure_.Applications_%29) | |       [2.2.5 Conditionals with if, and, or, and cond](syntax-overview.html#%28part._.Conditionals_with_if__and__or__and_cond%29) | |       [2.2.6 Function Calls, Again](syntax-overview.html#%28part._.Function_.Calls__.Again%29) | |       [2.2.7 Anonymous Functions with lambda](syntax-overview.html#%28part._.Anonymous_.Functions_with_lambda%29) | |       [2.2.8 Local Binding with define, let, and let*](syntax-overview.html#%28part._local-binding-intro%29) | |     [2.3 Lists, Iteration, and Recursion](Lists__Iteration__and_Recursion.html) | |       [2.3.1 Predefined List Loops](Lists__Iteration__and_Recursion.html#%28part._.Predefined_.List_.Loops%29) | |       [2.3.2 List Iteration from Scratch](Lists__Iteration__and_Recursion.html#%28part._.List_.Iteration_from_.Scratch%29) | |       [2.3.3 Tail Recursion](Lists__Iteration__and_Recursion.html#%28part._tail-recursion%29) | |       [2.3.4 Recursion versus Iteration](Lists__Iteration__and_Recursion.html#%28part._.Recursion_versus_.Iteration%29) | |     [2.4 Pairs, Lists, and Racket Syntax](Pairs__Lists__and_Racket_Syntax.html) | |       [2.4.1 Quoting Pairs and Symbols with quote](Pairs__Lists__and_Racket_Syntax.html#%28part._quoting-lists%29) | |       [2.4.2 Abbreviating quote with '](Pairs__Lists__and_Racket_Syntax.html#%28part._.Abbreviating_quote_with__%29) | |       [2.4.3 Lists and Racket Syntax](Pairs__Lists__and_Racket_Syntax.html#%28part._lists-and-syntax%29) |
# 2 Racket Essentials ------------------------------------------------------------------------
# 2.1 Simple Values
### 2.1 Simple Values Racket 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. Numbers are written in the usual way, including fractions and imaginary numbers: > > > <img src="finger.png" width="24" height="24" alt="+" />[Numbers](numbers.html) (later in this guide) explains more about numbers. > ```racket > 1 3.14 > 1/2 6.02e+23 > 1+2i 9999999999999999999999 > ``` Booleans are #t for true and #f for false. In conditionals, however, all non-#f values are treated as true. > > > <img src="finger.png" width="24" height="24" alt="+" />[Booleans](booleans.html) (later in this guide) explains more about booleans. Strings 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. > > > <img src="finger.png" width="24" height="24" alt="+" />[Strings (Unicode)](strings.html) (later in this guide) explains more about strings. > ```racket > "Hello, world!" > "Benjamin \"Bugsy\" Siegel" > "λx:(μα.α→α).xx" > ```
# 2.1 Simple Values When 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. Examples: > ```racket > > 1.0000 > 1.0 > > "Bugs \u0022Figaro\u0022 Bunny" > "Bugs \"Figaro\" Bunny" > ``` ------------------------------------------------------------------------
# 2.2 Simple Definitions and Expressions
### 2.2 Simple Definitions and Expressions A program module is written as > #lang ‹langname› ‹topform›\* where a ‹topform› is either a ‹definition› or an ‹expr›. The [REPL](intro.html#%28tech._repl%29) also evaluates ‹topform›s. In 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. > > > <img src="magnify.png" width="24" height="24" alt="+" />[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. Following 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.
#### 2.2.1 Definitions A definition of the form > > > <img src="finger.png" width="24" height="24" alt="+" />[Definitions: define](define.html) (later in this guide) explains more about definitions. > ( define ‹id› ‹expr› ) binds ‹id› to the result of ‹expr›, while > ( define ( ‹id› ‹id›\* ) ‹expr›+ ) binds 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›. Examples: > ```racket > ( define pie 3 ) ; defines pie to be 3 > ( define ( piece str ) ; defines piece as a function ( substring str 0 pie ) ) ; of one argument > > pie > 3 > > ( piece "key lime" ) > "key" > ``` Under 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. Examples: > ```racket > > piece > #<procedure:piece> > > substring > #<procedure:substring> > ``` A 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. Examples: > ```racket > ( define ( bake flavor ) ( printf "preheating oven...\n" ) ( string-append flavor " pie" ) ) > > ( bake "apple" ) > preheating oven... > "apple pie" > ```
# 2.2 Simple Definitions and Expressions Racket 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: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define ( nobake flavor ) > string-append flavor &quot;jello&quot; )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>&gt; ( nobake &quot;green&quot; ) > &quot;jello&quot;</code></pre></td></tr></tbody></table> Within 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".
#### 2.2.2 An Aside on Indenting Code Line 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. DrRacket 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. Re-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:
# 2.2 Simple Definitions and Expressions > ```racket > ( define ( halfbake flavor > ( string-append flavor " creme brulee" ) ) ) > ``` In 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.
#### 2.2.3 Identifiers Racket’s syntax for identifiers is especially liberal. Excluding the special characters > > > <img src="finger.png" width="24" height="24" alt="+" />[Identifiers and Binding](binding.html) (later in this guide) explains more about identifiers.    ( ) \[ \] { } " , ' \` ; # \| \\ and 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: > ```racket > + > integer? > pass/fail > Hfuhruhurr&Uumellmahaye > john-jacob-jingleheimer-schmidt > a-b-c+1-2-3 > ```
#### 2.2.4 Function Calls (Procedure Applications) We have already seen many function calls, which are called procedure applications in more traditional terminology. The syntax of a function call is > > > <img src="finger.png" width="24" height="24" alt="+" />[Function Calls](application.html) (later in this guide) explains more about function calls. > ( ‹id› ‹expr›\* ) where the number of ‹expr›s determines the number of arguments supplied to the function named by ‹id›. The [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. In 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.
# 2.2 Simple Definitions and Expressions > ```racket > > ( string-append "rope" "twine" "yarn" ) ; append strings > "ropetwineyarn" > > ( substring "corduroys" 0 4 ) ; extract a substring > "cord" > > ( string-prefix? "shoelace" "shoe" ) ; recognize string prefix/suffix > #t > > ( string-suffix? "shoelace" "shoe" ) > #f > > ( string? "Ceci n'est pas une string." ) ; recognize strings > #t > > ( string? 1 ) > #f > > ( sqrt 16 ) ; find a square root > 4 > > ( sqrt -1 6 ) > 0+4i > > ( + 1 2 ) ; add numbers > 3 > > ( - 2 1 ) ; subtract numbers > 1 > > ( < 2 1 ) ; compare numbers> #f > > ( >= 2 1 ) > #t > > ( number? "c'est une number" ) ; recognize numbers > #f > > ( number? 1 ) > #t > > ( equal? 6 "half dozen" ) ; compare anything > #f > > ( equal? 6 6 ) > #t > > ( equal? "half dozen" "half dozen" ) > #t > ```
#### 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) The 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: > ( if ‹expr› ‹expr› ‹expr› ) > > > <img src="finger.png" width="24" height="24" alt="+" />[Conditionals](conditionals.html) (later in this guide) explains more about conditionals.
# 2.2 Simple Definitions and Expressions The 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. Example: > ```racket > > ( if ( > 2 3 ) "2 is bigger than 3" "2 is smaller than 3" ) > "2 is smaller than 3" > ``` > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define ( reply s ) > ( if ( string-prefix? s &quot;hello &quot; ) > &quot;hi!&quot; > &quot;huh?&quot; ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>&gt; ( reply &quot;hello racket&quot; ) > &quot;hi!&quot; > &gt; ( reply &quot;λx:(μα.α→α).xx&quot; ) > &quot;huh?&quot;</code></pre></td></tr></tbody></table>
# 2.2 Simple Definitions and Expressions Complex 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: > ```racket > ( define ( reply-non-string s ) > ( if ( string? s ) > ( if ( string-prefix? s "hello " ) > "hi!" > "huh?" ) > "huh?" ) ) > ``` Instead of duplicating the "huh?" case, this function is better written as > ```racket > ( define ( reply-non-string s ) > ( if ( if ( string? s ) > ( string-prefix? s "hello " ) > #f ) > "hi!" > "huh?" ) ) > ```
# 2.2 Simple Definitions and Expressions but 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: > > > <img src="finger.png" width="24" height="24" alt="+" />[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). > ```racket > ( and ‹ expr › * ) > ( or ‹ expr › * ) > ```
# 2.2 Simple Definitions and Expressions 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) 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. Examples: > ```racket > ( define ( reply-non-string s ) ( if ( and ( string? s ) ( string-prefix? s "hello " ) ) "hi!" "huh?" ) ) > > ( reply-non-string "hello racket" ) > "hi!" > > ( reply-non-string 17 ) > "huh?" > ``` Note 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. Examples:
# 2.2 Simple Definitions and Expressions > ```racket > ( define ( reply-only-enthusiastic s ) ( if ( and ( string? s ) ( string-prefix? s "hello " ) ( string-suffix? s "!" ) ) "hi!" "huh?" ) ) > > ( reply-only-enthusiastic "hello racket!" ) > "hi!" > > ( reply-only-enthusiastic "hello racket" ) > "huh?" > ``` Another 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: > ```racket > ( define ( reply-more s ) > ( if ( string-prefix? s "hello " ) > "hi!" > ( if ( string-prefix? s "goodbye " ) > "bye!" > ( if ( string-suffix? s "?" ) > "I don't know" > "huh?" ) ) ) ) > ``` The 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: > > > <img src="finger.png" width="24" height="24" alt="+" />[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). > ( cond {\[ ‹expr› ‹expr›\* \]}\* )
# 2.2 Simple Definitions and Expressions 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) 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. Using [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: > ``` (define (reply-more s)
# 2.2 Simple Definitions and Expressions > ( cond > [ ( string-prefix? s "hello " ) > "hi!" ] > [ ( string-prefix? s "goodbye " ) > "bye!" ] > [ ( string-suffix? s "?" ) > "I don't know" ] > [ else "huh?" ] ) ) > ( reply-more "hello racket" ) > "hi!" > > ( reply-more "goodbye cruel world" ) > "bye!" > > ( reply-more "what is your favorite color?" ) > "I don't know" > > ( reply-more "mine is lime green" ) > "huh?" ``` The 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. #### 2.2.6 Function Calls, Again In 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›: > > > <img src="finger.png" width="24" height="24" alt="+" />Function Calls (later in this guide) explains more about function calls. > ( ‹expr› ‹expr›\* ) The 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: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define ( double v ) > ( ( if ( string? v ) string-append + ) v v ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>> ( double "mnah" ) > "mnahmnah" > > ( double 5 ) > 10</code></pre></td></tr></tbody></table> Syntactically, 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. > ```racket > > ( 1 2 3 4 ) > application: not a procedure; > expected a procedure that can be applied to arguments > given: 1 > ``` When 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. #### 2.2.7 Anonymous Functions with lambda Programming in Racket would be tedious if you had to name all of your numbers. Instead of writing (+ 1 2), you’d have to write > > > <img src="finger.png" width="24" height="24" alt="+" />Functions: lambda (later in this guide) explains more about lambda. > ```racket > > ( define a 1 ) > > ( define b 2 ) > > ( + a b ) > 3 > ``` It 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: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define ( twice f v ) > ( f ( f v ) ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>> ( twice sqrt 16 ) > 2</code></pre></td></tr></tbody></table> If you want to call a function that is not yet defined, you could define it, and then pass it to twice: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define ( louder s ) > ( string-append s "!" ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>> ( twice louder "hello" ) > "hello!!"</code></pre></td></tr></tbody></table> But 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: > ( lambda ( ‹id›\* ) ‹expr›+ ) Evaluating a lambda form by itself produces a function: > ```racket > > ( lambda ( s ) ( string-append s "!" ) ) > #<procedure> > ``` Using lambda, the above call to twice can be re-written as > ```racket > > ( twice ( lambda ( s ) ( string-append s "!" ) ) "hello" ) > "hello!!" > > ( twice ( lambda ( s ) ( string-append s "?!" ) ) "hello" ) > "hello?!?!" > ``` Another use of lambda is as a result for a function that generates functions: > ``` (define (make-add-suffix s2) > ( lambda ( s ) ( string-append s s2 ) ) )   > ( twice ( make-add-suffix "!" ) "hello" ) > "hello!!" > > ( twice ( make-add-suffix "?!" ) "hello" ) > "hello?!?!" > > ( twice ( make-add-suffix "..." ) "hello" ) > "hello......"``` Racket 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: > ```racket > > ( define louder ( make-add-suffix "!" ) ) > > ( define less-sure ( make-add-suffix "?" ) ) > > ( twice less-sure "really" ) > "really??" > > ( twice louder "really" ) > "really!!" > ``` We 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: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define ( louder s ) > ( string-append s &quot;!&quot; ) ) > ( define louder > ( lambda ( s ) > ( string-append s &quot;!&quot; ) ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>&gt; louder > #&lt;procedure:louder&gt;</code></pre></td></tr></tbody></table> Note 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. #### 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) It’s time to retract another simplification in our grammar of Racket. In the body of a function, definitions can appear before the body expressions: > > > <img src="finger.png" width="24" height="24" alt="+" />[Internal Definitions](define.html#%28part._intdefs%29) (later in this guide) explains more about local (internal) definitions. > ```racket > ( define ( ‹ id › ‹ id › * ) ‹ definition › * ‹ expr › + ) > ( lambda ( ‹ id › * ) ‹ definition › * ‹ expr › + ) > ``` Definitions at the start of a function body are local to the function body. Examples: > ```racket > ( 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?" ] ) ) > > ( converse "hello world" ) > "hi!" > > ( converse "hellonearth" ) > "huh?" > > ( converse "goodbye friends" ) > "bye!" > > ( converse "urp" ) > "huh?" > > starts? ; outside of converse , so... > starts?: undefined; > cannot reference an identifier before its definition > in module: top-level > ``` Another 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. > > > <img src="finger.png" width="24" height="24" alt="+" />[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). > ( let ( {\[ ‹id› ‹expr› \]}\* ) ‹expr›+ ) Each 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. > ```racket > > ( let ( [ x ( random 4 ) ] [ o ( random 4 ) ] ) ( cond [ ( > x o ) "X wins" ] [ ( > o x ) "O wins" ] [ else "cat's game" ] ) ) > "cat's game" > ``` The 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: > ```racket > > ( 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" ] ) ) > "O wins by 2" > ``` ------------------------------------------------------------------------ # 2.3 Lists, Iteration, and Recursion ### 2.3 Lists, Iteration, and Recursion Racket 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. The [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: > ```racket > > ( list "red" "green" "blue" ) > '("red" "green" "blue") > > ( list 1 2 3 4 5 ) > '(1 2 3 4 5) > ``` > > > 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. As 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. Many predefined functions operate on lists. Here are a few examples: > ```racket > > ( length ( list "hop" "skip" "jump" ) ) ; count the elements > 3 > > ( list-ref ( list "hop" "skip" "jump" ) 0 ) ; extract by position > "hop" > > ( list-ref ( list "hop" "skip" "jump" ) 1 ) > "skip" > > ( append ( list "hop" "skip" ) ( list "jump" ) ) ; combine lists > '("hop" "skip" "jump") > > ( reverse ( list "hop" "skip" "jump" ) ) ; reverse order > '("jump" "skip" "hop") > > ( member "fall" ( list "hop" "skip" "jump" ) ) ; check for an element > #f > ``` #### 2.3.1 Predefined List Loops In 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. Different 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: > ```racket > > ( map sqrt ( list 1 4 9 16 ) ) > '(1 2 3 4) > > ( map ( lambda ( i ) ( string-append i "!" ) ) ( list "peanuts" "popcorn" "crackerjack" ) ) > '("peanuts!" "popcorn!" "crackerjack!") > ``` The [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: > ```racket > > ( andmap string? ( list "a" "b" "c" ) ) > #t > > ( andmap string? ( list "a" "b" 6 ) ) > #f > > ( ormap number? ( list "a" "b" 6 ) ) > #t > ``` 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), [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: > ```racket > > ( map ( lambda ( s n ) ( substring s 0 n ) ) ( list "peanuts" "popcorn" "crackerjack" ) ( list 6 3 7 ) ) > '("peanut" "pop" "cracker") > ``` The [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: > ```racket > > ( filter string? ( list "a" "b" 6 ) ) > '("a" "b") > > ( filter positive? ( list 1 -2 6 7 0 ) ) > '(1 6 7) > ``` The [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: > ```racket > > ( foldl ( lambda ( elem v ) ( + v ( * elem elem ) ) ) 0 ' ( 1 2 3 ) ) > 14 > ``` Despite 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. Racket 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). #### 2.3.2 List Iteration from Scratch Although [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. Since a Racket list is a linked list, the two core operations on a non-empty list are - [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 - [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. Examples: > ```racket > > ( first ( list 1 2 3 ) ) > 1 > > ( rest ( list 1 2 3 ) ) > '(2 3) > ``` To 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: > ```racket > > empty > '() > > ( cons "head" empty ) > '("head") > > ( cons "dead" ( cons "head" empty ) ) > '("dead" "head") > ``` To 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: > ```racket > > ( empty? empty ) > #t > > ( empty? ( cons "head" empty ) ) > #f > > ( cons? empty ) > #f > > ( cons? ( cons "head" empty ) ) > #t > ``` With 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. Examples: > ```racket > ( define ( my-length lst ) ( cond [ ( empty? lst ) 0 ] [ else ( + 1 ( my-length ( rest lst ) ) ) ] ) ) > > ( my-length empty ) > 0 > > ( my-length ( list "a" "b" "c" ) ) > 3 > ``` > ``` (define (my-map f lst) > ( cond > [ ( empty? lst ) empty ] > [ else ( cons ( f ( first lst ) ) > ( my-map f ( rest lst ) ) ) ] ) )   > ( my-map string-upcase ( list "ready" "set" "go" ) ) > '("READY" "SET" "GO") ```
# 2.2 Simple Definitions and Expressions If 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.
#### 2.3.3 Tail Recursion Both 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: > ```racket > ( my-length ( list "a" "b" "c" ) ) > = ( + 1 ( my-length ( list "b" "c" ) ) ) > = ( + 1 ( + 1 ( my-length ( list "c" ) ) ) ) > = ( + 1 ( + 1 ( + 1 ( my-length ( list ) ) ) ) ) > = ( + 1 ( + 1 ( + 1 0 ) ) ) > = ( + 1 ( + 1 1 ) ) > = ( + 1 2 ) > = 3 > ``` For a list with n elements, evaluation will stack up n (+ 1 ...) additions, and then finally add them up when the list is exhausted. You 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: > ```racket > ( define ( my-length lst ) > ; local function iter : > ( define ( iter lst len ) > ( cond > [ ( empty? lst ) len ] > [ else ( iter ( rest lst ) ( + len 1 ) ) ] ) ) > ; body of my-length calls iter : > ( iter lst 0 ) ) > ``` Now evaluation looks like this: > ```racket > ( my-length ( list "a" "b" "c" ) ) > = ( iter ( list "a" "b" "c" ) 0 ) > = ( iter ( list "b" "c" ) 1 ) > = ( iter ( list "c" ) 2 ) > = ( iter ( list ) 3 ) > 3 > ```
# 2.2 Simple Definitions and Expressions The 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. This 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. In 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: > > > Attempting to reduce a constant factor like this is usually not worthwhile, as discussed below. > ```racket > ( define ( my-map f lst ) > ( define ( iter lst backward-result ) > ( cond > [ ( empty? lst ) ( reverse backward-result ) ] > [ else ( iter ( rest lst ) > ( cons ( f ( first lst ) ) > backward-result ) ) ] ) ) > ( iter lst empty ) ) > ``` It turns out that if you write > ```racket > ( define ( my-map f lst ) > ( for/list ( [ i lst ] ) > ( f i ) ) ) > ```
# 2.2 Simple Definitions and Expressions then 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.
#### 2.3.4 Recursion versus Iteration The 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. At 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. Suppose, 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: > ``` (define (remove-dups l) > ( cond > [ ( empty? l ) empty ] > [ ( empty? ( rest l ) ) l ] > [ else > ( let ( [ i ( first l ) ] ) > ( if ( equal? i ( first ( rest l ) ) ) > ( remove-dups ( rest l ) ) > ( cons i ( remove-dups ( rest l ) ) ) ) ) ] ) )
# 2.2 Simple Definitions and Expressions > ( remove-dups ( list "a" "b" "b" "b" "c" "c" ) ) > '("a" "b" "c")``` In 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: > ```racket > ( remove-dups ( list "a" "b" "b" "b" "b" "b" ) ) > = ( cons "a" ( remove-dups ( list "b" "b" "b" "b" "b" ) ) ) > = ( cons "a" ( remove-dups ( list "b" "b" "b" "b" ) ) ) > = ( cons "a" ( remove-dups ( list "b" "b" "b" ) ) ) > = ( cons "a" ( remove-dups ( list "b" "b" ) ) ) > = ( cons "a" ( remove-dups ( list "b" ) ) ) > = ( cons "a" ( list "b" ) ) > = ( list "a" "b" ) > ``` ------------------------------------------------------------------------
# 2.4 Pairs, Lists, and Racket Syntax
### 2.4 Pairs, Lists, and Racket Syntax 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 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: > ```racket > > ( cons 1 2 ) > '(1 . 2) > > ( cons "banana" "split" ) > '("banana" . "split") > ```
# 2.4 Pairs, Lists, and Racket Syntax Thus, 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.
# 2.4 Pairs, Lists, and Racket Syntax The 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.”) Examples:
# 2.4 Pairs, Lists, and Racket Syntax > ```racket > > ( car ( cons 1 2 ) ) > 1 > > ( cdr ( cons 1 2 ) ) > 2 > > ( pair? empty ) > #f > > ( pair? ( cons 1 2 ) ) > #t > > ( pair? ( list 1 2 3 ) ) > #t > ``` Racket’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. You 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): > ```racket > > ( cons ( list 2 3 ) 1 ) > '((2 3) . 1) > > ( cons 1 ( list 2 3 ) ) > '(1 2 3) > ```
# 2.4 Pairs, Lists, and Racket Syntax Non-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. The 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: > ```racket > > ( cons 0 ( cons 1 2 ) ) > '(0 1 . 2) > ``` In 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).
#### 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) A 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: > ```racket > > ( list ( list 1 ) ( list 2 3 ) ( list 4 ) ) > '((1) (2 3) (4)) > ``` For 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: > ```racket > > ( quote ( "red" "green" "blue" ) ) > '("red" "green" "blue") > > ( quote ( ( 1 ) ( 2 3 ) ( 4 ) ) ) > '((1) (2 3) (4)) > > ( quote ( ) ) > '() > ``` 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 works with the dot notation, too, whether the quoted form is normalized by the dot-parenthesis elimination rule or not: > ```racket > > ( quote ( 1 . 2 ) ) > '(1 . 2) > > ( quote ( 0 . ( 1 . 2 ) ) ) > '(0 1 . 2) > ``` Naturally, lists of any kind can be nested:
# 2.4 Pairs, Lists, and Racket Syntax > ```racket > > ( list ( list 1 2 3 ) 5 ( list "a" "b" "c" ) ) > '((1 2 3) 5 ("a" "b" "c")) > > ( quote ( ( 1 2 3 ) 5 ( "a" "b" "c" ) ) ) > '((1 2 3) 5 ("a" "b" "c")) > ``` If 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: > ```racket > > ( quote jane-doe ) > 'jane-doe > ``` A 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.
# 2.4 Pairs, Lists, and Racket Syntax Indeed, 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. Examples: > ```racket > > map > #<procedure:map> > > ( quote map ) > 'map > > ( symbol? ( quote map ) ) > #t > > ( symbol? map ) > #f > > ( procedure? map ) > #t > > ( string->symbol "map" ) > 'map > > ( symbol->string ( quote map ) ) > "map" > ```
# 2.4 Pairs, Lists, and Racket Syntax In 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: > ```racket > > ( car ( quote ( road map ) ) ) > 'road > > ( symbol? ( car ( quote ( road map ) ) ) ) > #t > ``` When a symbol is inside a list that is printed with ', the ' on the symbol is omitted, since ' is doing the job already: > ```racket > > ( quote ( road map ) ) > '(road map) > ``` 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 has no effect on a literal expression such as a number or string: > ```racket > > ( quote 42 ) > 42 > > ( quote "on the record" ) > "on the record" > ```
#### 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 ' As 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: > ```racket > > ' ( 1 2 3 ) > '(1 2 3) > > ' road > 'road > > ' ( ( 1 2 3 ) road ( "a" "b" "c" ) ) > '((1 2 3) road ("a" "b" "c")) > ``` In 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.
# 2.4 Pairs, Lists, and Racket Syntax A ' 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 ': > ```racket > > ( car ' ' road ) > 'quote > > ( car ' ( quote road ) ) > 'quote > ``` The ' 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: > ```racket > > ( quote ( quote road ) ) > ''road > > ' ( quote road ) > ''road > > ' ' road > ''road > ```
#### 2.4.3 Lists and Racket Syntax Now 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. The syntax of Racket is not defined directly in terms of character streams. Instead, the syntax is determined by two layers: - a reader layer, which turns a sequence of characters into lists, symbols, and other constants; and - an expander layer, which processes the lists, symbols, and other constants to parse them as an expression. The 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. One consequence of the read layer for expressions is that you can use the dot notation in expressions that are not quoted forms: > ```racket > > ( + 1 . ( 2 ) ) > 3 > ```
# 2.4 Pairs, Lists, and Racket Syntax This 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. Normally, . 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: > ```racket > > ( 1 . < . 2 )> #t > > ' ( 1 . < . 2 )> '(< 1 2)> ```
# 2.4 Pairs, Lists, and Racket Syntax This 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). ------------------------------------------------------------------------
# 3 Built-In Datatypes
## 3 Built-In Datatypes The [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. | | |-------------------------------------------------------------------------------| |     [3.1 Booleans](booleans.html) | |     [3.2 Numbers](numbers.html) | |     [3.3 Characters](characters.html) | |     [3.4 Strings (Unicode)](strings.html) | |     [3.5 Bytes and Byte Strings](bytestrings.html) | |     [3.6 Symbols](symbols.html) | |     [3.7 Keywords](keywords.html) | |     [3.8 Pairs and Lists](pairs.html) | |     [3.9 Vectors](vectors.html) | |     [3.10 Hash Tables](hash-tables.html) | |     [3.11 Boxes](boxes.html) | |     [3.12 Void and Undefined](void_undefined.html) | ------------------------------------------------------------------------
# 3.1 Booleans
### 3.1 Booleans Racket 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. The [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. Examples:
# 3.1 Booleans > ```racket > > ( = 2 ( + 1 1 ) ) > #t > > ( boolean? #t ) > #t > > ( boolean? #f ) > #t > > ( boolean? "no" ) > #f > > ( if "no" 1 0 ) > 1 > ``` ------------------------------------------------------------------------
# 3.2 Numbers
### 3.2 Numbers A Racket number is either exact or inexact: - An exact number is either - an arbitrarily large or small integer, such as 5, 99999999999999999, or -17; - a rational that is exactly the ratio of two arbitrarily small or large integers, such as 1/2, 99999999999999999/2, or -3/4; or - 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. - An inexact number is either - 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 - 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. Inexact 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.
# 3.2 Numbers > > > <img src="magnify.png" width="24" height="24" alt="+" />[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. Examples: > ```racket > > 0.5 > 0.5 > > #e0.5 > 1/2 > > #x03BB > 955 > ``` Computations 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. Examples: > ```racket > > ( / 1 2 ) > 1/2 > > ( / 1 2.0 ) > 0.5 > > ( if ( = 3.0 2.999 ) 1 2 ) > 2 > > ( inexact->exact 0.1 ) > 3602879701896397/36028797018963968 > ```
# 3.2 Numbers Inexact 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. Examples: > ```racket > > ( sin 0 ) ; rational... > 0 > > ( sin 1/2 ) ; not rational... > 0.479425538604203 > ``` In 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. > ``` (define (sigma f a b) > ( if ( = a b ) > 0 > ( + ( f a ) ( sigma f ( + a 1 ) b ) ) ) )
# 3.2 Numbers > ( time ( round ( sigma ( lambda ( x ) ( / 1 x ) ) 1 2000 ) ) ) > cpu time: 21 real time: 3 gc time: 0 > 8 > > ( time ( round ( sigma ( lambda ( x ) ( / 1.0 x ) ) 1 2000 ) ) ) > cpu time: 0 real time: 0 gc time: 0 > 8.0 ``` (Unicode) → (-> integer → char 65)``` The above example says that, within a something-else form, a thing is either an identifier or a keyword. ------------------------------------------------------------------------ # 4.2 Identifiers and Binding ### 4.2 Identifiers and Binding The 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 > [#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) means 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. > > > <img src="finger.png" width="24" height="24" alt="+" />[Symbols](symbols.html) introduces the syntax of identifiers. Forms 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. For example, in > ```racket > #lang racket > ( define f > ( lambda ( x ) > ( let ( [ y 5 ] ) > ( + x y ) ) ) ) > ( f 10 ) > ``` 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) 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). 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 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. Examples: > ```racket > ( define f ( lambda ( append ) ( define cons ( append "ugly" "confusing" ) ) ( let ( [ append ' this-was ] ) ( list append cons ) ) ) ) > > ( f list ) > '(this-was ("ugly" "confusing")) > ``` Similarly, 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. Even 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. Examples: > ```racket > > define > eval:1:0: define: bad syntax > in: define > > ( let ( [ define 5 ] ) define ) > 5 > ``` Again, shadowing standard bindings in this way is rarely a good idea, but the possibility is an inherent part of Racket’s flexibility. ------------------------------------------------------------------------ # 4.3 Function Calls ### 4.3 Function Calls (Procedure Applications) An expression of the form > > | | > > |--------------------------| > > | (proc-expr arg-expr ...) | is 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)). #### 4.3.1 Evaluation Order and Arity A 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. Examples: > ```racket > > ( cons 1 null ) > '(1) > > ( + 1 2 3 ) > 6 > > ( cons 1 2 3 ) > cons: arity mismatch; > the expected number of arguments does not match the given > number > expected: 2 > given: 3 > > ( 1 2 3 ) > application: not a procedure; > expected a procedure that can be applied to arguments > given: 1 > ``` Some 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. #### 4.3.2 Keyword Arguments Some 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: > > > <img src="finger.png" width="24" height="24" alt="+" />[Keywords](keywords.html) introduces keywords. > > ``` (proc-expr arg ...)   arg   =   arg-expr     |   arg-keyword arg-expr ```
# 3.2 Numbers For example, > (go "super.rkt" #:mode 'fast) calls 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. Since a keyword by itself is not an expression, then > (go "super.rkt" #:mode #:fast) is a syntax error. The #:mode keyword must be followed by an expression to produce an argument value, and #:fast is not an expression. The 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 > (go #:mode 'fast "super.rkt") > > > <img src="magnify.png" width="24" height="24" alt="+" />Procedure Applications and #%app in The Racket Reference provides more on procedure applications.
#### 4.3.3 The apply Function The 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: > ``` (define (avg lst) ; doesn’t work... > ( / ( + lst ) ( length lst ) ) ) > ( avg ' ( 1 2 3 ) ) > +: contract violation > expected: number? > given: '(1 2 3)``` > ``` (define (avg lst) ; doesn’t always work... > ( / ( + ( list-ref lst 0 ) ( list-ref lst 1 ) ( list-ref lst 2 ) ) > ( length lst ) ) ) > ( avg ' ( 1 2 3 ) ) > 2 > > ( avg ' ( 1 2 ) ) > list-ref: index too large for list > index: 2 > in: '(1 2)
# 3.2 Numbers ``` The 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: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define ( avg lst ) > ( / ( apply + lst ) ( length lst ) ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>> ( avg ' ( 1 2 3 ) ) > 2 > > ( avg ' ( 1 2 ) ) > 3/2 > > ( avg ' ( 1 2 3 4 ) ) > 5/2</code></pre></td></tr></tbody></table> As a convenience, the apply function accepts additional arguments between the function and the list. The additional arguments are effectively consed onto the argument list: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define ( anti-sum lst ) > ( apply - 0 lst ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>> ( anti-sum ' ( 1 2 3 ) ) > -6</code></pre></td></tr></tbody></table> The apply function accepts keyword arguments, too, and it passes them along to the called function: > ```racket > ( apply go #:mode ' fast ' ( "super.rkt" ) ) > ( apply go ' ( "super.rkt" ) #:mode ' fast ) > ``` Keywords 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<?), and the second list contains a corresponding argument for each keyword. The third list contains by-position function arguments, as for apply. > ```racket > ( keyword-apply go > ' ( #:mode ) > ' ( fast ) > ' ( "super.rkt" ) ) > ``` ------------------------------------------------------------------------ # 4.4 Functions: lambda ### 4.4 Functions (Procedures): lambda A lambda expression creates a function. In the simplest case, a lambda expression has the form > > ``` (lambda (arg-id ...) > > body ...+ )``` 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 with n arg-ids accepts n arguments: > ```racket > > ( ( lambda ( x ) x ) 1 ) > 1 > > ( ( lambda ( x y ) ( + x y ) ) 1 2 ) > 3 > > ( ( lambda ( x y ) ( + x y ) ) 1 ) > arity mismatch; > the expected number of arguments does not match the given > number > expected: 2 > given: 1 > ``` #### 4.4.1 Declaring a Rest Argument 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) expression can also have the form > > ``` (lambda rest-id > > body ...+ ) ```
# 3.2 Numbers That 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. Examples: > ```racket > > ( ( lambda x x ) 1 2 3 ) > '(1 2 3) > > ( ( lambda x x ) ) > '() > > ( ( lambda x ( car x ) ) 1 2 3 ) > 1 > ``` Functions with a rest-id often use apply to call another function that accepts any number of arguments. > > > <img src="finger.png" width="24" height="24" alt="+" />The apply Function describes apply. Examples: > ```racket > ( define max-mag ( lambda nums ( apply max ( map magnitude nums ) ) ) ) > > ( max 1 -2 0 ) > 1 > > ( max-mag 1 -2 0 ) > 2 > ``` The lambda form also supports required arguments combined with a rest-id: > > ``` (lambda (arg-id ...+ . rest-id) > > body ...+ )``` The 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. Examples: > ```racket > ( define max-mag ( lambda ( num . nums ) ( apply max ( map magnitude ( cons num nums ) ) ) ) ) > > ( max-mag 1 -2 0 ) > 2 > > ( max-mag ) > max-mag: arity mismatch; > the expected number of arguments does not match the given > number > expected: at least 1 > given: 0 > ``` A 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.
#### 4.4.2 Declaring Optional Arguments Instead 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: > > ``` (lambda gen-formals > > body ...+ ) gen-formals   =   (arg ...)     |   rest-id     |   (arg ...+ . rest-id) arg   =   arg-id     |   [arg-id default-expr] ``` An 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. Examples: > ```racket > ( define greet ( lambda ( given [ surname "Smith" ] ) ( string-append "Hello, " given " " surname ) ) ) > > ( greet "John" ) > "Hello, John Smith" > > ( greet "John" "Doe" ) > "Hello, John Doe" > ``` > ``` (define greet > ( lambda ( given [ surname ( if ( equal? given "John" ) > "Doe" > "Smith" ) ] ) > ( string-append "Hello, " given " " surname ) ) )   > ( greet "John" ) > "Hello, John Doe" > > ( greet "Adam" ) > "Hello, Adam Smith"``` #### 4.4.3 Declaring Keyword Arguments 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 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: > > > <img src="finger.png" width="24" height="24" alt="+" />[Keyword Arguments](application.html#%28part._keyword-args%29) introduces function calls with keywords. > > ``` (lambda gen-formals > > body ...+ )   gen-formals   =   (arg ...)     |   rest-id     |   (arg ...+ . rest-id)           arg   =   arg-id     |   [arg-id default-expr]     |   arg-keyword arg-id     |   arg-keyword [arg-id default-expr] ```
# 3.2 Numbers An 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. > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define greet > ( lambda ( given #:last surname ) > ( string-append "Hello, " given " " surname ) ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>> ( greet "John" #:last "Smith" ) > "Hello, John Smith" > > ( greet #:last "Doe" "John" ) > "Hello, John Doe"</code></pre></td></tr></tbody></table> An arg-keyword \[arg-id default-expr\] argument specifies a keyword-based argument with a default value. Examples: > ```racket > ( define greet ( lambda ( #:hi [ hi "Hello" ] given #:last [ surname "Smith" ] ) ( string-append hi ", " given " " surname ) ) ) > > ( greet "John" ) > "Hello, John Smith" > > ( greet "Karl" #:last "Marx" ) > "Hello, Karl Marx" > > ( greet "John" #:hi "Howdy" ) > "Howdy, John Smith" > > ( greet "Karl" #:last "Marx" #:hi "Guten Tag" ) > "Guten Tag, Karl Marx" > ```
# 3.2 Numbers The 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. > > > <img src="finger.png" width="24" height="24" alt="+" />The apply Function introduces keyword-apply. Examples: > ```racket > ( 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 ) ) ) ) > > ( ( trace-wrap greet ) "John" #:hi "Howdy" ) > Called with (#:hi) ("Howdy") ("John") > "Howdy, John Smith" > ``` > > > <img src="magnify.png" width="24" height="24" alt="+" />Procedure Expressions: lambda and case-lambda in The Racket Reference provides more on function expressions.
#### 4.4.4 Arity-Sensitive Functions: case-lambda The 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 > > ``` (case-lambda > > [ formals body ...+ ] > > ... ) formals   =   (arg-id ...)     |   rest-id     |   (arg-id ...+ . rest-id)``` where 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. Examples:
# 3.2 Numbers > ```racket > ( define greet ( case-lambda [ ( name ) ( string-append "Hello, " name ) ] [ ( given surname ) ( string-append "Hello, " given " " surname ) ] ) ) > > ( greet "John" ) > "Hello, John" > > ( greet "John" "Smith" ) > "Hello, John Smith" > > ( greet ) > greet: arity mismatch; > the expected number of arguments does not match the given > number > given: 0 > ``` A [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. ------------------------------------------------------------------------
# 4.5 Definitions: define
### 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) A basic definition has 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) | in which case id is bound to the result of expr. Examples: > ```racket > ( define salutation ( list-ref ' ( "Hi" "Hello" ) ( random 2 ) ) ) > > salutation > "Hi" > ```
#### 4.5.1 Function Shorthand 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 also supports a shorthand for function 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) (id arg ...) body ...+) | which is a shorthand for
### 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) > ([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 ...+)) Examples: > ```racket > ( define ( greet name ) ( string-append salutation ", " name ) ) > > ( greet "John" ) > "Hi, John" > ``` > ``` (define (greet first [surname "Smith"] #:hi [hi salutation]) > ( string-append hi ", " first " " surname ) ) > ( greet "John" ) > "Hi, John Smith" > > ( greet "John" #:hi "Hey" ) > "Hey, John Smith" > > ( greet "John" "Doe" ) > "Hi, John Doe"
### 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) ``` The function shorthand via define also supports a rest argument (i.e., a final argument to collect extra arguments in a list): > > | | > > |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | (define (id arg ... . rest-id) body ...+) | which is a shorthand > (define id (lambda (arg ... . rest-id) body ...+)) Examples: > ```racket > ( define ( avg . l ) ( / ( apply + l ) ( length l ) ) ) > > ( avg 1 2 3 ) > 2 > ``` #### 4.5.2 Curried Function Shorthand Consider the following make-add-suffix function that takes a string and returns another function that takes a string: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define make-add-suffix > ( lambda ( s2 ) > ( lambda ( s ) ( string-append s s2 ) ) ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code></code></pre></td></tr></tbody></table> Although it’s not common, the result of make-add-suffix could be called directly, like this: > ```racket > > ( ( make-add-suffix "!" ) "hello" ) > "hello!" > ``` In 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. Using the function-shorthand form of define, make-add-suffix can be written equivalently as > ```racket > ( define ( make-add-suffix s2 ) > ( lambda ( s ) ( string-append s s2 ) ) ) > ``` This 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: > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define ( ( make-add-suffix s2 ) s ) > ( string-append s s2 ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>> ( ( make-add-suffix "!" ) "hello" ) > "hello!"</code></pre></td></tr></tbody></table> > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td><pre><code>( define louder ( make-add-suffix "!" ) ) > ( define less-sure ( make-add-suffix "?" ) )</code></pre></td></tr><tr><td><p> </p></td></tr><tr><td><pre><code>> ( less-sure "really" ) > "really?" > > ( louder "really" ) > "really!"</code></pre></td></tr></tbody></table> The full syntax of the function shorthand for define is as follows: > > <table data-cellpadding="0" data-cellspacing="0"><colgroup><col style="width: 100%" /></colgroup><tbody><tr><td>(define (head args) body ...+)</td></tr><tr><td> </td></tr><tr><td><table data-cellpadding="0" data-cellspacing="0"><tbody><tr><td style="text-align: right;" data-valign="baseline">head</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">=</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">id</td></tr><tr><td style="text-align: right;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">|</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">(head args)</td></tr><tr><td style="text-align: right;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td></tr><tr><td style="text-align: right;" data-valign="baseline">args</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">=</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">arg ...</td></tr><tr><td style="text-align: right;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: center;" data-valign="baseline">|</td><td style="text-align: left;" data-valign="baseline"> </td><td style="text-align: left;" data-valign="baseline">arg ... . rest-id</td></tr></tbody></table></td></tr></tbody></table> The expansion of this shorthand has one nested lambda form for each head in the definition, where the innermost head corresponds to the outermost lambda. #### 4.5.3 Multiple Values and define-values A 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: > ```racket > > ( quotient 13 3 ) > 4 > > ( remainder 13 3 ) > 1 > > ( quotient/remainder 13 3 ) > 4 1 > ``` As shown above, the REPL prints each result value on its own line. Multiple-valued functions can be implemented in terms of the values function, which takes any number of values and returns them as the results: > ```racket > > ( values 1 2 3 ) > 1 2 3 > ``` > ``` (define (split-name name) > ( let ( [ parts ( regexp-split " " name ) ] ) > ( if ( = ( length parts ) 2 ) > ( values ( list-ref parts 0 ) ( list-ref parts 1 ) ) > ( error "not a <first> <last> name" ) ) ) )   > ( split-name "Adam Smith" ) > "Adam" "Smith"``` The [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: > > | | > > |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| > > | ([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) | The number of results produced by the expr must match the number of ids. Examples: > ```racket > ( define-values ( given surname ) ( split-name "Adam Smith" ) ) > > given > "Adam" > > surname > "Smith" > ``` A [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. > > > <img src="magnify.png" width="24" height="24" alt="+" />[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. #### 4.5.4 Internal Definitions When 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. Expressions and internal definitions in a body sequence can be mixed, as long as the last body is an expression. For 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 > > ``` (lambda gen-formals > > body ...+ ) ```
### 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) so the following are valid instances of the grammar: > ```racket > ( lambda ( f ) ; no definitions > ( printf "running\n" ) > ( f 0 ) ) > ( lambda ( f ) ; one definition > ( define ( log-it what ) > ( printf "~a\n" what ) ) > ( log-it "running" ) > ( f 0 ) > ( log-it "done" ) ) > ( lambda ( f n ) ; two definitions > ( define ( call n ) > ( if ( zero? n ) > ( log-it "done" ) > ( begin > ( log-it "running" ) > ( f n ) > ( call ( - n 1 ) ) ) ) ) > ( define ( log-it what ) > ( printf "~a\n" what ) ) > ( call n ) ) > ``` Internal 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. Examples: > ```racket > ( define ( weird ) ( define x x ) x ) > > ( weird ) > x: undefined; > cannot use before initialization > ``` A 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).
### 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) > > > <img src="magnify.png" width="24" height="24" alt="+" />Internal Definitions in The Racket Reference documents the fine points of internal definitions. ------------------------------------------------------------------------
# 4.6 Local Binding
### 4.6 Local Binding Although internal defines can be used for local binding, Racket provides three forms that give the programmer more control over bindings: let, let*, and letrec.
End of preview. Expand in Data Studio

Racket Programming Language Documentation

This dataset contains the Racket programming language documentation, chunked using semantic parsing for pretraining language models.

Updated: 2025-09-08

Loading

from datasets import load_dataset
ds = load_dataset("json", data_files={"train": "train.jsonl"}, split="train")

Statistics

  • Format: JSONL with single text field per line
  • Chunking: Semantic structure-aware chunking
  • Content: Official Racket documentation and manuals
Downloads last month
10

Collection including jusjinuk/racket-manuals