### Create and Populate Runtime-Sized Array in Vale Source: https://vale.dev/guide/collections This example shows how to create a runtime-sized array of integers with a capacity determined by user input. It populates the array by multiplying the index by 5 and then prints the elements. ```Vale import stdlib.*; import stdlib.math.*; import stdlib.stdin.*; exported func main() { n = stdinReadInt(); arr = []int(n); foreach i in range(0, n) { push(&arr, i * 5); } foreach i in range(0, n) { println(arr[i]); } } ``` -------------------------------- ### Create and Populate a List in Vale Source: https://vale.dev/guide/collections This snippet shows how to create an integer list and add elements to it using the `List` function and the `add` method. It then iterates through the list to print each element. ```Vale import stdlib.collections.list.*; exported func main() { l = List(); l.add(1); l.add(3); l.add(7); foreach x in l { println(x); } } ``` ```Vale import stdlib.collections.list.*; exported func main() { l = List().add(1).add(3).add(7); foreach x in l { println(x); } } ``` -------------------------------- ### Heap Allocation with Pointers in Vale Source: https://vale.dev/guide/references Illustrates how to place a struct on the heap using the `^` operator in Vale. This example shows creating a `Spaceship` instance on the heap and accessing its members. ```vale import stdlib.*; struct Spaceship { name str; numWings int; } exported func main() { ship = ^Spaceship("Enterprise", 4); println(ship.name); } ``` -------------------------------- ### While Loop Iteration with List Access in Vale Source: https://vale.dev/guide/collections Shows an alternative to `foreach` for iterating over a list using a `while` loop. It manually manages the index and accesses elements using `get()`, demonstrating control over the loop's progression. ```Vale import stdlib.*; import stdlib.collections.list.*; exported func main() { l = List().add(1).add(3).add(7); i = 0; while i < l.len() { x = l.get(i); println(i + ": " + x); set i = i + 1; } } ``` -------------------------------- ### Populate Runtime-Sized Array with Function in Vale Source: https://vale.dev/guide/collections Demonstrates creating a runtime-sized array with a specified capacity and populating it using a provided function (x => x * 5). The code reads the capacity from user input and prints the array elements. ```Vale import stdlib.*; import stdlib.math.*; import stdlib.stdin.*; exported func main() { n = stdinReadInt(); arr = [](n, x => x * 5); foreach i in range(0, n) { println(arr[i]); } } ``` -------------------------------- ### Interface Limitations Example in Go Source: https://vale.dev/guide/generics Demonstrates how using interfaces can lead to a loss of specific type information, preventing the use of type-specific methods. This example highlights the compile error when trying to call a method on a variable that is typed as an interface rather than its original concrete type. ```Go interface ISpaceship { func length(virtual this &ISpaceship) int; 0 func honk(virtual this &ISpaceship) void; } func longerShip( a &ISpaceship, b &ISpaceship) &ISpaceship { if (a.length() > b.length()) { return a; } else { return b; } } struct Raza { ... } func length(r &Raza) int { 4 } func honk(r &Raza) { ... } impl ISpaceship for Raza; struct Firefly { ... } func length(f &Firefly) int { 3 } func honk(f &Firefly) { ... } func crazyIvan(f &Firefly) { ... } exported func main() { flametail = Firefly(...); serenity = Firefly(...); ship = longerShip( &flametail, &serenity); // ship.crazyIvan(); // Compile error: ship is type // ISpaceship, not Firefly! } ``` -------------------------------- ### Vale Hello World Program Source: https://vale.dev/guide/introduction This snippet demonstrates the basic structure of a Vale program, including importing the standard library, defining an exported main function, and printing 'Hello world!' to the console. It's the foundational example for new Vale developers. ```vale import stdlib.*; exported func main() { println("Hello world!"); } ``` -------------------------------- ### Demonstrate Universal Function Call Syntax (UFCS) in Vale Source: https://vale.dev/guide/functions Shows how Vale treats functions and methods identically, using Universal Function Call Syntax (UFCS) for cleaner method chaining. This example uses string and collection utilities. ```vale import stdlib.*; import stdlib.stringutils.*; import stdlib.collections.*; func main() { s1 = "Hail Hydra!".split(" "); s2 = split("Hail Hydra!", " "); } ``` -------------------------------- ### Populate Static-Sized Array with Function in Vale Source: https://vale.dev/guide/collections This snippet demonstrates creating a static-sized array of 5 integers and populating it using a lambda function that doubles the index. It then iterates and prints the array elements. ```Vale import stdlib.*; exported func main() { arr = [#5](i => i * 2); foreach i in range(0, 5) { println(arr[i]); } } ``` -------------------------------- ### Vale Structs: Owning Reference Example Source: https://vale.dev/guide/references Demonstrates the concept of an owning reference in Vale. A struct has exactly one owning reference, and when this reference is no longer pointing to the struct, the struct is deallocated. This example shows the basic declaration and usage of a mutable struct with an owning reference. ```vale import stdlib.* struct Spaceship { name str; fuel int; } exported func main() { ship = Spaceship("Serenity", 2); // ship is an owning reference println(ship.name); // implicit (ship).drop() } ``` -------------------------------- ### Iterate Over an Integer Range in Vale Source: https://vale.dev/guide/collections Demonstrates how to use a `foreach` loop with the `range` function to iterate over a sequence of integers and print each number. This is a concise way to handle numerical loops. ```Vale import stdlib.*; import stdlib.math.*; exported func main() { foreach x in range(0, 3) { println(x); } } ``` -------------------------------- ### Generic Struct for Collections in Go Source: https://vale.dev/guide/generics Demonstrates the creation of generic structs in Go. This example defines a `Flock` struct that can hold a list of a specific, generic type `T`. This allows for type-safe collections, ensuring that a `Flock` can only contain `Firefly` objects. ```Go // Using above imports and // ISpaceship, Firefly, Raza struct Flock { ships List; } exported func main() { f = Flock(List()); f.ships.add(Firefly(...)); f.ships.add(Firefly(...)); firstShip = f.ships.get(0); // This works because the compiler // can see that firstShip is a // Firefly. firstShip.crazyIvan(); } ``` -------------------------------- ### Generic Function for Type-Safe Comparisons in Go Source: https://vale.dev/guide/generics Introduces generic functions in Go using type parameters. This example modifies the `longerShip` function to accept and return a generic type `T`, allowing it to work with any type that satisfies the `ISpaceship` interface while retaining the specific type information for method calls. ```Go interface ISpaceship { func length(virtual self &ISpaceship) int; func honk(virtual self &ISpaceship); } func longerShip ( a &T, b &T) &T { if (a.length() > b.length()) { return a; } else { return b; } } struct Raza { ... } impl ISpaceship for Raza; func length(r &Raza) int { 4 } func honk(r &Raza) { ... } struct Firefly { ... } func length(f &Firefly) int { 3 } func honk(f &Firefly) { ... } func crazyIvan(f &Firefly) { ... } impl ISpaceship for Firefly; exported func main() { flametail = Firefly(...); serenity = Firefly(...); ship = longerShip( &flametail, &serenity); // This works now! ship.crazyIvan(); } ``` -------------------------------- ### Vale Variable Declaration and Usage Source: https://vale.dev/guide/introduction This example illustrates how to declare and initialize a variable in Vale using the assignment operator (=). It then shows how to use this variable in conjunction with a string literal for output. This is fundamental for data handling in Vale programs. ```vale import stdlib.*; exported func main() { x = "world!"; println("Hello " + x); } ``` -------------------------------- ### Vale Mutexed Region Example Source: https://vale.dev/guide/regions Illustrates the use of mutexed regions in Vale for controlled access to shared data. The `makeGame` function creates a `Game` object, which is then wrapped in a `Mutex`. The example shows how to acquire read-only access (`rlock`) and read-write access (`rwlock`) to the game data, ensuring thread safety. Locks must be explicitly dropped. ```vale struct Game { bases List; ships List; } struct Base { ... } struct Ship { name str; from &Base; } func makeGame() Game { bases List = …; ships = List( Ship("Serenity", bases.0), Ship("Raza", bases.1)); return Game(bases, ships); } exported func main() { mutex = Mutex(a' makeGame()); // Open for reading roLock = mutex.rlock(); roGame = lock.root; println(roGame.ships.0.name); drop(roLock); // Open for writing rwLock = mutex.rwlock(); rwGame = lock.root; set rwGame.ships.0.from = rwGame.bases.0; drop(rwLock); } ``` -------------------------------- ### Iterate List with Index in Vale Source: https://vale.dev/guide/collections This snippet illustrates how to iterate over a list while also accessing the index of each element using the `entries()` function. It prints both the index and the element. ```Vale import stdlib.*; import stdlib.collections.list.*; exported func main() { l = List().add(1).add(3).add(7); foreach [i, x] in l.entries() { println(i + ": " + x); } } ``` -------------------------------- ### Indexing Tuples to Produce Variant Types Source: https://vale.dev/guide/structs Demonstrates accessing fields of a tuple using index notation, which results in a variant type. The example shows accessing an element which is a string, and notes that operations on such variants handle the underlying types appropriately. ```vale exported func main() { tup = (5, true, "V"); println("Saturn " + tup[1 + 1]); } ``` -------------------------------- ### Vale Borrow Reference: Function Argument Source: https://vale.dev/guide/references Shows how to create and use a borrow reference in Vale using the '&' symbol. A borrow reference asserts that the target object is live and temporarily 'tethers' it. This example passes a borrow reference of a 'Spaceship' to the 'foo' function. ```vale import stdlib.* struct Spaceship { name str; numWings int; } func foo(s &Spaceship) { println(s.name); } exported func main() { ship = Spaceship("Serenity", 2); foo(&ship); } ``` -------------------------------- ### Create a Non-Owning Reference (Lend) to a Struct Source: https://vale.dev/guide/structs Explains how to create a non-owning reference (a 'lend') to a mutable struct using the '&' symbol. The example shows an 'owningRef' and a 'nonOwningRef'. ```vale struct Spaceship { name str; fuel int; } exported func main() { owningRef = Spaceship("Serenity", 2); nonOwningRef = &owningRef; } ``` -------------------------------- ### Vale Static Typing with Explicit Declaration Source: https://vale.dev/guide/introduction This example demonstrates Vale's static typing system by explicitly declaring the type of a variable ('str'). It shows how to define a variable with a specific type and then use it in string concatenation, highlighting Vale's compile-time type checking. ```vale import stdlib.*; exported func main() { a str = "world!"; println("Hello " + a); } ``` -------------------------------- ### Generated Header for readInt Source: https://vale.dev/guide/externs This is an example of a generated header file that Vale creates for extern functions. It declares the C signature of the `mvtest_readInt` function, allowing the C compiler to verify the function signature used in the C implementation against what Vale expects, preventing signature mismatches. ```c extern ValeInt mvtest_readInt(); ``` -------------------------------- ### Destructuring Function Parameters in Vale Source: https://vale.dev/guide/patterns This example demonstrates using destructuring directly in function parameters to assign struct members to local variables within the function scope. It contrasts a traditional parameter approach with a destructuring approach. ```vale // Using above Vec3 // Without destructuring: func refuelA( vec Vec3, len int) Vec3 { Vec3( vec.x * len, vec.y * len, vec.z * len) } // With destructuring: func refuelB( Vec3[x, y, z], len int) Vec3 { Vec3(x * len, y * len, z * len) } ``` -------------------------------- ### Calling C's readInt from Vale Source: https://vale.dev/guide/externs This snippet shows a Vale program that calls an external C function `readInt` to get an integer input from the user and then prints it. It declares the external function signature in Vale and assumes the C implementation is provided separately. ```vale import stdlib.*; exported func main() { i = readInt(); println("User entered: " + i); } extern func readInt() int; ``` -------------------------------- ### Vale Pure Block Example Source: https://vale.dev/guide/regions Demonstrates a 'pure block' in Vale, which establishes a temporary pure region within a function. Inside a pure block, existing data cannot be mutated, but accesses to that data are free of overhead. This is useful for read-only operations on shared data without explicit locking. ```vale struct Ship { fuel int; } func addAndPrint(ships List) { ships.add(Ship(10)); pure block { foreach ship in ships { println(ship.fuel); } // Cannot ships.add(Ship(15)) here. } } ``` -------------------------------- ### Break Statement in Vale Loop Source: https://vale.dev/guide/collections Demonstrates the use of the `break` keyword within a `foreach` loop to terminate the loop prematurely. The loop stops once a specific condition (index equals 1) is met. ```Vale import stdlib.*; import stdlib.collections.list.*; exported func main() { l = List().add(1).add(3).add(7); foreach [i, x] in l.entries() { println(i + ": " + x); if i == 1 { break; } } } ``` -------------------------------- ### Using Weak References in Vale Source: https://vale.dev/guide/references Demonstrates how to create and use weak references in Vale. A weak reference is set to null when the object it points to is destroyed. The `lock` function is used to attempt to get a borrow reference from a weak reference. ```vale import stdlib.*; weakable struct Base { name str; } struct Spaceship { name str; origin &&Base; } func printShipBase(ship &Spaceship) { maybeOrigin = lock(ship.origin); 45 if (not maybeOrigin.isEmpty()) { 6 o = maybeOrigin.get(); println("Ship base: " + o.name); } else { println("Ship base unknown!"); } } exported func main() { base = Base("Zion"); ship = Spaceship("Neb", &&base); printShipBase(&ship); (base).drop(); // Destroys base. printShipBase(&ship); } ``` -------------------------------- ### Vale: Moving Owning Reference to a Function Source: https://vale.dev/guide/references Demonstrates how an owning reference is moved when passed as an argument to a function. The ownership transfers to the function's parameter, invalidating the original variable. This example passes a 'Spaceship' struct to the 'foo' function. ```vale import stdlib.* struct Spaceship { name str; } func foo(b Spaceship) { println(b.name); } exported func main() { a = Spaceship("Raza"); foo(a); // Move a into foo's b // Can't use a now. } ``` -------------------------------- ### Vale: Moving Owning Reference Between Locals Source: https://vale.dev/guide/references Explains the 'move' operation in Vale, where an owning reference can be transferred from one local variable to another. After a move, the original local is invalidated and cannot be used. This example moves a 'Spaceship' struct from 'a' to 'b'. ```vale struct Spaceship {} exported func main() { a = Spaceship(); 2 b = a; // Move the ship from a to b. // b now owns the Spaceship. // Can't use a now. } ``` -------------------------------- ### Vale Read-Only Region Example Source: https://vale.dev/guide/regions Demonstrates a read-only region in Vale. The `biggestShipName` function takes a list of ships from a read-only region 'a', preventing modifications to the original data. This allows the compiler to perform aggressive optimizations. The `main` function initializes ships and calls `biggestShipName`, printing the result. ```vale struct Ship { name str; size int; } func biggestShipName( ships &a'List) str { biggest = ships.0; foreach ship in ships { if (ship.size > biggest.size) { set biggest = ship; } } return biggest.name; } exported func main() { allShips = List( Ship("Serenity", 9), Ship("Raza", 7)); n = biggestShipName(allShips); println(n); } ``` -------------------------------- ### Vale Immutable Structs: Multiple Owning References Source: https://vale.dev/guide/references Illustrates how immutable structs in Vale can have multiple owning references. Unlike mutable structs, immutable ones allow multiple references to coexist and be used independently. This example declares an immutable struct 'Vec3' and shows two references pointing to it. ```vale import stdlib.* struct Vec3 imm { x int; y int; z int; } exported func main() { firstRef = Vec3(3, 4, 5); otherRef = &firstRef; // Can use both freely. println(firstRef.x + otherRef.y); } ``` -------------------------------- ### Import and Use External Library in Vale Source: https://vale.dev/guide/modules Demonstrates how to import and use an external Vale library. This involves cloning the library, adding its source to the build command, and using the import statement in the code. ```vale import simpleterrain.* exported func main() { my_terrain = MakeSimpleTerrain(1337, 40, 16); my_terrain.display(); } ``` -------------------------------- ### Define and Use a Simple Function in Vale Source: https://vale.dev/guide/functions Demonstrates defining a basic function that adds two to its integer argument and calling it. It also shows the optional expression return syntax. This function is written in Vale. ```vale import stdlib.*; func add2(x int) int { return x + 2; } func main() { println("Half-Life " + add2(1)); } ``` ```vale func add2(x int) int { x + 2 } ``` -------------------------------- ### Build Module with Single File Source: https://vale.dev/guide/modules Builds a Vale module by specifying a single source file. The module name is defined by the user, and the source file path is provided. ```vale valec build mymodule=~/myprogram.vale --output_dir build ``` -------------------------------- ### Build Module with Folder Source: https://vale.dev/guide/modules Builds a Vale module by including all source files within a specified folder. This simplifies the build command when a module consists of many files. ```vale valec build mymodule=src ``` -------------------------------- ### Define and Construct a Basic Spaceship Struct Source: https://vale.dev/guide/structs Demonstrates how to define a 'Spaceship' struct with 'name' and 'numWings' members and construct an instance using the auto-generated constructor. Assumes 'stdlib' is imported for 'println'. ```vale import stdlib.*; struct Spaceship { name str; numWings int; } exported func main() { ship = Spaceship("Serenity", 2); println(ship.name); } ``` -------------------------------- ### Build Module with Multiple Files Source: https://vale.dev/guide/modules Builds a Vale module using multiple source files. Each file is associated with the same module name. ```vale valec build mymodule=~/foo.vale mymodule=~/bar.vale ``` -------------------------------- ### Import and Use Standard Library List Namespace in Vale Source: https://vale.dev/guide/modules Shows how to import and utilize the List class from the standard library's collections namespace in Vale. This allows for the creation and manipulation of lists. ```vale import stdlib.collections.list.* exported func main() { myList = List().add(4).add(2); foreach i in myList { print(i); } } ``` -------------------------------- ### Shortcalling Constructors for Spaceship Struct Source: https://vale.dev/guide/structs Demonstrates equivalent ways to initialize a Spaceship struct using both explicit constructor calls and a shorthand syntax. This feature simplifies code by allowing direct use of literal representations for struct initialization. ```vale exported func main() { // These statements are equivalent: x Spaceship = Spaceship("Raza", 2); x Spaceship = ["Raza", 2]; } ``` -------------------------------- ### Create and Use a Closure in Vale Source: https://vale.dev/guide/functions Illustrates how to create a closure (a function within another function) in Vale using lambda syntax. It shows both explicit and inferred parameter types for the closure. ```vale import stdlib.*; func main() { add2 = (x int) => { x + 2 }; println("Half-Life " + add2(1)); } ``` ```vale import stdlib.*; func main() { add2 = (x) => { x + 2 }; println("Half-Life " + add2(1)); } ``` -------------------------------- ### Vale: Using Sealed Interface Constructors Source: https://vale.dev/guide/interfaces Demonstrates how to use sealed interface constructors to create instances of different subclasses (SomeInt, NoInt) of a sealed interface (MaybeInt). The constructor infers the correct subclass based on the arguments provided. ```vale exported func main() { x = MaybeInt(7); // x is of type SomeInt. y = MaybeInt(); // y is of type NoInt. } ``` -------------------------------- ### Planned Simplified Interface Syntax (Vale) Source: https://vale.dev/guide/interfaces Presents a preview of a simplified syntax for interfaces in Vale. This future syntax aims to make interfaces more intuitive by allowing methods within the interface definition and using 'self' for method receivers. ```vale interface Bipedal { func hop(self) void; func skip(self) void; } struct Human { ... impl Bipedal { func hop(&self impl) { ... } func skip(&self impl) { ... } } } ``` -------------------------------- ### Open Interface Constructor (Vale) Source: https://vale.dev/guide/interfaces Shows how to create an 'open interface constructor' which allows defining an anonymous substruct that implements an interface. This is particularly useful for creating simple, one-off implementations of interfaces, often with lambdas. ```vale import stdlib.*; interface IShip { func launch(virtual ship &IShip); } exported func main() { x = IShip({ println("Launching!"); }); x.launch(); } ``` -------------------------------- ### Assigning Incoming Data to Locals in Vale Source: https://vale.dev/guide/patterns This snippet demonstrates how to use patterns to assign incoming data to new local variables. The pattern on the left of the '=' receives the data from the expression on the right. ```vale exported func main() { a = 3 + 4; } ``` -------------------------------- ### Vale Variable Reassignment with 'set' Source: https://vale.dev/guide/introduction This snippet showcases how to change the value of an existing variable in Vale using the 'set' keyword. It demonstrates the mutability of variables after their initial declaration, a key aspect of imperative programming. ```vale import stdlib.*; exported func main() { x = "world!"; set x = "Antarctica!"; println("Hello " + x); } ``` -------------------------------- ### Using Match Statement with Patterns in Vale Source: https://vale.dev/guide/patterns This snippet shows how to use a match statement with patterns to conditionally execute code based on an input value. The '_' pattern acts as a wildcard to match any other value. ```vale import stdlib.*; exported func main() { match inputInt() { 1 { println("One!"); } 2 { println("Two!"); } _ { println("Other!"); } } } ``` -------------------------------- ### Vale Tuple Usage Source: https://vale.dev/guide/structs Shows how to create and access tuple data structures in Vale. Tuples are simple structs with members named 0, 1, 2, etc., created using parentheses. Members are accessed using dot notation. ```vale import stdlib.* exported func main() { tup = (5, true, 42); println("Babylon " + tup.0); } ``` -------------------------------- ### C implementation of readInt for Vale Source: https://vale.dev/guide/externs This C code provides the implementation for the `readInt` function that Vale expects. It reads a 64-bit integer from standard input using `scanf` and returns it as a `ValeInt` (which is a `int32_t` in C). It includes necessary headers for standard I/O and Vale types. ```c #include #include #include "mvtest/readInt.h" extern ValeInt mvtest_readInt() { int64_t x = 0; scanf("%ld", &x); return x; } ``` -------------------------------- ### Define a Custom Constructor for Spaceship Struct Source: https://vale.dev/guide/structs Shows how to define a custom constructor for the 'Spaceship' struct, allowing initialization with default values. The constructor must be named the same as the struct and must call another constructor. ```vale import stdlib.*; struct Spaceship { name str; numWings int; } func Spaceship() Spaceship { Spaceship("Serenity", 2) } exported func main() { ship = Spaceship(); println(ship.name); } ``` -------------------------------- ### C implementation calling Vale's triple Source: https://vale.dev/guide/externs This C code implements the `cFunc` declared in Vale. It uses the generated header for `mvtest_triple` to call the Vale exported function `mvtest_triple` with the value 14 and prints the result (which should be 42). ```c #include #include #include "mvtest/cFunc.h" #include "mvtest/triple.h" extern void mvtest_cFunc() { printf("%ld", mvtest_triple(14)); } ``` -------------------------------- ### Move Owning Reference into a Function Source: https://vale.dev/guide/structs Demonstrates how moving an owning reference works when passing it to a function. The function receives ownership, and the original variable becomes invalid. ```vale import stdlib.*; struct Spaceship { name str; fuel int; } func foo(b Spaceship) { println(b.name); } exported func main() { a = Spaceship("Serenity", 2); // Move the Spaceship from a // into foo's b foo(a); // Can't use a now. } ``` -------------------------------- ### Vale: Shortcalling Sealed Interface Constructors Source: https://vale.dev/guide/interfaces Illustrates shortcalling for sealed interface constructors, where a value can be directly passed to a function expecting a specific sealed interface type, implicitly invoking the appropriate constructor. This reduces verbosity compared to explicit constructor calls. ```vale // Using above MaybeInt/NoInt/SomeInt func foo(m MaybeInt) { ... } exported func main() { foo(SomeInt(7)); // Equivalent, calling sealed // interface constructor: foo(MaybeInt(7)); // Equivalent, shortcalling sealed // interface constructor: foo((7)); foo(NoInt()); // Equivalent, calling sealed // interface constructor: foo(MaybeInt()); // Equivalent, shortcalling sealed // interface constructor: foo(()); } ``` -------------------------------- ### Passing Immutable Structs from Vale to C Source: https://vale.dev/guide/externs Demonstrates sending an immutable Vec3 struct from Vale to C. The C code receives a copy and must free it. Includes generated header files. ```vale import stdlib.*; exported struct Vec3 imm { x int; y int; z int; } exported func main() { v = Vec3(10, 11, 12); s = sum(v); println(s); } extern func sum(v Vec3) int; ``` ```c #include #include "mvtest/Vec3.h" #include "mvtest/sum.h" extern int mvtest_sum(mvtest_Vec3* v) { int result = v->x + v->y + v->z; free(v); return result; } ``` -------------------------------- ### Vale Higher RAII with Custom Destructor Source: https://vale.dev/guide/structs Illustrates Higher RAII in Vale, where a custom function (`destroyShip`) handles deallocation instead of the implicit `drop` function. This allows the deallocation function to accept parameters and return values, providing more control over resource management and enforcing specific function calls. ```vale #!DeriveStructDrop struct Spaceship { name str; fuel int; } exported func main() { ship = Spaceship("Serenity", 2); // ship is an owning reference println(ship.name); fuel = (ship).destroyShip(true); println("Fuel was {fuel}.") } func destroyShip( s Spaceship, print bool) int { [name, fuel] = s; // Deallocates ship if print { println("Destroyed {name}!"); } return fuel; } ``` -------------------------------- ### Shortcalling Constructors within Function Calls Source: https://vale.dev/guide/structs Illustrates how shortcalling constructors can be used directly within function arguments, making function calls more concise. This allows passing struct literals directly to functions expecting the struct type. ```vale func foo(s Spaceship) { ... } exported func main() { // These statements are equivalent: foo(Spaceship("Raza", 2)); foo(["Raza", 2]); } ``` -------------------------------- ### Define Generic Function with Interfaces (Vale) Source: https://vale.dev/guide/interfaces Demonstrates how to define a function that can operate on different struct types by using an interface. This avoids code duplication for similar functionalities across various data structures. ```vale interface Bipedal { func hop(virtual b &Bipedal) void; func skip(virtual b &Bipedal) void; } struct Human { ... } func hop(h &Human) { ... } func skip(h &Human) { ... } impl Bipedal for Human; func hopscotch(b &Bipedal) { b.hop(); b.skip(); b.hop(); } struct DarkElf { ... } func hop(s &DarkElf) { ... } func skip(s &DarkElf) { ... } impl Bipedal for DarkElf; exported func main() { wulfgar = Human(...); hopscotch(&wulfgar); drizzt = DarkElf(...); hopscotch(&drizzt); } ``` -------------------------------- ### Transmigrate Drawable Object to Another Region (Vale) Source: https://vale.dev/guide/regions Demonstrates how to move a Drawable object from one region to another using transmigrating. This involves defining Vec2, Curve, and Drawable structures and functions to segmentify a curve into drawables and then transmigrate them. Note that this process can incur 'secede' costs. ```Vale struct Vec2 { x float; y float; } // Represents a quadratic curve struct Curve { origin Vec2; scale Vec2; } func getYForX(curve &Curve, x float) { origin.y + scale.y * pow( x * scale.x + origin.x, 2) } struct Drawable { segments List; } func segmentify(curve &Curve) Drawable { results = List(); foreach x in range(0, 10) { y = curve.getYForX(x); results.add(Vec2(x, y)); } return Drawable(results); } func segmentifyAndSend( curve &a'Curve, drawables &b'List) { // Assembles Drawable drawableInA = segmentify(curve); // Transmigrate it to region b' drawableInB = b' drawableInA; // Can now add it to drawables drawables.add(drawableInB); } ``` -------------------------------- ### Calling Vale's triple from C Source: https://vale.dev/guide/externs This Vale code defines an exported function `triple` that multiplies an integer by 3. It also declares an external C function `cFunc` and a main function that calls `cFunc`. This demonstrates how Vale functions can be called from C. ```vale extern func cFunc(); exported func main() { cFunc(); } exported func triple(x int) int { x * 3 } ``` -------------------------------- ### Manage Ownership of a Mutable Spaceship Struct Source: https://vale.dev/guide/structs Demonstrates the ownership concept for mutable structs in Vale. An owning reference is created, and upon its disappearance (end of scope), the struct is automatically deallocated. ```vale import stdlib.*; struct Spaceship { name str; fuel int; } exported func main() { ship = Spaceship("Serenity", 2); // ship is an owning reference println(ship.name); // implicitly drops ship } ``` -------------------------------- ### Creating Variant Types with If-Statements Source: https://vale.dev/guide/structs Shows how to define a variant type by using an if-statement where the 'then' and 'else' branches return different types. The resulting variable 'a' can hold either a string or an integer, denoted as (str|int). ```vale exported func main() { a = if true { "hello" } else { 42 }; } ``` -------------------------------- ### Destructuring Structs into Locals in Vale Source: https://vale.dev/guide/patterns This code shows how to destructure a struct into individual local variables. It illustrates both explicit type destructuring and type-inferred destructuring for a Vec3 struct. ```vale import stdlib.*; struct Vec3 imm { x int; y int; z int; } func makeVec() Vec3 { Vec3(3, 4, 5) } exported func main() { // Without destructure pattern: tempVec = makeVec(); a = tempVec.x; b = tempVec.y; c = tempVec.z; // Equivalent, using destructure: Vec3[d, e, f] = makeVec(); // Equivalent; can leave off the type: [g, h, i] = makeVec(); println("a: " + a); println("d: " + d); println("g: " + g); } ``` -------------------------------- ### Move Owning Reference Between Locals Source: https://vale.dev/guide/structs Illustrates the concept of 'moving' an owning reference from one local variable to another. After the move, the original local is no longer valid. ```vale struct Spaceship { name str; fuel int; } exported func main() { a = Spaceship("Serenity", 2); b = a; // Move the ship from a to b. // b now owns the Spaceship. // Can't use a now. } ``` -------------------------------- ### Exporting Vale Arrays for C Usage Source: https://vale.dev/guide/externs Shows how to export a Vale immutable runtime-sized array (#[]int) as a named type (ImmIntArray) for use in C. The C function sums the array elements. ```vale export #[]int as ImmIntArray; extern func sumBytes(arr #[]int) int; exported func main() int { a = #[](5, x => x); return sumBytes(a); } ``` ```c #include #include #include "vtest/ImmIntArray.h" ValeInt vtest_sumBytes(vtest_ImmIntArray* arr) { ValeInt total = 0; for (int i = 0; i < arr->length; i++) { total += arr->elements[i]; } free(arr); return total; } ``` -------------------------------- ### Modify Struct Members Using 'set' Source: https://vale.dev/guide/structs Illustrates how to modify a member of a 'Spaceship' struct instance after its creation using the 'set' keyword. The struct has a 'name' member. ```vale struct Spaceship { name str; } exported func main() { ship = Spaceship("Serenity"); set ship.name = "Raza"; } ``` -------------------------------- ### Vale Immutable Struct with Multiple References Source: https://vale.dev/guide/structs Demonstrates the usage of immutable structs in Vale, declared with the `imm` keyword. Immutable structs, once constructed, cannot be modified and can safely have multiple owning references, similar to Java or Python. Vale automatically derives common functions like `println` and `str` for them. ```vale import stdlib.* struct Spaceship imm { name str; numWings int; } exported func main() { ship = Spaceship("Serenity", 2); ship2 = ship; println(ship.numWings); println(ship2.numWings); } ``` -------------------------------- ### Avoid Secede Costs by Making Object Regioned (Vale) Source: https://vale.dev/guide/regions Illustrates how to modify the 'segmentify' function to return a regioned object, thereby avoiding the 'secede' cost during transmigrating. This version accepts the curve from a different region, allowing 'segmentify' to create its own region and produce a regioned Drawable. ```Vale func segmentify( curve &a'Curve) Drawable { results = List(); foreach x in range(0, 10) { y = curve.getYForX(x); results.add(Vec2(x, y)); } return Drawable(results); } func segmentifyAndSend( curve &a'Curve, drawables &b'List) { // Assembles Drawable drawableInA = segmentify(curve); // No secede, because drawableInA // is a regioned object. drawableInB = b' drawableInA; // Can now add it to drawables drawables.add(drawableInB); } ``` -------------------------------- ### Passing Mutable Structs from Vale to C Source: https://vale.dev/guide/externs Illustrates passing a mutable Ship struct reference from Vale to C. C receives an opaque handle and uses Vale functions to access members. Vale avoids copying the entire struct. ```vale import stdlib.*; exported struct Ship { fuel int; } exported func getFuel(s &Ship) int { s.fuel } exported func main() { s = Ship(42); h = halfFuel(&s); println(h); } extern func halfFuel(s &Ship) int; ``` ```c #include #include "mvtest/Ship.h" #include "mvtest/halfFuel.h" #include "mvtest/getFuel.h" extern int mvtest_halfFuel(mvtest_ShipRef s) { return mvtest_getFuel(s) / 2; } ``` -------------------------------- ### Downcasting Interface to Struct (Vale) Source: https://vale.dev/guide/interfaces Illustrates how to safely downcast an interface type back to its concrete struct type using the 'as' function. This is useful when you need to access specific fields or methods of the underlying struct. ```vale interface Ship { } struct FireflyShip { name str; } impl Ship for FireflyShip; exported func main() { ship Ship = FireflyShip("Serenity"); fireflyShip = ship.as().expect(); println(fireflyShip.name); } ``` -------------------------------- ### Vale Unsafe Block for FFI Operations Source: https://vale.dev/guide/unsafe Demonstrates the usage of an 'unsafe' block in Vale to perform operations that bypass normal memory safety checks. This block allows direct use of the heap and stack, similar to C, and requires careful handling to prevent memory corruption. References from the unsafe region to the safe region are scrambled and unscrambled to maintain safety. ```vale func main() { safeShip = Spaceship(1337); unsafe block { notSafeShip = Spaceship(1448); // ... other unsafe operations } } ``` -------------------------------- ### Destructuring Interfaces in Match Statements in Vale Source: https://vale.dev/guide/patterns This code demonstrates using a match statement to check the underlying type of an interface and destructure it simultaneously. It matches against specific struct types implementing an ISpaceship interface. ```vale import stdlib.*; interface ISpaceship { } struct Firefly { name str; } implements ISpaceship for Firefly; struct Raza { name str; fuel int; } implements ISpaceship for Raza; exported func main() { serenity = Firefly("Serenity"); match serenity { Firefly(name) { println("Firefly name " + name); } Raza(name, fuel) { println("Raza name " + name); } } } ``` -------------------------------- ### Sealed Interface Definition (Vale) Source: https://vale.dev/guide/interfaces Demonstrates the definition of a 'sealed' interface in Vale. A sealed interface restricts implementation to only structs defined within the same file, enabling compiler optimizations like inlining and exhaustive match checking. ```vale interface MaybeInt sealed { } struct NoInt { } impl MaybeInt for None; struct SomeInt { value int; } impl SomeInt for MaybeInt; ``` -------------------------------- ### Vale Struct Deallocation with Implicit Drop Source: https://vale.dev/guide/structs Demonstrates automatic deallocation of a struct instance when its owning reference goes out of scope. Vale implicitly generates a `drop` function for structs, which is called automatically. The `destruct` keyword is used within the `drop` function to free memory. ```vale struct Spaceship { name str; fuel int; } exported func main() { ship = Spaceship("Serenity", 2); // ship is an owning reference println(ship.name); // implicit (ship).drop(). } // Implicit: // func drop(s Spaceship) { // destruct s; // frees // } ``` -------------------------------- ### Vale Struct Custom Drop Function Source: https://vale.dev/guide/structs Shows how to define a custom `drop` function for a struct by using the #!DeriveStructDrop attribute to disable automatic derivation. This custom function is called when the owning reference is deallocated and can perform actions like printing a destruction message. ```vale #!DeriveStructDrop struct Spaceship { name str; fuel int; } exported func main() { ship = Spaceship("Serenity", 2); // ship is an owning reference println(ship.name); // implicit (ship).drop(). } func drop(s Spaceship) { // To destroy, move into a destructure. [name, fuel] = s; println("Destroyed {name}!"); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.