### Hylo: Multi-line String Literal Example Source: https://docs.hylo-lang.org/language-tour/basic-types Demonstrates the usage of multi-line string literals in Hylo, enclosed in triple double quotes. It shows how leading newlines and indentation are handled. ```hylo public fun main() { let text = """ C'est un trou de verdure où chante une rivière Accrochant follement aux herbes des haillons D'argent; où le soleil, de la montagne fière, Luit: c'est un petit val qui mousse de rayons. """ print(text) } ``` -------------------------------- ### Hylo: 'Hello, World!' Program Source: https://docs.hylo-lang.org/language-tour/hello-world A basic 'Hello, World!' program in Hylo. It defines the required 'main' function as the entry point and uses the 'print' function to display a message to the console. The standard library offers functionalities for environment interaction, including accessing command-line arguments via 'Environment.arguments' and signaling exit status with 'exit(status:)'. ```hylo public fun main() { print("Hello, World!") } ``` -------------------------------- ### Hylo 'sink' parameter example for ownership transfer Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates the 'sink' parameter convention in Hylo, where ownership of a value is transferred to the function. The original value becomes inaccessible after the call. This example shows how a Vector2 can be modified and returned, escaping the callee's lifetime. ```hylo fun offset_sink(_ base: sink Vector2, by delta: Vector2) -> Vector2 { &base.x += delta.x &base.y += delta.y return base // OK; base escapes here! } fun main() { let v = (x: 1, y: 2) print(offset_sink(v, (x: 3, y: 5))) // prints (x: 4, y: 7) print(v) // <== error: v was consumed in the previous line } // to use v here, pass v.copy() to offset_sink. ``` -------------------------------- ### Hylo Sink Subscript Example Source: https://docs.hylo-lang.org/language-tour/subscripts Demonstrates a Hylo sink subscript named 'min' that returns the smaller of two yielded integer values. This is useful when the arguments are last used within the subscript. ```Hylo subscript min(_ x: yielded Int, _ y: yielded Int): Int { inout { if y > x { &x } else { &y } } sink { if y > x { x } else { y } } } public fun main() { let (x, y) = (1, 2) var z = min[x, y] // last use of both x and y &z += 2 print(z) // 3 } ``` -------------------------------- ### Hylo: Numeric Type Conversion Example Source: https://docs.hylo-lang.org/language-tour/basic-types Illustrates explicit type conversion between numeric types in Hylo. It shows how to convert an Int to a Float64 to perform a mixed-type multiplication, preventing a compile-time error. ```hylo public fun main() { let n = 3.2 let m = 8 print(n * Float64(m)) // 25.6 } ``` -------------------------------- ### Inout Binding Projection and Modification in Hylo Source: https://docs.hylo-lang.org/language-tour/bindings Shows how `inout` bindings are used to project and mutably modify parts of a value. The example demonstrates projecting the `x` coordinate of a point and modifying it through the `inout` binding `x`. ```hylo public fun main() { var point = (x: 0.0, y: 1.0) inout x = &point.x &x = 3.14 print(point) // (x: 3.14, y: 1.0) } ``` -------------------------------- ### Hylo Reduce Method with Closure Argument Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Shows how to use the 'reduce(into:_:)'' method with a closure in Hylo. The closure defines how elements of a collection are combined. This example calculates the sum of elements in an array. ```hylo fun combine(_ partial_result: inout Int, _ element: Int) { &partial_result += element } public fun main() { let sum = [1, 2, 3].reduce(into: 0, combine) print(sum) } ``` -------------------------------- ### Hylo 'set' parameter for initializing uninitialized values Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates the 'set' parameter convention in Hylo, which allows a function to initialize an uninitialized variable. The example shows `init_vector` setting the `x` and `y` components of a Vector2. Attempts to pass an already initialized variable result in a compile-time error. ```hylo fun init_vector(_ target: set Vector2, x: sink Float64, y: sink Float64) { target = (x: x, y: y) } public fun main() { var v: Vector2 init_vector(&v, x: 1.5, y: 2.5) print(v) // (x: 1.5, y: 2.5) init_vector(&v, x: 3, y: 7). // error: 'v' is initialized } ``` -------------------------------- ### Hylo Closure Declaration and Usage Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Illustrates the declaration and usage of closures in Hylo. Functions are first-class citizens and can be assigned to bindings. This example shows assigning a function to a binding and printing its type. ```hylo fun round(_ n: Float64, digits: Int) -> Float64 { let factor = 10.0 ^ Float64(digits) return (n * factor).round() / factor } public fun main() { let f = round(_:digits:) print(type(of: f)) // (_: Float64, digits: Int) -> Float64 } ``` -------------------------------- ### Binding Lifetime Demonstration in Hylo Source: https://docs.hylo-lang.org/language-tour/bindings Exemplifies the concept of binding lifetime in Hylo. The lifetime of a binding extends until its last use in an expression. This example shows the lifetimes of `weight` and `length` ending after their respective `print` calls. ```hylo public fun main() { let weight = 1.0 print(weight) // 1.0 let length = 2.0 print(length) // 2.0 } ``` -------------------------------- ### Hylo Inout Parameter Example Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates how to use `inout` parameters in Hylo for in-place modification of a Vector2. Arguments to `inout` parameters must be mutable and marked with an ampersand at the call site. Overlapping `inout` access is prohibited. ```hylo fun offset_inout(_ target: inout Vector2, by delta: Vector2) { &target.x += delta.x &target.y += delta.y } fun main() { var v = (x: 3, y: 4) // v is mutable. offset_inout(&v, by: (x: 1, y: 1)) // ampersand indicates mutation. } fun main() { var v = (x: 3, y: 4) offset_inout(&v, by: v) // error: overlapping `inout` access to `v`; // pass `v.copy()` as the second argument instead. } ``` -------------------------------- ### Hylo Closure with 'inout' Capture Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates an 'inout' capture in a Hylo closure. An 'inout' capture occurs when a closure accesses a binding mutably. This example uses 'for_each' to sum the elements of an array. ```hylo public fun main() { var sum = 0 let result = [1, 2, 3].for_each(fun(_ n) { &sum += n }) print(sum) // 6 } ``` -------------------------------- ### Hylo Computed Property Example Source: https://docs.hylo-lang.org/language-tour/subscripts Illustrates a Hylo computed property 'degrees' within the 'Angle' type. This property converts radians to degrees and allows setting the angle in degrees, demonstrating computed property syntax. ```Hylo type Angle { public var radians: Float64 public memberwise init public property degrees: Float64 { let { radians * 180.0 / Float64.pi() } inout { var d = radians * 180.0 / Float64.pi() yield &d radians = d * Float64.pi() / 180.0 } set { &radians = new_value * Float64.pi() / 180.0 } } } public fun main() { let angle = Angle(radians: Double.pi) print(angle.degrees) // 180.0 } ``` -------------------------------- ### Custom Scheduler for Concurrent Tasks in Hylo Source: https://docs.hylo-lang.org/language-tour/concurrency Shows how to use custom schedulers for `spawn` operations, allowing for specialized execution strategies beyond the default CPU-bound scheduler. This example illustrates using an I/O-optimized scheduler for reading files and switching back to the default scheduler. ```hylo let io_scheduler = ... let file_content = (spawn(scheduler: io_scheduler, read_from_file)).await() ... ``` ```hylo let io_scheduler = ... let file_content = (spawn(scheduler: io_scheduler, read_from_file)).await() default_scheduler().activate() // switching threads ... ``` -------------------------------- ### Hylo Temporary Destruction Example Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates the 'temporary destruction' capability of `inout` parameters in Hylo. The callee can deinitialize the parameter and reinitialize it before returning, as long as it's valid at function exit. This mirrors Rust's `drop` behavior. ```hylo fun offset_inout(_ v: inout Vector2, by delta: Vector2) { let temporary = v.copy() v.deinit() // `v` is not bound to any value here v = (x: temporary.x + delta.x, y: temporary.y + delta.y) } ``` -------------------------------- ### Hylo Closure with 'let' Capture Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Illustrates a 'let' capture in a Hylo closure. A 'let' capture occurs when a closure accesses a binding immutably. This example uses 'map' to add an offset value to each element of an array. ```hylo public fun main() { let offset = 2 let result = [1, 2, 3].map(fun(_ n) { n + offset }) print(result) // [3, 4, 5] } ``` -------------------------------- ### Hylo 'set' Subscript for Assignment Operations Source: https://docs.hylo-lang.org/language-tour/subscripts Introduces the 'set' subscript in Hylo, used when the projected value is not needed but only assigned. This example demonstrates assigning a new value using the 'set' variant of the 'min' subscript. ```hylo subscript min(_ x: yielded Int, _ y: yielded Int): Int { inout { if y > x { &x } else { &y } } set { if y > x { &x = new_value } else { &y = new_value } } } public fun main() { var (x, y) = (1, 2) min[&x, &y] = 3 print(min[x, y]) // 2 } ``` -------------------------------- ### Hylo 'yielded' Subscript for Flexible Parameter Types Source: https://docs.hylo-lang.org/language-tour/subscripts Explains the 'yielded' keyword in Hylo subscripts, allowing parameters to be treated as 'let', 'inout', or 'sink' based on usage. This example synthesizes an immutable variant from a mutable 'inout' subscript. ```hylo subscript min(_ x: yielded Int, _ y: yielded Int): Int { inout { if y > x { &x } else { &y } } } public fun main() { let (x, y) = (1, 2) print(min[x, y]) // 1 } ``` -------------------------------- ### Consuming Operations and Lifetime Errors in Hylo Source: https://docs.hylo-lang.org/language-tour/bindings Illustrates consuming operations in Hylo, where a binding's lifetime is forcibly ended. Assigning to a `var` or initializing tuple elements are consuming operations. The example shows errors occurring when bindings (`weight`, `base_length`) are used after being consumed. ```hylo public fun main() { let weight = 1.0 let base_length = 2.0 var length = base_length // <----------------------------------------------------+ &length += 3.0 // | let measurements = ( // | w: weight, // <-----------------------------------------------+ | l: length) // | | print(weight) // error: `weight` used after being consumed here -+ | // | print(base_length) // error: `base_length` used after being consumed here -+ } ``` -------------------------------- ### Define Hylo Structure with Public Static Immutable Property Source: https://docs.hylo-lang.org/language-tour/basic-types This example illustrates defining a public, static, and immutable property 'zero' within the 'Matrix3' structure. Static properties are associated with the type itself, not instances, and are always immutable. ```hylo type Matrix3 { // ... public static let zero = Matrix3(components: [ [0, 0, 0], [0, 0, 0], [0, 0, 0], ]) } public fun main() { print(Matrix3.zero) } ``` -------------------------------- ### Anonymous Hylo Member Subscript for Element Access Source: https://docs.hylo-lang.org/language-tour/subscripts Defines an anonymous member subscript in 'Matrix3' to access individual elements using row and column indices. This example shows calling the anonymous subscript directly on the object. ```hylo type Matrix3 { public var components: Float64[3][3] public memberwise init public subscript(row: Int, col: Int): Float64 { components[row][col] } } public fun main() { var m = Matrix3(components: [ [1 ,4, 7], [2 ,5, 8], [3 ,6, 9], ]) print(m[row: 1, col: 1]) // 5.0 } ``` -------------------------------- ### Get HTTP Request from Connection in Hylo Source: https://docs.hylo-lang.org/language-tour/concurrency This function reads data from an HTTP connection, parses it into an HttpRequest, and manages scheduler activation for network I/O and main processing. It utilizes a MemBuffer for reading data in chunks and a HttpRequestParser. The operation might be asynchronous. ```hylo fun get_request(_ connection: inout HttpConnection) throws: HttpRequest { // Do the reading on the network I/O scheduler. net_scheduler.activate() // Read the incoming data in chunks, and parse the request while doing it. var parser: HttpRequestParser var buffer = MemBuffer(1024*1024) while !parser.is_complete { let n = connection.read(to: &buffer) // may be an async operation &parser.parse_packet(buffer, of_size: n) } // Done reading; switch now to main scheduler. main_scheduler.activate() return parser.request } ``` -------------------------------- ### Hylo Closure with 'sink' Capture Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Shows a 'sink' capture in a Hylo closure. A 'sink' capture is used when a closure acts as a sink for a value at its declaration, allowing it to maintain state across calls. This example creates a counter that returns incrementing integers. ```hylo public fun main() { var counter = fun[var i = 0]() inout -> Int { defer { &i += 1 } return i.copy() } print(&counter()) // 0 print(&counter()) // 1 } ``` -------------------------------- ### C++ Inout Parameter Equivalent Source: https://docs.hylo-lang.org/language-tour/functions-and-methods This C++ code shows a function `offset_inout` that modifies a `Vector2` passed by reference. Unlike Hylo, C++ does not provide static guarantees against data races or overlapping mutable access, as demonstrated by the `double_offset_inout` example. ```cpp void offset_inout(Vector2& target, Vector2 const& delta) { target.x += delta.x; target.y += delta.y; } // Offsets target by 2*delta. void double_offset_inout(Vector2& target, Vector2 const& delta) { offset_inout(target, delta); offset_inout(target, delta); } void main() { Vector2 v = {3, 4}; double_offset_inout(v, v); print(v); // Should print {9, 12}, but prints {12, 16} instead. } ``` -------------------------------- ### HyloLang: Basic `let` parameter function Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates the syntax for a function using `let` parameters in HyloLang. `let` is the default convention and implies immutability. ```hylo fun offset_let(_ v: let Vector2, by delta: let Vector2) -> Vector2 { (x: v.x + delta.x, y: v.y + delta.y) } ``` -------------------------------- ### Hylo: Basic Concurrent 'Hello World' with Spawn and Await Source: https://docs.hylo-lang.org/language-tour/concurrency Demonstrates a simple concurrent execution in Hylo. The `spawn` function creates a new thread to execute a closure, and `await` synchronizes the main thread with the spawned thread's completion. This is useful for offloading tasks to background threads. ```hylo fun main() { var handle = spawn(() => print("Hello, concurrent world!")) // do some other things handle.await() } ``` -------------------------------- ### Hylo: Calling different method bundle variants Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates calling variants of a Hylo method bundle based on the call site context (mutation, reuse, or sink). ```hylo public fun main() { let unit_x = Vector2(x: 1.0, y: 0.0) var v1 = Vector2(x: 1.5, y: 2.5) &v1.offset(by: unit_x) // 1. inout print(v1.offset(by: unit_x)) // 2. let let v2 = v1.offset(by: unit_x) // 3. sink print(v2) } ``` -------------------------------- ### C++ equivalent of Hylo 'set' parameter using placement new Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Illustrates a C++ approach similar to Hylo's 'set' parameter, using the placement new operator. This allows constructing a `Vector2` object within pre-allocated uninitialized storage, effectively initializing it. ```cpp #include void init_vector(Vector2* v, double x, double y) { new(v) Vector2(components[0], components[1]); } int main() { alignas(Vector2) char _storage[sizeof(Vector2)]; auto v1 = static_cast(static_cast(_storage)); init_vector(v1, 1.5, 2.5); std::cout << *v1 << std::endl; } ``` -------------------------------- ### Hylo: Method bundle with 'let', 'inout', and 'sink' variants Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Defines a Hylo method bundle 'offset' for 'Vector2' that includes implementations for 'let', 'inout', and 'sink' receiver passing conventions. ```hylo type Vector2 { public var x: Float64 public var y: Float64 public memberwise init public fun offset(by delta: Vector2) -> Vector2 { let { Vector2(x: x + delta.x, y: y + delta.y) } inout { &x += delta.x &y += delta.y } sink { &x += delta.x &y += delta.y return self } } } ``` -------------------------------- ### Hylo: Synthesizing method bundle variants Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Shows how Hylo can synthesize 'inout' and 'sink' variants of a method bundle from a single 'let' implementation, reducing code duplication. ```hylo type Vector2 { // ... public fun offset(by delta: Vector2) -> Vector2 { let { Vector2(x: x + delta.x, y: y + delta.y) } } } ``` -------------------------------- ### Hylo 'sink' and 'inout' parameter relationship Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Shows how Hylo's 'sink' and 'inout' parameter conventions can be implemented in terms of each other. This highlights the flexibility and interconnectedness of these parameter passing mechanisms. ```hylo fun offset_sink2(_ v: sink Vector2, by delta: Vector2) -> Vector2 { offset_inout(&v, by: delta) return v } fun offset_inout2(_ v: inout Vector2, by delta: Vector2) { v = offset_sink(v, by: delta) } ``` -------------------------------- ### Compile Hylo Module from a Subdirectory Source: https://docs.hylo-lang.org/language-tour/modules Shows how to compile a Hylo module when its source files are organized within a subdirectory. This simplifies project structure by grouping related files. The compiler command specifies the directory containing the source files. ```bash hc Sources -o hello ``` -------------------------------- ### Rust: Equivalent function to HyloLang's `let` parameter Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Presents a Rust implementation of the `offset_let` function using immutable borrows, comparing its guarantees to HyloLang's `let` parameters. ```rust fn offset_let(v: &Vector2, delta: &Vector2) -> Vector2 { Vector2 { x: v.x + delta.x, y: v.y + delta.y } } ``` -------------------------------- ### Bundled Hylo Subscripts for 'let' and 'inout' Behavior Source: https://docs.hylo-lang.org/language-tour/subscripts Shows how to bundle multiple implementations of a subscript, specifically providing distinct logic for 'let' (immutable) and 'inout' (mutable) parameter bindings within the same subscript definition. ```hylo subscript min(_ x: yielded Int, _ y: yielded Int): Int { let { if y > x { x } else { y } } inout { if y > x { &x } else { &y } } } ``` -------------------------------- ### Compile Multiple Hylo Files into a Single Module Source: https://docs.hylo-lang.org/language-tour/modules Demonstrates how to compile multiple Hylo source files into a single executable module. This is useful when related functions are spread across different files but belong to the same logical module. The command takes file paths as arguments and outputs an executable. ```hylo // In `Hello.hylo` public fun main() { greet("World") } // In `Greet.hylo` fun greet(_ name: String) { print("Hello, ${name}!") } ``` ```bash hc Hello.hylo Greet.hylo -o hello ./hello ``` -------------------------------- ### HyloLang: `let` parameter ownership and return limitations Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates that `let` parameters cannot be returned directly without copying, as ownership is not transferred in HyloLang. ```hylo fun duplicate(_ v: Vector2) -> Vector2 { v // error: `v` cannot escape; return `v.copy()` instead. } ``` -------------------------------- ### C++: Equivalent function to HyloLang's `let` parameter Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Provides a C++ equivalent of the HyloLang `offset_let` function using pass-by-const-reference, highlighting potential data race issues. ```cpp Vector2 offset_let(Vector2 const& v, Vector2 const& delta) { return Vector2 { v.x + delta.x, v.y + delta.y }; } ``` -------------------------------- ### Compile Multiple Hylo Modules with Imports Source: https://docs.hylo-lang.org/language-tour/modules Illustrates compiling a Hylo program composed of multiple modules, where one module imports functionality from another. This requires specifying each module's source directory. Public functions from imported modules become accessible. ```hylo // In `Sources/Hello/Hello.hylo` import Greetings public fun main() { greet("World") } // In `Sources/Greetings/Greetings.hylo` public fun greet(_ name: String) { print("Hello, ${name}!") } ``` ```bash hc --modules Sources/Hello Sources/Greetings -o hello ./hello ``` -------------------------------- ### Initialize Buffer with Initializer Function in Hylo Source: https://docs.hylo-lang.org/language-tour/basic-types Shows how to create a buffer of a specific type and size using an initializer function that determines the value of each element based on its index. The `Buffer.init(_:)` method is used here. ```hylo typealias Point = {x: Float64, y: Float64} public fun main() { var triangle = Point[3](fun(i) { (x: Float64(i), y: 0.0) }) // <== HERE &triangle[1].y = 2.5 print(triangle[1]) // (x: 1.0, y: 2.5) } ``` -------------------------------- ### Create and Access Buffer Elements in Hylo Source: https://docs.hylo-lang.org/language-tour/basic-types Demonstrates the creation of a buffer (fixed-size homogeneous collection) using a literal expression and accessing its elements by index. Buffers are enclosed in square brackets. ```hylo public fun main() { let triangle = [ (x: 0.0, y: 0.0), (x: 1.0, y: 0.0), (x: 0.0, y: 1.0), ] print(triangle[1]) // (x: 1.0, y: 0.0) } ``` -------------------------------- ### HyloLang: `let` parameter immutability enforcement Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Illustrates how HyloLang enforces immutability for `let` parameters, showing an error when attempting to modify them directly. ```hylo fun offset_let(_ v: Vector2, by delta: Vector2) -> Vector2 { &v.x += delta.x // Error: v is immutable &v.y += delta.y return v } ``` -------------------------------- ### Bulk Execution of Functions in Hylo Source: https://docs.hylo-lang.org/language-tour/concurrency Demonstrates how to spawn multiple instances of a function to run concurrently. The `spawn` function with the `bulk` argument allows for creating a specified number of concurrent executions of a given function. The `await` call ensures all spawned computations complete. ```hylo fun greet(_ index: Int) { print("Hello, from thread ${index}") } fun main() { let handle = spawn(bulk: 19, greet) handle.await() } ``` -------------------------------- ### Hylo: Concurrent Function Execution with Thread Inversion Source: https://docs.hylo-lang.org/language-tour/concurrency Illustrates a more complex concurrent scenario in Hylo, showcasing how functions can be spawned for concurrent execution and how `await` handles results and potential 'thread inversion'. This pattern allows the calling thread to be returned to a pool, improving resource utilization. ```hylo fun do_greet(): Int { print("Hello, concurrent world!") return 17 } fun prime_number(): Int { 13 } fun concurrent_greeting() { var handle = spawn(do_greet) let x = prime_number() let y = handle.await() // switching threads return x + y } fun main() { print(concurrent_greeting()) } ``` -------------------------------- ### Declare and Use a Basic Hylo Subscript Source: https://docs.hylo-lang.org/language-tour/subscripts Demonstrates the declaration of a basic subscript 'min' which finds the smaller of two integers. It highlights the syntax for subscript definition and invocation using square brackets. ```hylo subscript min(_ x: Int, _ y: Int): Int { if x > y { y } else { x } } public fun main() { let one = 1 let two = 2 print(min[one, two]) // 1 } ``` -------------------------------- ### Hylo: Calling a method on a type instance Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Illustrates how to call a method on an instance of a type in Hylo using dot notation. The instance is implicitly passed as the 'self' parameter. ```hylo public fun main() { let unit_x = Vector2(x: 1.0, y: 0.0) let v1 = Vector2(x: 1.5, y: 2.5) let v2 = v1.offset_let(by: unit_x) // <== HERE print(v2) } ``` -------------------------------- ### HyloLang: Modifying a copy of a `let` parameter Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Shows how to work around `let` parameter immutability by creating a mutable copy within the function body in HyloLang. ```hylo fun offset_let(_ v: Vector2, by delta: Vector2) -> Vector2 { var temporary = v.copy() &temporary.x += delta.x &temporary.y += delta.y return temporary } ``` -------------------------------- ### Create and Print a Tuple in Hylo Source: https://docs.hylo-lang.org/language-tour/basic-types Demonstrates how to create a tuple with labeled elements and nested tuples, and then print its contents. Tuples are comma-separated values enclosed in parentheses. ```hylo public fun main() { let circle = (origin: (x: 6.3, y: 1.0), radius: 2.3) print(circle) } ``` -------------------------------- ### Create and Print a Slice from a Collection in Hylo Source: https://docs.hylo-lang.org/language-tour/basic-types Demonstrates creating a slice from a collection (in this case, a buffer literal) by specifying a range of indices. Slices provide read and write access to a sub-part of a collection. ```hylo public fun main() { let numbers = [0, 1, 2, 3, 4] print(numbers[2 ..< 4]) // [2, 3] } ``` -------------------------------- ### Hylo: Calling a mutating method Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Illustrates calling a mutating Hylo method using the ampersand ('&') prefix on the receiver to indicate mutation. ```hylo fun main() { var y = Vector2(x: 3, y: 4) &y.offset_inout(by: Vector2(x: 7, y: 11)) // <== HERE print(y) } ``` -------------------------------- ### Hylo: Boolean Type Declaration and Usage Source: https://docs.hylo-lang.org/language-tour/basic-types Demonstrates the declaration and usage of the Boolean type in Hylo. It shows how a comparison operation results in a Bool value and how to print its type. ```hylo public fun main() { let is_two_greater_than_one = 2 > 1 print(type(of: is_two_greater_than_one)) // Bool } ``` -------------------------------- ### Instantiate and Modify Hylo Structure Instance Source: https://docs.hylo-lang.org/language-tour/basic-types This code demonstrates how to instantiate the 'Matrix3' structure using its memberwise initializer and then modify its mutable properties. It highlights that modifying a property requires both the instance binding to be mutable and the property itself to be declared with 'var'. ```hylo type Matrix3 { public var components: Float64[3][3] public memberwise init } public fun main() { var m = Matrix3(components: [ [0, 0, 0], [0, 0, 0], [0, 0, 0], ]) &m.components[0][0] = 1.0 &m.components[1][1] = 1.0 &m.components[2][2] = 1.0 print(m) } ``` -------------------------------- ### Hylo: Type Inference with Literal Assignment Source: https://docs.hylo-lang.org/language-tour/basic-types Shows how Hylo's compiler infers the type of numeric literals based on the variable's declaration context. Demonstrates in-place mutation of a Float64 variable. ```hylo public fun main() { var n: Float64 = 2 &n *= 10 print(n) // prints 20.0 } ``` -------------------------------- ### Hylo Member Subscript for Type Access Source: https://docs.hylo-lang.org/language-tour/subscripts Illustrates a member subscript within a 'Matrix3' type that provides access to rows of the matrix components. It demonstrates how member subscripts implicitly receive a receiver parameter. ```hylo type Matrix3 { public var components: Float64[3][3] public memberwise init public subscript row(_ index: Int): Float64[3] { components[index] } } ``` -------------------------------- ### Hylo: Declaring a mutating method with 'inout' Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Shows how to declare a mutating Hylo method where the receiver is passed using the 'inout' convention, allowing modification of the instance. ```hylo type Vector2 { // ... public fun offset_inout(by delta: Vector2) inout -> Vector2 { &x += delta.x &y += delta.x } } ``` -------------------------------- ### Instrumented Hylo Subscript with Yield Statement Source: https://docs.hylo-lang.org/language-tour/subscripts Shows an instrumented 'min' subscript that includes 'yield' statements to explicitly control value projection and observe execution flow. This illustrates the requirement for a 'yield' on every execution path. ```hylo subscript min(_ x: Int, _ y: Int): Int { print("enter") yield if x > y { y } else { x } print("leave") } public fun main() { let one = 1 let two = 2 let z = min[one, two] // enter print(z) // 1 // leave } ``` -------------------------------- ### Rust equivalent of Hylo 'sink' parameter Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Presents a Rust function that mimics Hylo's 'sink' parameter using a move. The `base` Vector2 is passed by value, implying a move. If the source type is copyable, it's treated as assigning to a unique reference, forcing the move. ```rust fn offset_sink(base: Vector2, delta: &Vector2) -> Vector2 { base.x += delta.x base.y += delta.y return base } fn main() { let mut v: Vector2 = {1, 2}; let moveV = &mut v; println("{}", offset_sink(moveV, {3, 5})) } ``` -------------------------------- ### Hylo Function Overloading via Argument Labels Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Shows two 'scale' functions in Hylo that share a base name but differ in argument labels, enabling a form of overloading. One scales by a Vector2, the other by a scalar Float64. Argument labels are part of the function's full name. ```hylo typealias Vector2 = {x: Float64, y: Float64} fun scale(_ v: Vector2, by factor: Vector2) -> Vector2 { (x: v.x * factor.x, y: v.y * factor.y) } fun scale(_ v: Vector2, uniformly_by factor: Float64) -> Vector2 { (x: v.x * factor, y: v.y * factor) } ``` -------------------------------- ### Hylo: Mutable String In-place Modification Source: https://docs.hylo-lang.org/language-tour/basic-types Illustrates how to mutate a String in-place in Hylo using the `append` method. It shows the initial string and the result after appending text. ```hylo public fun main() { var text = "Hello, " &text.append("World!") // <=== HERE print(text) // Hello, World! } ``` -------------------------------- ### Concurrent Quick-Sort Implementation in Hylo Source: https://docs.hylo-lang.org/language-tour/concurrency A basic implementation of a quick-sort algorithm designed to utilize multicore systems. It partitions data and recursively sorts sub-arrays, with the option to spawn concurrent tasks for sorting. Sorting is done serially below a size threshold. ```hylo fun my_concurrent_sort(_ a: inout ArraySlice) { if a.count < size_threshold { // Use serial sort under a certain threshold. a.sort() } else { // Partition the data, such as elements [0, mid) < [mid] <= [mid+1, n). let mid = sort_partition(&a) inout (lhs, rhs) = &a.split(at: mid) &rhs.drop_first(1) // Spawn work to sort the right-hand side. let handle = spawn(() => my_concurrent_sort(&rhs)) // Execute the sorting on the left side, on the current thread. my_concurrent_sort(&lhs) // We are done when both sides are done. handle.await() } } fun sort_partition(_ a: inout ArraySlice): Int { let mid_value = median9(a) return a.partition(by: (val) => val > mid_value) } fun median9(_ a: inout ArraySlice) -> Element { ... } ``` -------------------------------- ### Rust Inout Parameter Equivalent Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Illustrates the `inout` parameter concept in Rust using mutable borrows (`&mut`). This provides similar safety guarantees to Hylo regarding exclusive access to data during modification, preventing data races. ```rust fn offset_inout(target: &mut Vector2, delta: &Vector2) { target.x += delta.x; target.y += delta.y; } ``` -------------------------------- ### C++ equivalent of Hylo 'sink' parameter Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Illustrates a C++ implementation analogous to Hylo's 'sink' parameter. It uses `std::move` to transfer ownership of the `base` Vector2, making it inaccessible in the caller after the function call, similar to Hylo's behavior. ```cpp Vector2 offset_sink(Vector2 base, Vector2 const& delta) { base.x += delta.x base.y += delta.y return base } int main() { Vector2 v = {1, 2}; print(offset_sink(std::move(v), {3, 5})); // prints (x: 4, y: 7) print(v); // prints garbage } ``` -------------------------------- ### Hylo Function with Explicit Return Statement Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates a Hylo function 'round' that performs calculations and uses an explicit 'return' statement to return a value. Non-Void functions require a 'return' statement for every execution path. ```hylo fun round(_ n: Float64, digits: Int) -> Float64 { let factor = 10.0 ^ Float64(digits) return (n * factor).round() / factor } ``` -------------------------------- ### Hylo 'inout' Subscript for Mutable Projection Source: https://docs.hylo-lang.org/language-tour/subscripts Demonstrates an 'inout' subscript 'min_inout' that modifies its parameters. It shows how to use the '&' operator for passing mutable references and performing in-place modifications. ```hylo subscript min_inout(_ x: inout Int, y: inout Int): Int { inout { if y > x { &x } else { &y } } } public fun main() { var (x, y) = (1, 2) &min_inout[&x, &y] += 2 print(x) // 3 } ``` -------------------------------- ### Destructure Tuple Elements to Local Bindings in Hylo Source: https://docs.hylo-lang.org/language-tour/basic-types Illustrates tuple destructuring to unpack elements into local variables, including ignoring irrelevant elements using an underscore. This process assigns tuple elements to named bindings. ```hylo public fun main() { let circle = (origin: (x: 6.3, y: 1.0), radius: 2.3) // Bind to px to circle.origin.x and r to circle.radius, // ignoring circle.origin.y let (origin: (x: px, y: _), radius: r) = circle print((px, r)) // (6.3, 2.3) } ``` -------------------------------- ### Append Elements to a Resizable Array in Hylo Source: https://docs.hylo-lang.org/language-tour/basic-types Illustrates the dynamic resizing capability of an array by appending elements to an initially empty array and printing its count after each addition. Arrays provide dynamic collection functionality. ```hylo typealias Point = {x: Float64, y: Float64} public fun main() { var points = Array() print(points.count()) // 0 &points.append((x: 6.3, y: 1.0)) // <== HERE print(points.count()) // 1 } ``` -------------------------------- ### Hylo Free Function Declaration and Usage Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates the declaration of a Hylo 'free function' named 'norm' to calculate the length of a 2D vector. It also shows the 'main' function calling 'norm' with a vector literal and printing the result. Return types can be omitted if they are 'Void'. ```hylo typealias Vector2 = {x: Float64, y: Float64} fun norm(_ v: Vector2) -> Float64 { Float64.sqrt(v.x * v.x + v.y * v.y) } public fun main() { let velocity = (x: 3.0, y: 4.0) print(norm(velocity)) // 5.0 } ``` -------------------------------- ### Hylo: Calling a method via the type with explicit 'self' Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates calling a Hylo method directly through its type, explicitly passing the receiver instance as the 'self' parameter. ```hylo let v2 = Vector2.offset_let(self: v1, by: unit_x) ``` -------------------------------- ### Hylo: Declare a method within a type Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates the declaration of a method 'offset_let' within the 'Vector2' type in Hylo. Methods operate on a receiver instance, represented by 'self'. ```hylo type Vector2 { public var x: Float64 public var y: Float64 public memberwise init public fun offset_let(by delta: Vector2) -> Vector2 { // <== HERE Vector2(x: self.x + delta.x, y: self.y + delta.y) } } ``` -------------------------------- ### Hylo: Stop Spawned Work Using Handle Source: https://docs.hylo-lang.org/language-tour/concurrency Demonstrates how to spawn a concurrent operation and later cancel it by calling `request_stop()` on the returned handle. This pattern is useful for managing background tasks that may need to be terminated early. The spawned function checks a `StopToken` to see if a stop has been requested. ```hylo let handle = spawn(fun(s: StopToken) { for i in 1... { if s.stop_requested() { break } print("working") sleep(seconds: 1) } }) // do some other work concurrently sleep(seconds: 3) // cancel the spawned work handle.request_stop() ``` -------------------------------- ### Hylo Inline Closure Expression for Reduce Source: https://docs.hylo-lang.org/language-tour/functions-and-methods Demonstrates using an inline closure expression in Hylo for the 'reduce(into:_:)'' method. This is a more concise way to define a closure when its sole purpose is to be used as an argument. ```hylo public fun main() { let sum = [1, 2, 3].reduce(into: 0, fun(_ partial_result, _ element) { &partial_result += element }) print(sum) } ``` -------------------------------- ### Mutable Binding Declaration and Modification in Hylo Source: https://docs.hylo-lang.org/language-tour/bindings Illustrates the declaration and modification of a mutable binding using `var`. Mutable bindings allow for reassignment of their values, as shown by the updated value of `length` after modification. ```hylo public fun main() { var length = 1 &length = 2 print(length) // 2 } ``` -------------------------------- ### Handle HTTP Request in Hylo Source: https://docs.hylo-lang.org/language-tour/concurrency This function processes an HttpRequest based on its path, returning an appropriate HttpResponse. It demonstrates switching between schedulers for different types of operations, including lengthy ones that might use multiple threads. It handles paths like '/isalive' and '/lengthy'. ```hylo fun handle_request(_ request: HttpRequest) throws { if request.path == "/isalive" { return OkResponse(content: "still breathing") } // Perform any processing on a different scheduler. processing_scheduler.activate() switch request.path { case "/isalive": return OkResponse(content: "still breathing") case "/lengthy": // May involve other, more specialized, schedulers. // Most probably will use multiple threads. return process_lengthy_operation(request) } // Get back to the main scheduler. main_scheduler.activate() } ``` -------------------------------- ### Immutable Binding Declaration in Hylo Source: https://docs.hylo-lang.org/language-tour/bindings Demonstrates the declaration of an immutable binding using `let`. Attempting to reassign a value to an immutable binding results in a compile-time error, ensuring the bound object remains unchanged. ```hylo public fun main() { let gravity = 9.81 &gravity = 11.2 // error: cannot assign, `gravity` is a `let` binding } ```