### Install Rhombus Package using Raco Source: https://docs.racket-lang.org/rhombus/Quick_Start This command-line instruction installs the Rhombus package for Racket. It requires the Raco command-line tool, which is included with Racket installations. This command fetches and installs the latest stable version of Rhombus. ```bash > raco pkg install rhombus ``` -------------------------------- ### Try Match Port Example Setup Source: https://docs.racket-lang.org/rhombus/-reference/Regexp_Objects This code snippet sets up an input port from a string, which is a prerequisite for demonstrating the try_match methods on port inputs. ```raskell > def p = Port.Input.open_string("hello") ``` -------------------------------- ### Render Block-like Description (Racket) Source: https://docs.racket-lang.org/rhombus/-reference/Printables Illustrates the use of `PrintDesc.block` to render a multi-line block structure. The example defines a block starting with "begin" and containing two lines of text: "one" and "two", separated by a newline. This rendering specifically showcases how `PrintDesc.block` handles multi-line content when pretty printing is enabled. ```racket Printable.render( PrintDesc.block( "begin", PrintDesc.concat( "one", PrintDesc.newline(), "two" ))) ``` -------------------------------- ### Racket: Install or Query Syntax Source Properties Source: https://docs.racket-lang.org/rhombus/-reference/stxobj These methods facilitate the installation or querying of source text information for syntax objects. Source text is segmented into prefix, content, tail, and suffix. The information is structured as a tree of Pairs, PairList.empty, and strings. ```racket ;; Query source properties for a Term (Syntax.source_properties syntax) ;; Install source properties for a Term (Syntax.source_properties syntax prefix content tail suffix) ;; Query source properties for a Group (Syntax.group_source_properties syntax) ;; Install source properties for a Group (Syntax.group_source_properties syntax prefix content tail suffix) ``` -------------------------------- ### Regexp Match with Start Offset Example Source: https://docs.racket-lang.org/rhombus/-reference/Regexp_Objects This example shows how the ~start argument in match_in can be used to specify a portion of the input string to begin matching from, ignoring content before the specified offset. ```raskell > rx'"a"*'.match_in("a aa aaa", ~start: 2) RXMatch("aa", [], {}) ``` -------------------------------- ### Rhombus Importing Installed Library Source: https://docs.racket-lang.org/rhombus/Modules Illustrates how to import an installed Rhombus library by specifying its path using a `/` separator. The last path element determines the default import prefix. ```Rhombus import: rhombus/measure measure.cpu_milliseconds() // prints a number ``` -------------------------------- ### Racket Class Definition Example Source: https://docs.racket-lang.org/rhombus/-reference/class Demonstrates a basic class definition in Racket with fields and instance access. ```racket > | > class Posn(x, y) > --- > | > Posn(1, 2) > --- > Posn(1, 2) > | > Posn.x > --- > # > | > Posn.x(Posn(1, 2)) > --- > 1 > | > Posn(1, 2).x > --- > 1 ``` -------------------------------- ### Regexp Matching Examples Source: https://docs.racket-lang.org/rhombus/-reference/Regexp_Objects Illustrative examples demonstrating the usage of Regexp matching methods like match and match_in, showing successful matches, non-matches, and boolean checks for matches. ```racket > rx'"a"'.match("a") RXMatch("a", [], {}) > rx'"a"'.match("ab") #false > rx'"a"'.match_in("ab") RXMatch("a", [], {}) > rx'"a"'.is_match("ab") #false > rx'"a"'.is_match_in("ab") #true ``` -------------------------------- ### Rhombus Module with Main Submodule Example Source: https://docs.racket-lang.org/rhombus/main-submod This example demonstrates a Rhombus module that exports a 'greeting' function. When run directly, it also executes the 'greeting' function from its 'main' submodule and prints the result. This pattern allows a module to serve as both a library and an executable program. ```rhombus #lang rhombus --- export: greeting fun greeting(): "hello" module main: greeting() ``` -------------------------------- ### Racket Syntax Class Examples Source: https://docs.racket-lang.org/rhombus/-reference/Syntax_Classes Examples of defining various syntax classes in Racket, specifying their kind. These classes are used for matching different types of syntax, such as terms, sequences, groups, multis, and blocks. ```racket syntax class | syntax_class Term: kind: ~term syntax class | syntax_class Identifier: kind: ~term syntax class | syntax_class Operator: kind: ~term syntax class | syntax_class Name: kind: ~sequence syntax class | syntax_class IdentifierName: kind: ~sequence syntax class | syntax_class Keyword: kind: ~term syntax class | syntax_class String: kind: ~term syntax class | syntax_class Int: kind: ~term syntax class | syntax_class Number: kind: ~term syntax class | syntax_class Boolean: kind: ~term syntax class | syntax_class Literal: kind: ~term syntax class | syntax_class Sequence: kind: ~sequence syntax class | syntax_class Group: kind: ~group syntax class | syntax_class Multi: kind: ~multi syntax class | syntax_class Block: kind: ~block ``` -------------------------------- ### Example: Creating and Inspecting a Cross-Platform Path (Racket) Source: https://docs.racket-lang.org/rhombus/-reference/cross-path Demonstrates how to create a cross-platform path with a specified convention and then access its string representation and convention. ```racket > | > def p = CrossPath("#/home/rhombus/shape.txt", #'unix) > --- > | > p.string() > --- > "/home/rhombus/shape.txt" > | > p.convention() > --- > #'unix ``` -------------------------------- ### Racket PairList Pattern Matching Examples Source: https://docs.racket-lang.org/rhombus/-reference/Pairs Demonstrates various ways to match a pair list using patterns with bind_or_splices, similar to how List matches lists. Includes examples with direct values, binding variables, and splices. ```racket > def PairList(1, x, y) = PairList[1, 2, 3] > y 3 ``` ```racket > def PairList[1, also_x, also_y] = PairList[1, 2, 3] > also_y 3 ``` ```racket > def PairList(1, & xs) = PairList[1, 2, 3] > xs PairList[2, 3] ``` ```racket > def PairList(1, x, ...) = PairList[1, 2, 3] > PairList[x, ...] PairList[2, 3] ``` -------------------------------- ### Rhombus Guard.let Example: Successful Match Source: https://docs.racket-lang.org/rhombus/-reference/Guards An example of 'guard.let' successfully matching a list against a pattern '[_, _, third, & _]', binding the third element to 'third', and printing it. ```Rhombus fun print_third(xs): guard.let [_, _, third, & _] = xs | println("list doesn't have three or more elements") println(third) ``` -------------------------------- ### Implementing Indexable Interface (Rhombus) Source: https://docs.racket-lang.org/rhombus/-reference/Indexables An example of a class implementing the Indexable interface in Rhombus. This allows instances of the class to be used with the #%index form for element access. The `get` method defines how elements are retrieved. ```Rhombus class Interleaved(lst1, lst2): private implements Indexable private override method get(index): if (index mod 2) == 0 lst1[index div 2] lst2[index div 2] > def lsts = Interleaved([1, 2, 3], [-1, -2, -3]) > lsts[2] 2 > lsts[3] -2 ``` -------------------------------- ### Racket Nonfinal Class and Constructor Example Source: https://docs.racket-lang.org/rhombus/-reference/class Shows the definition of a nonfinal class with custom constructor arguments and inheritance. ```racket > | > class Rectangle(w, h): > --- > nonfinal > constructor (~width: w, ~height: h): > super(w, h) > | > class Square(): > --- > extends Rectangle ``` -------------------------------- ### Create Rhombus Program Distribution with raco dist Source: https://docs.racket-lang.org/rhombus/standalone Assembles all necessary files for a Rhombus program into a distribution directory. This allows the program to be installed and run on other machines without a full Racket and Rhombus installation. ```bash raco dist prog_dist prog ``` -------------------------------- ### Rhombus Module Execution Example Source: https://docs.racket-lang.org/rhombus/Modules Demonstrates the basic structure of a Rhombus module, including the '#lang rhombus' declaration and how expressions at the top level are evaluated and printed. ```Rhombus #lang rhombus 1+4 // prints 5 "Hello, world!" // prints "Hello, world!", including the quotes ``` -------------------------------- ### Rhombus Namespace Export Example (Direct) Source: https://docs.racket-lang.org/rhombus/-reference/Export Demonstrates exporting a directly defined identifier 'x' from a namespace 'ns1'. The example shows how 'export x' makes 'ns1.x' accessible with its value. ```racket | > namespace ns1: --- def x = 1 export x | > ns1.x --- 1 ``` -------------------------------- ### Rhombus Syntax Class for Export Name Start Source: https://docs.racket-lang.org/rhombus/-meta/Export_Macros Defines a syntax class `expo_meta.NameStart` for identifying the start of an export name. It uses `head` and `tail` fields to parse the name structure. ```racket | syntax_class expo_meta.NameStart: --- kind: ~group fields: name [head, ...] [tail, ...] ``` -------------------------------- ### Rhombus Guard.let Block Form Example: Successful Match Source: https://docs.racket-lang.org/rhombus/-reference/Guards An example using the block form of 'guard.let' that successfully matches a list against a pattern, binding the third element and printing it. ```Rhombus fun print_third(xs): guard.let [_, _, third, & _]: xs | println("list doesn't have three or more elements") println(third) ``` -------------------------------- ### Racket Example: Iterating Lines Source: https://docs.racket-lang.org/rhombus/-reference/Input_Ports Demonstrates iterating through lines of a string port using the 'lines' method. Each line is processed sequentially. ```Racket > | > def p = Port.Input.open_string("a\nb\nc") > --- > | > for (ln in p.lines()): > --- > showln(ln) > "a" > "b" > "c" ``` -------------------------------- ### Racket Example: NTerms Syntax Class with Fields Source: https://docs.racket-lang.org/rhombus/-reference/Syntax_Classes Illustrates a Racket syntax class `NTerms` that defines fields like `b` and `average`. It shows how to declare fields and compute their values based on matched patterns, including examples of macro usage. ```racket > | > meta syntax_class NTerms > --- > | '~one $a': > field b = '0' > field average = '$(a.unwrap() / 2)' > | '~two $a $b': > def sum = a.unwrap() + b.unwrap() > field average = '$(sum / 2)' > | > expr.macro 'second_term $(e :: NTerms)': > --- > e.b > | > second_term ~two 1 2 > --- > 2 > | > second_term ~one 3 > --- > 0 > | > expr.macro 'average $(e :: NTerms)': > --- > e.average > | > average ~two 24 42 > --- > 33 ``` -------------------------------- ### Rhombus 'meta' with Example Macro Usage Source: https://docs.racket-lang.org/rhombus/-meta/Meta_Definitions_and_Expressions Demonstrates the usage of the 'meta' construct within a Rhombus program, showcasing how it can define and apply macros for arithmetic operations and static evaluations. This example highlights compile-time evaluation and transformation. ```Rhombus > | > meta: > --- > syntax_class Arithmetic > | '$x + $y' > | '$x - $y' > | > expr.macro 'right_operand $(exp :: Arithmetic)': > --- > exp.y > | > right_operand 1 + 2 > --- > 2 > | > meta fun add1(x): > --- > x+1 > | > expr.macro 'add1_statically $(n :: Int)': > --- > '#%literal $(add1(Syntax.unwrap(n)))' > | > add1_statically 13 > --- > 14 ``` -------------------------------- ### Get Range Start and End Points (Racket) Source: https://docs.racket-lang.org/rhombus/-reference/Ranges Retrieves the starting and ending points of a range. These can be negative infinity or positive infinity to signify no bound. The methods are `start()` and `end()`. ```racket method (rge :: Range).start() :: Int || matching(#neginf) --- method --- | method (rge :: Range).end() :: Int || matching(#inf) ``` -------------------------------- ### Get Operating System Source: https://docs.racket-lang.org/rhombus/-reference/system Provides a more specific operating system identifier than system.type. For example, it might return #'linux or #'freebsd for a Unix-like system. ```Rhombus system.os() ``` -------------------------------- ### Basic Rhombus Program: Hello, World! Source: https://docs.racket-lang.org/rhombus/Quick_Start A minimal Rhombus program that prints 'Hello, World!' to the console. It uses the '#lang rhombus' directive to specify the language and a simple string literal. This is typically entered into the DrRacket IDE. ```rhombus #lang rhombus --- "Hello, World!" ``` -------------------------------- ### Racket Class Inheritance Example (Extends) Source: https://docs.racket-lang.org/rhombus/-reference/class Illustrates extending a parent class in Racket, including issues with extending final classes and chaining inheritance. ```racket > | > class Posn3(z): > --- > extends Posn > class: superclass is final and cannot be extended > | > class Posn2D(x, y): > --- > nonfinal > | > class Posn3D(z): > --- > extends Posn2D > | > Posn3D(1, 2, 3) > --- > Posn3D(1, 2, 3) ``` -------------------------------- ### Rhombus: List Length Example Source: https://docs.racket-lang.org/rhombus/namespaces-overview Demonstrates accessing a function within a hierarchical namespace using dot notation. This showcases how to call `List.length` to get the number of elements in a list. ```Rhombus > List.length(["a", "b", "c"]) 3 ``` -------------------------------- ### Get System Host Details Source: https://docs.racket-lang.org/rhombus/-reference/system Returns a string containing platform-specific details about the host operating system. ```Rhombus system.host() ``` -------------------------------- ### Get element at index in Racket list Source: https://docs.racket-lang.org/rhombus/-reference/Lists Retrieves the nth element of a list (starting from 0). Accessing an element by position takes O(log N) time. This is equivalent to lst[n]. ```Racket lst.get(n) lst[n] ``` -------------------------------- ### Constructing and Parsing Command-Line Arguments with cmdline.parser Source: https://docs.racket-lang.org/rhombus/-reference/cmdline-make The cmdline.parser form creates a parser for command-line arguments, while cmdline.parse creates the parser and immediately applies it. Both use content expressions to define flag and argument handlers. The result is a map representing the parsed state. Options like ~init allow for initial state configuration, and ~no_builtin adds implicit --help/-h support. ```racket | cmdline.parser: --- option ... content_expr ... expression | cmdline.parse: --- option ... content_expr ... expression ``` -------------------------------- ### Immediate Callee Macro Expansion Example in Racket Source: https://docs.racket-lang.org/rhombus/-meta/Immediate_Callee_Macros Demonstrates the expansion logic for an immediate callee macro, showing how it differentiates between parsing as a callee or as a general expression based on context. ```racket > | immediate_callee.macro 'enlist $tail ...': > --- > ~op_stx: all > ~static_infos: sis > ~in_op_mode mode > ~in_op_stx op > if expr_meta.ends_parse(mode, op, '$tail ...') > | // parse as callee > let res = annot_meta.pack_predicate('fun (x): #true', > sis[0]) > values('fun (x) :~ List.of($res): [x]', > '$tail ...') > | // parse as expression > 'dynamic(enlist) $tail ...' > | > use_static > --- > | > ("apple" |> enlist)[0][0] > --- > Char"a" ``` -------------------------------- ### Implementing MutableIndexable Interface (Rhombus) Source: https://docs.racket-lang.org/rhombus/-reference/Indexables An example class implementing the MutableIndexable interface in Rhombus, extending Indexable. This enables both element access via `get` and modification via `set` using the #%index form with assignment operators. ```Rhombus class InterleavedArray(arr1, arr2): private implements MutableIndexable private override method get(index): if (index mod 2) == 0 arr1[index div 2] arr2[index div 2] private override method set(index, val): if (index mod 2) == 0 arr1[index div 2] := val arr2[index div 2] := val ``` -------------------------------- ### Racket Function Annotation: Multiple Return Values Source: https://docs.racket-lang.org/rhombus/-reference/function-annot Demonstrates how to annotate functions that return multiple values in Racket using '(Any, ...)' or equivalent forms. This example shows accepting an Int and returning multiple values starting from 0 up to n. ```racket > def n_values :: (Int) -> (Any, ...): fun (n): values(& 0..n) > n_values(1) --- 0 > n_values(3) --- 0 1 2 ``` -------------------------------- ### File Input and Output Operations Source: https://docs.racket-lang.org/rhombus/port Illustrates how to open, read from, and write to files using `Port.Output.open_file` and `Port.Input.open_file`. It covers writing byte strings, closing files, and reading specific byte lengths. The example uses `filesystem.make_temporary` for temporary file handling. ```Rhombus def tmp = filesystem.make_temporary() def outp = Port.Output.open_file(tmp.path, ~exists: #'truncate) outp.write_bytes(#"data") outp.close() def inp = Port.Input.open_file(tmp.path) inp.read_bytes(4) inp.close() tmp.close() ``` -------------------------------- ### Get Real Time Milliseconds in Rhombus `measure.real_milliseconds` Source: https://docs.racket-lang.org/rhombus/-reference/measure The `measure.real_milliseconds` function returns the number of milliseconds elapsed in real time since an unspecified starting point. Unlike `system.milliseconds`, its results are not affected by system clock adjustments and advance with real time within a process, but are not comparable across processes. ```racket import: rhombus/measure (measure.real_milliseconds) ``` -------------------------------- ### Rhombus Export Syntax Examples Source: https://docs.racket-lang.org/rhombus/-reference/Export Illustrates various forms of the 'export' declaration in Rhombus, including exporting specific definitions, renaming exports, and exporting all defined items. This demonstrates the core syntax for controlling module visibility. ```racket | export: | --- export_clause --- nestable declaration | export export_clause | --- nestable declaration | export defn | --- nestable declaration | export ~scope_like id defn | --- | export_clause| = | | export_item | --- | | | | export_item: | --- modifier ... | | | | | modifier: | --- export_clause ... | | export_item| = | | id_or_op | --- | | | | all_from(source) | --- | | | | rename rename_decl | --- | | | | names names_decl | --- | | | | all_defined all_defined_decl | --- | | | | export_item #%juxtapose export_item | --- | | | | other_export | --- | id_or_op| = | | id_name | --- | | | | op_name | --- | modifier| = | | except except_decl | --- | | | | meta meta_decl | --- | | | | meta_label | --- | | | | only_space only_space_decl | --- | | | | except_space except_space_decl | --- | | | | other_modifier | --- Exports from the enclosing module or namespace. An export form with a single immediate export_clause is shorthand for an export form that has a block containing the single export_clause, except that export as a prefix before a defn (optionally with ~scope_like id) means the same as the defn plus exporting the defined names. ``` ```racket | export all_from(module_path) | --- export | all_from(. id_name) | --- With module_path, exports all bindings imported without a prefix from module_path, where module_path appears the same via import. “The same” means that the module paths are the same after some normalization: paths that use /-separated indentifiers are converted to lib forms, and in a lib form, an implicit ".rhm" suffix is made explicit. With . id_name, exports the content of the specified namespace or module import (i.e., the content that would be accessed with a prefix in the exporting context). See Namespaces for information on id_name. ``` ```racket | export: | --- rename: --- int_id_or_op as ext_id_or_op ... export | rename int_id_or_op as ext_id_or_op | --- For each as group, exports int_id_or_op bound locally so that it’s imported as ext_id_or_op. ``` ```racket | export: | --- names: --- id_or_op ... ... Exports all id_or_ops. Most id_or_ops can be exported directly without using names, but the names form disambiguates in the case of an id_or_op that is itself bound as an export form or modifier. ``` ```racket | export all_defined | --- export | all_defined ~scope_like id | --- ``` -------------------------------- ### Extract Sublist from List in Racket Source: https://docs.racket-lang.org/rhombus/-reference/Lists Returns a sublist based on start and end indices or a range. Equivalent to lst.drop(start).take(end - start) when using indices. ```Racket > [1, 2, 3, 4, 5].sublist(1, 3) --- [2, 3] ``` ```Racket > [1, 2, 3, 4, 5].sublist(1..=3) --- [2, 3, 4] ``` ```Racket > [1, 2, 3, 4, 5].sublist(1..) --- [2, 3, 4, 5] ``` ```Racket > [1, 2, 3, 4, 5].sublist(..3) --- [1, 2, 3] ``` ```Racket > [1, 2, 3, 4, 5].sublist(..) --- [1, 2, 3, 4, 5] ``` -------------------------------- ### Rhombus: Simple Class Definition and Method Call Source: https://docs.racket-lang.org/rhombus/class-together Demonstrates a basic Rhombus class definition 'Posn' with a constructor and a function 'make' that creates an instance. It shows how to define and then use the class and its associated function. ```racket def make: fun () :: Posn: Posn(1, 2) class Posn(x, y) make() Posn(1, 2) ``` -------------------------------- ### Syntax Class for Sequence Definition Starts (defn_meta.SequenceStartGroup) - Racket Source: https://docs.racket-lang.org/rhombus/-meta/Definition_Macros A syntax class that matches only groups starting with an identifier bound as a definition-sequence form. This syntax class is used to identify the start of sequence-based definitions within a context. ```racket syntax_class defn_meta.SequenceStartGroup: kind: ~group ``` -------------------------------- ### File and Stream Port Operations Source: https://docs.racket-lang.org/rhombus/-reference/Output_Ports Documentation for opening, closing, and interacting with file and stream ports. ```APIDOC ## File and Stream Port Operations ### Description Functions for managing file and stream ports, including opening and closing them. ### Endpoints #### `Port.Output.open_file` - **Description**: Opens a file for writing. - **Parameters**: - `filename` (string) - Required - The name of the file to open. - `mode` (symbol) - Optional - The mode to open the file in (e.g., `:truncate`, `:append`). Defaults to `:truncate`. - **Method**: Typically a function call in the language, not a REST API. #### `Port.Output.open_bytes` - **Description**: Opens a byte string for writing. - **Method**: Typically a function call in the language, not a REST API. #### `Port.Output.open_string` - **Description**: Opens a string buffer for writing. - **Method**: Typically a function call in the language, not a REST API. #### `Port.Output.close` - **Description**: Closes an open port. - **Parameters**: - `port` (port) - Required - The port to close. - **Method**: Typically a function call in the language, not a REST API. ### Request Example ``` (define my-file-port (Port.Output.open_file "output.txt" #:mode "append")) (Port.Output.write_string my-file-port "Appending some text.") (Port.Output.close my-file-port) ``` ### Response Example File operations modify the file system. No direct response data in this context. ``` -------------------------------- ### Racket Array Copy Method Source: https://docs.racket-lang.org/rhombus/-reference/Arrays The `copy(start, end)` method creates a new mutable array containing a slice of the original array's elements, from `start` (inclusive) to `end` (exclusive). Default values for `start` and `end` allow for copying the entire array or from a specific index to the end. ```Racket method (arr :: Array).copy(start :: NonnegInt = 0, end :: NonnegInt = Array.length(arr)) :: MutableArray def a = Array("a", "b", "c") a.copy() a.copy(1) a.copy(1, 2) ``` ```Racket def a = Array("a", "b", "c").snapshot() a.copy() ``` -------------------------------- ### Convenience Wrappers for File I/O Source: https://docs.racket-lang.org/rhombus/port Introduces the `Port.Output.using` and `Port.Input.using` functions as convenient wrappers for opening, using, and automatically closing files for I/O operations. This simplifies common file handling patterns. ```Rhombus def tmp = filesystem.make_temporary() Port.Output.using ~file tmp.path: ~exists: #'truncate println("data") Port.Input.using ~file tmp.path: stdin.read_line() tmp.close() ``` -------------------------------- ### Rhombus Pipe-Forward Operator Example Source: https://docs.racket-lang.org/rhombus/-reference/ref-function-call Shows a practical example of the pipe-forward operator '|>' being used to apply a function (List.length) to a list. ```racket | > [1, 2, 3] |> List.length ``` -------------------------------- ### Rhombus Closeable.let Example Source: https://docs.racket-lang.org/rhombus/-reference/Closeables An example demonstrating the usage of Closeable.let to open a file, read from it, and ensure the file is automatically closed afterward, even if errors occur. ```rhombus > | > block: > --- > Closeable.let i = Port.Input.open_file("data.txt") > i.read_line() > // `i` is closed after this point > "file content" ``` -------------------------------- ### Rhombus Bitwise Field Extraction Source: https://docs.racket-lang.org/rhombus/-reference/Numbers Produces the integer represented by bits from `start` (inclusive) through `end` (exclusive) of an integer `n`. `start` and `end` must be non-negative integers. ```Racket | fun bits.field(n :: Int, start :: NonnegInt, end :: NonnegInt) :: Int ``` ```Racket > | > bits.field(255, 1, 4) > --- > 7 ``` -------------------------------- ### Rhombus entry_point.macro definition and usage Source: https://docs.racket-lang.org/rhombus/-meta/Entry_Point_Macros Demonstrates the definition of an entry point macro using `entry_point.macro` and its subsequent usage within a class method. It illustrates how the 'identity' macro is defined and then applied to a method, showing the expected output. ```racket > | entry_point.macro 'identity': --- ~mode mode ~adjustment adj match mode | #'shape: { #'arity: [2, [], []] } | #'function: let [arg, ...] = adj.prefix_arguments entry_point_meta.pack( 'fun ($arg, ..., x): $(adj.wrap_body(2, 'x'))' ) | > class C(): --- method m: identity | > C().m("ok") --- "ok" ``` -------------------------------- ### Example of a Custom Language Usage in Rhombus Source: https://docs.racket-lang.org/rhombus/lang This snippet shows how to use a custom language defined with `#lang`. Assuming `noisy_rhombus` is registered as a collection, this example illustrates a simple expression within that language. ```racket #lang noisy_rhombus 1 + 2 // prints "1 + 2" and then "3" ``` -------------------------------- ### Racket Rhombus: Basic Regular Expression Matching Source: https://docs.racket-lang.org/rhombus/rx-lang Demonstrates basic regular expression matching using the 'rx' language in Racket. It shows how to define patterns for repetitions and literal characters, and use the .match method to test them against input strings. The 'open' command is required to import the 'rhombus/rx' library. ```racket | import: --- rhombus/rx open | > rx'.*' --- is a regular expression that matches any number of repetitions of any non-newline character, since the . operator matches any non-newline character, and the * operator combines with the preceding pattern to match any number (zero or more) repetitions of that pattern. > > > More precisely, .* is a single shrubbery operator, but .* is defined as an alias of . followed by .* > rx'"a"* "b"*'.match("aaabb") --- RXMatch("aaabb", [], {}) | > rx'"a"* "b"*'.match("xxaaabb") --- #false > | > rx'"a"* "b"*'.match("aaabbxx") --- #false > | > rx'"a"* "b"*'.match_in("xx") // matches 0 repetitions at start --- RXMatch("", [], {}) ``` -------------------------------- ### Rhombus Guard Example: False Condition Source: https://docs.racket-lang.org/rhombus/-reference/Guards An example demonstrating the 'guard' form where the 'test_expr' evaluates to false, skipping the primary body and executing the 'failure_body', printing 'KABOOM!!!'. ```Rhombus guard #false | println("KABOOM!!!") println("everything working normally") ``` -------------------------------- ### Rhombus Guard Example: True Condition Source: https://docs.racket-lang.org/rhombus/-reference/Guards An example demonstrating the 'guard' form where the 'test_expr' evaluates to true, executing the primary body and printing 'everything working normally'. ```Rhombus guard #true | println("KABOOM!!!") println("everything working normally") ``` -------------------------------- ### Creating Lists in Rhombus Source: https://docs.racket-lang.org/rhombus/list Demonstrates how to create lists using the bracket syntax and the `List` constructor. Lists can contain elements of various types. The `List` constructor can take any number of arguments. ```racket > | > [1, 2, 3] > --- > [1, 2, 3] > | > [0, "apple", Posn(1, 2)] > --- > [0, "apple", Posn(1, 2)] > | > List(1, 2, 3) > --- > [1, 2, 3] ``` -------------------------------- ### Output Port Context Parameters Source: https://docs.racket-lang.org/rhombus/-reference/Output_Ports Information about context parameters for determining the current output port. ```APIDOC ## Output Port Context Parameters ### Description Context parameters that define the default output port for printing operations. ### Parameters - **Port.Output.current**: The default output port for general printing. - **Port.Output.current_error**: The default output port for printing errors. ``` -------------------------------- ### Command Line Parser Parameters Source: https://docs.racket-lang.org/rhombus/-reference/cmdline-help Provides details on context parameters used for command-line parsing, including defaults and how they are set during parsing. ```APIDOC ## Context Parameters for Command Line Parsing ### Description These context parameters provide default values and are updated during command-line parsing to reflect user-supplied arguments. ### Parameters #### Context Parameters - **cmdline.current_program** (String | Path) - The current program name. - **cmdline.current_command_line** (List.of(String)) - The list of command-line arguments. - **cmdline.current_flag_string** (maybe(String)) - The flag string as written by the user. - **cmdline.current_containing_flag_string** (maybe(String)) - The containing flag string, providing more precise reporting for short-form flags. ### Request Example ```json { "cmdline.current_program": "my-script.rkt", "cmdline.current_command_line": ["--verbose", "-o", "output.txt"], "cmdline.current_flag_string": "-v", "cmdline.current_containing_flag_string": "-vv" } ``` ### Response Example ```json { "status": "success", "message": "Command line parameters updated." } ``` ``` -------------------------------- ### Getting Map Length in Racket Source: https://docs.racket-lang.org/rhombus/-reference/Maps Shows how to get the number of key-value pairs in a map using the Map.length method in Racket. This applies to both explicit map literals and maps created with constructors. ```racket > | > Map.length({"a": 1, "b": 2}) > --- > 2 > | > Map.length({}) > --- > 0 > | > {"a": 1, "b": 2}.length() > --- > 2 > | > {}.length() > --- > 0 ``` -------------------------------- ### Print Strings and Values in Rhombus Source: https://docs.racket-lang.org/rhombus/print Demonstrates how to print strings and other values using the `print` and `show` functions in Rhombus. It covers default behavior, explicit mode usage, and multi-argument printing with spacing and newlines. ```rhombus #lang rhombus "Hello, World!" ``` ```rhombus "Hello, World!" ``` ```rhombus print("Hello, World!") ``` ```rhombus print("Hello, World!", ~mode: #'expr) ``` ```rhombus show("Hello, World!") ``` ```rhombus print("apple") ``` ```rhombus print(["apple", "banana", "cherry"]) ``` ```rhombus block: print("hello", "there", "world") print("next") ``` ```rhombus block: println("hello", "there", "world") print("next") ``` -------------------------------- ### Running Rhombus Test Submodule from Command Line Source: https://docs.racket-lang.org/rhombus/main-submod Illustrates how to execute the 'test' submodule of a Rhombus program ('prog.rhm') directly from the command line using the 'rhombus' executable. This is useful for running unit tests during development without deploying the main program. ```shell rhombus prog.rhm'!'test ``` -------------------------------- ### Racket Array Get Method (Element Access) Source: https://docs.racket-lang.org/rhombus/-reference/Arrays The `get(n)` method retrieves the element at the specified index `n` (0-based) from an array. It is equivalent to array indexing `arr[n]`. ```Racket method (arr :: Array).get(n :: NonnegInt) :: Any.like_element(arr) Array("a", "b", "c").get(1) ``` ```Racket Array("a", "b", "c")[1] ``` -------------------------------- ### Example of Shrubbery Input Reading in Rhombus Source: https://docs.racket-lang.org/rhombus/-reference/Shrubbery Demonstrates how to use the 'shrubbery.read' function to parse a string containing a simple function definition. It imports the 'rhombus/shrubbery' module and then calls 'read' with a string input, showing the resulting parsed syntax. ```racket import rhombus/shrubbery shrubbery.read(Port.Input.open_string("fun (x):\n x + 1")) ``` -------------------------------- ### Racket: Block Syntax Class for Full Content Matching Source: https://docs.racket-lang.org/rhombus/syntax Demonstrates the use of the Block syntax class in Racket to match the entire content block, preserving its source location and raw text, and binding it as a single term. ```racket > | def 'thunk: $(body :: Block)' = thunk_form > --- > | > 'fun () $body' > --- > 'fun (): def x = 1 x + 1' ``` -------------------------------- ### Racket Function as Entry Point and Immediate Callee Source: https://docs.racket-lang.org/rhombus/-reference/ref-function Explains the syntactic roles of 'fun' bindings as entry points and immediate callees in Racket. Entry points allow functions to be used in contexts expecting a function value, while immediate callees improve static information propagation, for example, with the '|>' operator. ```Racket // Entry point example: // constructor ... (entry_point_fun ...) // Immediate callee example: // form |> immediate_callee_fun(...) ``` -------------------------------- ### Canonicalize Range (Racket) Source: https://docs.racket-lang.org/rhombus/-reference/Ranges Converts a range to its canonical form for integers. This ensures the range is represented as start..end, start.., ..end, or ... It returns the range unchanged if already in canonical form. ```racket method (rge :: Range).canonicalize() :: Range --- Returns the canonical form of rge with respect to the discrete domain of integers. > | > (1..5).canonicalize() > --- > 1 .. 5 > | > (1..).canonicalize() > --- > 1 .. > | > (..5).canonicalize() > --- > .. 5 > | > (..).canonicalize() > --- > .. > | > (1..=5).canonicalize() > --- > 1 .. 6 > | > (..=5).canonicalize() > --- > .. 6 > | > (1 <.. 5).canonicalize() > --- > 2 .. 5 > | > (1 <..).canonicalize() > --- > 2 .. > | > (1 <..= 5).canonicalize() > --- > 2 .. 6 ``` -------------------------------- ### Racket Class and Field Documentation Example Source: https://docs.racket-lang.org/rhombus/-reference/doc_notation This snippet illustrates how a Racket class named 'Lure' with fields 'weight' and 'color' would be documented. It shows the syntax for defining class arguments and field-accessor functions. ```racket class Lure(weight :: Number, color :: String) ``` -------------------------------- ### Racket Rhombus Arity Mismatch Examples Source: https://docs.racket-lang.org/rhombus/-reference/Matching Provides examples of runtime errors resulting from arity mismatches, where the number of values returned by the target expression does not match the expected number of values in the match clauses or '~else' clause. ```racket > match 1: --- ~arity: 2 | ~else: "two values" result arity mismatch; expected number of values not received expected: 2 received: 1 ... > match values(1, 2) --- | ~else: "one value" result arity mismatch; expected number of values not received expected: 1 received: 2 ... ``` -------------------------------- ### Rhombus Command Line Parsing Source: https://docs.racket-lang.org/rhombus/-reference/path Documentation for parsing command-line arguments within Rhombus. ```APIDOC ## Rhombus Command Line Parsing API ### Description Provides functionality for parsing command-line arguments. ### Methods and Functions - **Command Line Parsing**: Functions for processing arguments passed to the script or application. *(Note: Specific parsing functions are implied but not explicitly detailed in the provided text.)* ``` -------------------------------- ### Racket Example: Arithmetic Syntax Class Source: https://docs.racket-lang.org/rhombus/-reference/Syntax_Classes Demonstrates a Racket syntax class for arithmetic expressions, including macro definitions for doubling operands and adding one to an expression. This showcases basic pattern matching and macro expansion within syntax classes. ```racket > | > meta syntax_class Arithmetic > --- > | '$x + $y' > | '$x - $y' > | > expr.macro 'doubled_operands $(a :: Arithmetic)': > --- > '$a.x * 2 + $a.y * 2' > | > doubled_operands 3 + 5 > --- > 16 > | > expr.macro 'add_one_to_expression $(a :: Arithmetic)': > --- > '$a + 1' > | > add_one_to_expression 2 + 2 > --- > 5 ``` -------------------------------- ### Count Grapheme Clusters in Racket String Source: https://docs.racket-lang.org/rhombus/-reference/Strings Calculates the number of Unicode grapheme clusters within a specified range of a Racket string. It requires valid start and end indices, similar to `String.substring`. Returns 0 if start equals end. ```Racket String.grapheme_count(str :: ReadableString, start :: NonnegInt = 0, end :: NonnegInt = String.length(str)) :: NonnegInt ``` -------------------------------- ### Documenting Namespace Members in Rhombus Source: https://docs.racket-lang.org/rhombus/-reference/doc_notation Explains how to document members within a namespace, where the namespace is indicated in boldface. This example shows functions 'buy' and 'sell' belonging to the 'pet_store' namespace. ```Racket > function > --- > | fun pet_store.buy(pets :: List, n :: Number) :: Void > --- > function > | fun pet_store.sell() :: Number > --- ``` -------------------------------- ### Rhombus: Defining Classes with Keyword and Default Arguments Source: https://docs.racket-lang.org/rhombus/constructors Demonstrates defining a 'Posn' class with keyword fields '~x' and '~y', where '~y' has a default value. It shows examples of creating instances using keyword arguments and default values. ```Racket class Posn(~x: x, ~y: y = x) ``` ```Racket > Posn(~y: 2, ~x: 1) ``` ```Racket Posn(~x: 1, ~y: 2) ``` ```Racket > Posn(~x: 1) ``` ```Racket Posn(~x: 1, ~y: 1) ``` ```Racket > def Posn(~y: y1, ~x: x1) = Posn(~x: 1, ~y: 2) ``` ```Racket > y1 ``` ```Racket 2 ``` -------------------------------- ### Racket Rhombus Efficient Case Dispatch Source: https://docs.racket-lang.org/rhombus/-reference/Matching Explains and demonstrates how 'match' can optimize matching for clauses starting with literal-like patterns, enabling logarithmic time complexity instead of linear. ```racket > fun classify_efficiently(n): --- match n | 1: "one" | 2: "two" | 3 || 4: "some" | ~else: "more" ``` -------------------------------- ### Example Usage of annot.macro in Rhombus Source: https://docs.racket-lang.org/rhombus/-meta/Annotation_Macros Demonstrates the usage of 'annot.macro' with a 'two_of' annotation. It shows how the macro matches lists of two elements and checks if they satisfy the specified annotation type. Examples include successful matches and cases where the value does not satisfy the annotation. ```racket > | > annot.macro 'two_of($ann)': > --- > 'matching(List(_ :: $ann, _ :: $ann))' > | > [1, 2] :: two_of(Number) > --- > [1, 2] > | > [1, 2, 3] :: two_of(Number) > --- > ::: value does not satisfy annotation > value: [1, 2, 3] > annotation: two_of(Number) > | > [1, "x"] :: two_of(Number) > --- > ::: value does not satisfy annotation > value: [1, "x"] > annotation: two_of(Number) ``` -------------------------------- ### Box Creation and Representation in Racket Source: https://docs.racket-lang.org/rhombus/-reference/Boxes Demonstrates the basic creation of a box with an initial value and how the box object is represented. ```Racket def b = Box(1) b b.value ``` -------------------------------- ### Racket: Example using assign_meta.AssignParsed with expr.macro Source: https://docs.racket-lang.org/rhombus/-meta/Assignment_Macros This example demonstrates using the 'assign_meta.AssignParsed' syntax class within 'expr.macro' to handle custom assignment to a mutable list. It defines how to access and modify elements of 'reflist' using a custom operator and verifies the results. ```Racket expr.macro 'refcar $(a :: assign_meta.AssignParsed( 'fun () : List.first(reflist)', 'fun (v): reflist := [v]', 'refelem' )) $()': values(a, '$a.tail ...') ``` -------------------------------- ### Port File Operations API Source: https://docs.racket-lang.org/rhombus/-reference/Ports APIs for opening and managing input/output files and ports. ```APIDOC ## Port.open_input_output_file ### Description Opens a file for both input and output, returning connected input and output ports that share the underlying file descriptor. This is intended for special devices; for regular files, separate open calls are recommended. ### Method `Port.open_input_output_file` ### Parameters #### Path Parameters - **path** (PathString) - Required - The path to the file. #### Query Parameters - **~exists** (Port.Output.ExistsMode) - Optional - How to handle existing files (e.g., `'error`). Defaults to `#'error`. - **~mode** (Port.Mode) - Optional - The mode for opening the port (e.g., `'binary`). Defaults to `#'binary`. - **~permissions** (integer) - Optional - File permissions (0-65535). Defaults to `0o666`. - **~replace_permissions** (boolean) - Optional - Whether to replace existing permissions. Defaults to `#false`. ### Request Example ```json { "path": "/path/to/file.txt", "~exists": "#create", "~mode": "#text" } ``` ### Response #### Success Response (200) - **input_port** (Port.Input) - The input port. - **output_port** (Port.Output) - The output port. #### Response Example ```json { "input_port": "", "output_port": "" } ``` ``` -------------------------------- ### Rhombus Unit Testing: Output and Exception Handling (~prints_like, ~matches, ~throws) Source: https://docs.racket-lang.org/rhombus/-reference/Unit_Testing Illustrates advanced unit testing scenarios in Rhombus, focusing on `~prints_like` for checking printed output format, `~matches` for verifying structured results, and `~throws` for asserting that specific exceptions are raised. These are crucial for testing code with side effects or error conditions. ```Racket | > check: --- [1+1, 1+2] ~matches [_ :: Int, ...] | > check: --- '$(1+1)' ~prints_like '2' | > check: --- 1+"a" ~throws "expected: Number" check: failed got: exception +: value does not satisfy annotation annotation: Number value: "a" expected: exception "expected: Number" ``` -------------------------------- ### String Input and Output Ports Source: https://docs.racket-lang.org/rhombus/port Demonstrates the creation and usage of string-based input and output ports. `Port.Output.open_string` creates a port that accumulates output into a string, retrievable with `get_string`. `Port.Input.open_string` creates a port that reads from an existing string. ```Rhombus def outp = Port.Output.open_string() outp.print("hello") outp.print(" ") outp.print("world") outp.get_string() def inp = Port.Input.open_string("λ") inp.read_byte() inp.read_byte() ```