### Rational Number Examples and Division by Zero Source: https://github.com/verselang/book/blob/main/docs/02_primitives.md Provides examples of rational number creation and highlights that division by zero is a failable operation. ```verse Half := 5 / 2 # rational: exactly 5/2 Third := 10 / 3 # rational: exactly 10/3 Quarter := 1 / 4 # rational: exactly 1/4 if (not (1 / 0)): # Division by zero fails ``` -------------------------------- ### Module Initialization Example Source: https://github.com/verselang/book/blob/main/docs/16_modules.md Demonstrates how to define and use a module with a local qualifier to distinguish between module-scoped and local variables. ```verse ModuleX := module: Value:int = 10 ProcessValue((local:)Value:int): (ModuleX:)Value + (local:)Value # Clear distinction ``` -------------------------------- ### Range Iteration Examples Source: https://github.com/verselang/book/blob/main/docs/07_control.md Demonstrates numeric iteration using the inclusive range operator '..'. Shows examples of standard ranges, single-element ranges, and empty ranges. ```Verse # Iterates: 1, 2, 3, 4, 5 (both bounds included) for (I := 1..5): Print("Count: {I}") # Single element range for (I := 42..42): Print("Answer: {I}") # Prints once: "Answer: 42" # Empty range (start > end produces no iterations) for (I := 5..1): Print("Never executes") # Loop body never runs ``` -------------------------------- ### Calling a Convenience Constructor Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Example of how to invoke a convenience constructor that delegates to another constructor within the same class. ```verse NewPlayer := MakeNewPlayer("Alice") ``` -------------------------------- ### Nested Defer Statements Example Source: https://github.com/verselang/book/blob/main/docs/07_control.md Illustrates nested defer blocks, showing how cleanup operations are executed in a cascading LIFO order. ```verse ProcessWithCleanup():void = Log("A") defer: Log("B") defer: Log("inner") # Runs after B Log("C") Log("D") # Output: A D B C inner ``` -------------------------------- ### Start Background Tasks with Branch Source: https://github.com/verselang/book/blob/main/docs/14_concurrency.md Utilize the `branch` primitive to start background tasks that do not block the main execution flow. These tasks run concurrently with the rest of the program. ```verse StartBackgroundSystems():void = branch: MonitorPlayerStats() branch: UpdateLeaderboards() branch: ProcessAchievements() # Main game continues while background tasks run ``` -------------------------------- ### Game Entity Example Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Shows a unique entity class and how to track specific entities in collections using identity-based equality. ```verse #entity := class: # var Health:int = 100 # var Position:vector3 # Can track specific entities in collections var ActiveEntities:[entity]logic = map{} ``` -------------------------------- ### Selecting Component Type Based on Configuration Source: https://github.com/verselang/book/blob/main/docs/11_types.md This example demonstrates how to dynamically select a component type based on a configuration string, returning the appropriate class type for instantiation or further processing. ```Verse # Select type based on configuration GetComponentType(Config:string):castable_subtype(component) = if (Config = "physics"): physics_component else if (Config = "render"): render_component else: component ``` -------------------------------- ### Verse Type System Example Source: https://github.com/verselang/book/blob/main/docs/VerseSyntaxValidation.md Illustrates Verse's type system, highlighting type inference, explicit type annotations for documentation, and the use of enums and structs with persistence. ```verse # Copyright Epic Games, Inc. All Rights Reserved. ################################################# # Generated Digest of Verse API # DO NOT modify this manually! ``` -------------------------------- ### Module Evolution Example Source: https://github.com/verselang/book/blob/main/docs/16_modules.md This example demonstrates valid and invalid updates to a public module member during module evolution. Valid updates include changing the value or making the type more specific. Invalid updates involve changing to an incompatible type or removing the member. ```verse # Initial publication Thing:rational = 1/3 # Valid updates: # - Change the value (not the type) Thing:rational = 10/3 # - Make the type more specific (subtype) Thing:int = 20 # nat is a subtype of int # Invalid updates (would be rejected): # - Remove the member # - Change to incompatible type # Thing:string = "hello" # Would fail ``` -------------------------------- ### Example of Delegating Constructor Execution Order Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Demonstrates the execution flow when a derived class constructor delegates to a parent constructor. Shows the output and the resulting object state. ```verse # Prints: "Base constructor" # Results in: derived{BaseValue := 10, DerivedValue := 20} Instance := MakeDerived(10, 20) ``` -------------------------------- ### Usage of Parametric Interface Implementation Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md This example demonstrates how to use a class that implements a parametric interface, providing the necessary type arguments for the interface. ```verse # Usage Eq := comparable_equivalence(int){} Eq.Equal[5, 5] # Succeeds ``` -------------------------------- ### Resource Distribution Logic Source: https://context7.com/verselang/book/llms.txt Example of a function distributing resources, including a check for minimum distribution per player. ```verse # Resource distribution example DistributeGold(TotalGold:int, NumPlayers:int):int = GoldPerPlayer := TotalGold / NumPlayers # rational Floor(GoldPerPlayer) > 0 # fails if < 1 per player if (Share := DistributeGold[100, 4]): Print("Each player gets {Share} gold") # 25 ``` -------------------------------- ### Insert into Array at Start or End Source: https://github.com/verselang/book/blob/main/docs/03_containers.md Demonstrates inserting elements at the beginning or end of an array. Out-of-bounds insertions will fail. ```verse if (Updated2 := NumArray.Insert[0, array{5}]): # Updated2 is array{5, 10, 20, 40} # Can insert at end (index = Length is valid) if (Updated3 := NumArray.Insert[NumArray.Length, array{50}]): # Updated3 is array{10, 20, 40, 50} # Out of bounds fails if (not NumArray.Insert[-1, array{5}]): # Negative index fails if (not NumArray.Insert[NumArray.Length + 1, array{5}]): # Beyond Length fails ``` -------------------------------- ### Basic Defer Statement Example Source: https://github.com/verselang/book/blob/main/docs/07_control.md Demonstrates nested defer statements for resource management. The inner defer executes after the outer defer's code, following a LIFO order. ```verse DatabaseTransaction():void = DbId := OpenDatabase() defer: CloseDatabase(DbId) # Executes second (outer resource) TxnId := BeginTransaction[DbId] defer: CommitTransaction(TxnId) # Executes first (inner resource) DoWork[] # Work happens with both resources active # Defers execute: CommitTransaction, then CloseDatabase ``` -------------------------------- ### Basic Suspension Effect Example Source: https://github.com/verselang/book/blob/main/docs/13_effects.md Demonstrates a function using the `` effect to pause execution for animations, sounds, and screen displays. ```verse PlayVictorySequence():void = PlayAnimation(VictoryDance) Sleep(2.0) # Wait 2 seconds PlaySound(VictoryFanfare) Sleep(1.0) ShowRewardsScreen() ``` -------------------------------- ### Nested Module Qualification Example Source: https://github.com/verselang/book/blob/main/docs/16_modules.md Shows how qualification works across multiple scopes in nested modules, including parameters, module members, and outer module paths. ```verse # What you write: GameSystem := module: BaseValue:int = 42 Calculator := module: Multiplier:int = 2 Calculate(Input:int):int = Input * Multiplier + BaseValue # How the compiler sees it: (/YourGame:)GameSystem := module: (/YourGame/GameSystem:)BaseValue:(/Verse.org/Verse:)int = 42 (/YourGame/GameSystem:)Calculator := module: (/YourGame/GameSystem/Calculator:)Multiplier:(/Verse.org/Verse:)int = 2 (/YourGame/GameSystem/Calculator:)Calculate((local:)Input:(/Verse.org/Verse:)int):(/Verse.org/Verse:)int = (local:)Input * (/YourGame/GameSystem/Calculator:)Multiplier + (/YourGame/GameSystem:)BaseValue ``` -------------------------------- ### Function Variance Examples Source: https://github.com/verselang/book/blob/main/docs/06_functions.md Demonstrates contravariant parameters and covariant return types with function assignments. Shows valid and invalid assignments based on type compatibility. ```verse # Some functions on animals AnimalToDog(X:animal):dog = dog{Name := X.Name, Breed := "Unknown"} DogToWorkingDog(X:dog):working_dog = working_dog{Name := X.Name, Breed := "Unknown", Work := "Guard"} DogToAnimal(X:dog):animal = X WorkingDogToDog(X:working_dog):dog = X # Example of valid assignments var ProcessDog:type{_(:dog):dog} = AnimalToDog # Valid: Accepts more general (animal), returns exact (dog) # Contravariant parameter: animal <: dog allows this set ProcessDog = AnimalToDog # OK: tuple(animal)->dog <: tuple(dog)->dog # Valid: Accepts exact (dog), returns more specific (working_dog) # Covariant return: working_dog <: dog allows this set ProcessDog = DogToWorkingDog # OK: tuple(dog)->working_dog <: tuple(dog)->dog ProcessDog1 := AnimalToDog # Inferred as type{_(:animal):dog} set ProcessDog1 = DogToAnimal # ERROR: incompatible assignment ProcessDog2 := AnimalToDog # Inferred as type{_(:animal):dog} set ProcessDog2 = WorkingDogToDog # ERROR: incompatible assignment ``` -------------------------------- ### Unstructured Concurrency with spawn and await Source: https://context7.com/verselang/book/llms.txt Use `spawn` to start a concurrent task and `await` to wait for its completion. This provides an unstructured approach to concurrency, returning a task handle. ```verse DoWork():void = Handle := spawn { HeavyComputation() } # ... do other things ... Result := await Handle # wait for the spawned task ``` -------------------------------- ### Path Literal Examples Source: https://github.com/verselang/book/blob/main/docs/01_expressions.md Path literals are used to identify modules and packages in a hierarchical structure. They must start with a '/' and contain labels with alphanumeric characters, periods, or hyphens. Identifiers within paths must start with a letter or underscore. ```Verse /Verse.org/Verse /YourGame/Player/Inventory /user@example.com/MyModule ``` -------------------------------- ### Dual-Specifier Pattern for Resource Management Source: https://github.com/verselang/book/blob/main/docs/12_access.md Demonstrates the dual-specifier pattern for variables, allowing public readability while maintaining private writability to enforce invariants. This example shows a resource manager class. ```verse resource_manager := class: var TotalResources:int = 1000 var AllocatedResources:int = 0 var AvailableResources:int = 1000 AllocateResources(Amount:int):void = Amount <= AvailableResources set AllocatedResources = AllocatedResources + Amount set AvailableResources = AvailableResources - Amount ``` -------------------------------- ### Array Slicing: Start Index to End Source: https://github.com/verselang/book/blob/main/docs/03_containers.md Extracts elements from a specified start index to the end of the array using `Array.Slice[Start]`. ```verse if (Slice := NumArray.Slice[2]): Slice = array{30, 40, 50} ``` -------------------------------- ### Demonstrate Control Flow and Failure Handling Source: https://github.com/verselang/book/blob/main/docs/00_overview.md Illustrates creating a player, equipping gear, and purchasing items, showing how failure can drive control flow. Requires setup for player and item creation. ```Verse RunExample():void = # Create a player (can't fail) Hero := player_character{Name := "Verse Hero"} # Try to equip starter gear (might fail) if (Hero.EquipStarterGear[]): Print("Hero equipped with starter gear") # Demonstrate transactional behavior ExpensiveItem := game_item{ Name := "Golden Crown" Rarity := item_rarity.epic Stats := item_stats{Value := 2000, Weight := 90.0} # Very heavy! } # This might fail due to weight or insufficient gold if (Hero.Inventory.PurchaseItem[ExpensiveItem]): Print("Purchase successful!") else: Print("Purchase failed - gold remains at {Hero.Inventory.Gold}") # Use higher-order functions with nested function predicate IsRareOrLegendary(I:game_item):void = I.Rarity = item_rarity.rare or I.Rarity = item_rarity.legendary RareItems := Hero.Inventory.FilterItems(IsRareOrLegendary) Print("Found {RareItems.Length} rare items") ``` -------------------------------- ### Combining Import and Using Source: https://github.com/verselang/book/blob/main/docs/16_modules.md Illustrates how to use 'import' to alias a module and then use 'using' to also bring its members directly into scope. ```verse Graphics := import(/MyProject/Systems/Graphics) using { Graphics } # now Graphics members are also directly available ``` -------------------------------- ### Array Slicing: Start and End Indices Source: https://github.com/verselang/book/blob/main/docs/03_containers.md Extracts a portion of an array using the `.Slice[Start, End]` method, which includes elements from `Start` up to (but not including) `End`. ```verse NumArray : []int = array{10, 20, 30, 40, 50} if (Slice := NumArray.Slice[1, 4]): Slice = array{20, 30, 40} ``` -------------------------------- ### Verse Subscribable Events Example Source: https://github.com/verselang/book/blob/main/docs/14_concurrency.md Demonstrates subscribing multiple handlers to a subscribable event, signaling, and unsubscribing. Use when multiple independent systems need to react to the same occurrence. ```verse LogScore(:int):void={} UpdateUI(:int):void={} CheckAchievements(:int):void={} ScoreEvent := subscribable_event(int){} # Subscribe multiple handlers Logger := ScoreEvent.Subscribe(LogScore) UIUpdater := ScoreEvent.Subscribe(UpdateUI) AchievementChecker := ScoreEvent.Subscribe(CheckAchievements) # Signal invokes all subscribed handlers ScoreEvent.Signal(1000) # Calls LogScore(1000), UpdateUI(1000), CheckAchievements(1000) # Unsubscribe to stop receiving signals Logger.Cancel() ScoreEvent.Signal(2000) # Only calls UpdateUI and CheckAchievements ``` -------------------------------- ### Example Hierarchy with Final Super Source: https://github.com/verselang/book/blob/main/docs/11_types.md Defines a component hierarchy with `physics_component` marked as ``. This example illustrates the structure used for querying type families. ```verse component := class: ID:int # Direct final_super subclass of component physics_component := class(component): Velocity:vector3 # Descendants of physics_component rigid_body := class(physics_component): Mass:float character_body := class(rigid_body): Health:int ``` -------------------------------- ### Compiler Error Message Example Source: https://github.com/verselang/book/blob/main/docs/16_modules.md Shows an example of a compiler error message that uses qualified names to precisely identify the types involved in an assignment error. ```verse Error: Cannot assign (/Verse.org/Verse:)string to (/Verse.org/Verse:)int at line 42 ``` -------------------------------- ### Partial Application Source: https://github.com/verselang/book/blob/main/docs/06_functions.md Demonstrates partial application, where a function with multiple arguments is applied to some arguments, returning a new function that expects the remaining arguments. ```verse Partial(F(:a, :b):c, X:a where a:type, b:type, c:type):type{_(:b):c} = # Return a nested function with X captured PartialFunc(Y:b):c = F(X, Y) PartialFunc Add(X:int, Y:int):int = X + Y Add5 := Partial(Add, 5) Add5(3) # Returns 8 ``` -------------------------------- ### Initialize Maps in Verse Source: https://github.com/verselang/book/blob/main/docs/03_containers.md Shows how to declare and initialize empty maps and maps with initial key-value pairs. Maps can be indexed by any comparable type. ```verse Empty := map{} var Weights:[string]float = map{ "ant" => 0.0001, "elephant" => 500.0, "galaxy" => 500000000000.0 } ``` -------------------------------- ### Constant and Variable Initialization in Verse Source: https://github.com/verselang/book/blob/main/docs/04_operators.md Demonstrates initialization of constants and variables using '=' and ':=', including type inference with ':='. ```verse # Constant initialization with explicit types - both = and := work MaxHealth:int = 100 PlayerName:string := "Hero" # Variable initialization with explicit types - both = and := work var CurrentHealth:int = 100 var Score:int := 0 # Type inference requires := (no type annotation) AutoTyped := 42 # Inferred as int # Note: var requires explicit type - var X := value is not allowed ``` -------------------------------- ### Map Covariance Example Source: https://github.com/verselang/book/blob/main/docs/03_containers.md Map types are covariant in both key and value types. This example demonstrates covariant assignment of a map with a more specific key type to a variable expecting a map with a more general key type. ```Verse # assume # animal := class {} # dog := class(animal) {} # Map TYPE variance is COVARIANT DogMap : [dog]int = map{dog{} => 1} AnimalMap : [animal]int = DogMap # ✓ Works - covariant assignment ``` -------------------------------- ### Initialize Multiple Systems Concurrently with Sync Source: https://github.com/verselang/book/blob/main/docs/14_concurrency.md Employ the `sync` primitive to initialize multiple systems concurrently. All tasks within the `sync` block must complete before the program proceeds. ```verse InitializeGame():void = sync: LoadAssets() ConnectToServer() InitializeUI() PrepareAudio() Print("Game ready!") ``` -------------------------------- ### Instantiate Parametric Container Class Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Demonstrates instantiating a parametric container class with different concrete types like int, string, and a custom player type. ```verse IntContainer := container(int){Value := 42} StringContainer := container(string){Value := "hello"} PlayerContainer := container(player){Value := player{Name := "Hero", Health := 100}} ``` -------------------------------- ### Component Interface Example Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Defines a unique component interface where identity-based equality is required for interface types. ```verse #component := interface: # Owner:entity ``` -------------------------------- ### Examples of Comparable Type Usage with Equality Source: https://github.com/verselang/book/blob/main/docs/11_types.md Illustrates successful equality comparisons between same-typed comparable values and a failure case where implicit conversion between int and float is not supported for equality checks. ```verse 0 = 0 # Succeeds - both are int 0.0 = 0.0 # Succeeds - both are float 0 = 0.0 # Fails - there is no implicit conversion from int to float ``` -------------------------------- ### Option Type Syntax and Construction Source: https://github.com/verselang/book/blob/main/docs/08_failure.md Demonstrates the correct syntax for declaring optional types with the '?' prefix and using the 'option{}' constructor to wrap values or handle potential failures from computations. ```verse ValidSyntax:?int = option{42} # Correct ``` ```verse MaybeNumber:?int = option{42} MaybeText:?string = option{"hello"} MaybePlayer:?player = option{player{}} ``` ```verse Filled:?int = option{42} Empty:?int = false Result:?int = option{RiskyComputation[]} # false if computation fails ``` -------------------------------- ### Get Map Length Source: https://github.com/verselang/book/blob/main/docs/03_containers.md Access the number of entries in a map using the `Length` field. This operation is efficient. ```verse Friendliness:[string]int = map{"peach" => 1000, "pelican" => 17} Friendliness.Length = 2 ``` -------------------------------- ### One-Time Resource Initialization with `upon` Source: https://github.com/verselang/book/blob/main/docs/15_live_variables.md Use `upon` to execute code once when specified conditions are met, ideal for initializing resources like textures and models before starting a game. The `Print` and `StartGame` functions are called only when both `TextureLoaded` and `ModelLoaded` become true. ```Verse resource_manager := class: var TextureLoaded:logic = false var ModelLoaded:logic = false Initialize():void = upon(TextureLoaded? and ModelLoaded?): Print("All resources loaded, starting game") StartGame() ``` -------------------------------- ### Array Indexing and Map Lookup Syntax Source: https://github.com/verselang/book/blob/main/docs/01_expressions.md Demonstrates the syntax for array indexing and map lookups using square brackets. ```verse Array[0] # Array indexing Map["key"] # Map lookup Matrix[Row][Col] # Nested indexing Data[ComputeIndex()] # Dynamic index computation ``` -------------------------------- ### Using vs. Importing Modules in Verse Source: https://github.com/verselang/book/blob/main/docs/16_modules.md Demonstrates the difference between 'using' and 'import' for module access. 'using' brings members directly into scope, while 'import' creates an alias for accessing members via dot notation. ```verse # using: members available directly using { /MyProject/Utilities } Result := HelperFunction() # HelperFunction is in scope # import: members accessed through alias Utils := import(/MyProject/Utilities) Result := Utils.HelperFunction() # accessed via alias ``` -------------------------------- ### Multiple Constraints on Same Type (Not Supported) Source: https://github.com/verselang/book/blob/main/docs/11_types.md Shows an example of attempting multiple constraints on the same type parameter, which is not currently supported in Verse. ```verse # Multiple constraints on the same type F(In:t where t:subtype(comparable), t:subtype(printable)):t = # Not supported Print("Processing: {In}") In ``` -------------------------------- ### Invalid Expression for Localization Source: https://github.com/verselang/book/blob/main/docs/12_access.md This example shows an error when attempting to use an expression instead of a string literal for a localized message. ```verse # ERROR: Expression not allowed # InvalidMessage : message = "A" + "B" # ERROR 3638 ``` -------------------------------- ### Unique Class Default Values Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Demonstrates how `` classes ensure each object gets its own distinct instance, even when nested. ```verse token := class: ID:int = 0 container := class: MyToken:token = token{} ``` -------------------------------- ### Integer Division and Modulo in Verse Source: https://github.com/verselang/book/blob/main/docs/02_primitives.md Shows how to use the Mod and Quotient functions for integer division with remainder. Both functions fail if the divisor is zero. ```verse # Signatures # Mod(Dividend:int, Divisor:int):int # Quotient(Dividend:int, Divisor:int):int # Positive operands Mod[15, 4] # Returns 3 Quotient[15, 4] # Returns 3 # Relationship: 15 = 3*4 + 3 # Negative dividend Mod[-15, 4] # Returns 1 Quotient[-15, 4] # Returns -4 # Relationship: -15 = -4*4 + 1 # Negative divisor Mod[-1, -2] # Returns 1 Quotient[-1, -2] # Returns 1 # Division by zero fails if (not Mod[10, 0]): Print("Cannot mod by zero") if (not Quotient[10, 0]): Print("Cannot divide by zero") ``` -------------------------------- ### Call a Constructor Function Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Demonstrates how to call a constructor function 'MakePlayer' to create an instance of the 'player' class. The '' annotation is used in the definition but not in the call. ```Verse Hero := MakePlayer("Aldric", 5) # Call constructor function ``` -------------------------------- ### Attempt to Get Length of Weak Map Source: https://github.com/verselang/book/blob/main/docs/03_containers.md Demonstrates that accessing the `.Length` property on a weak map is an error, as this operation is restricted. ```verse var MyWeakMap:weak_map(int,int) = map{1 => 2} # ERROR: weak_map has no Length property # Size := MyWeakMap.Length ``` -------------------------------- ### Bivariant Class Example Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Demonstrates a bivariant class where the type parameter does not affect the public interface, allowing for bidirectional type conversions. ```verse entity := class: ID:int player := class(entity): Name:string # Bivariant class - type parameter not used in public interface container(t:type) := class: DoSomething():void = {} # Doesn't use t at all ``` ```verse # Bivariant allows conversion in both directions EntityContainer:container(entity) = container(entity){} PlayerContainer:container(player) = container(player){} # Both directions work X:container(entity) = PlayerContainer # Valid Y:container(player) = EntityContainer # Also valid ``` -------------------------------- ### Basic Arithmetic and Unary Operators Source: https://github.com/verselang/book/blob/main/docs/04_operators.md Demonstrates basic arithmetic operations like addition, subtraction, multiplication, and division, as well as unary negation and positive operators. Includes an example of integer division and type conversion. ```verse # Basic arithmetic Sum := 10 + 20 # 30 Diff := 50 - 15 # 35 Prod := 6 * 7 # 42 Quot := 20.0 / 4.0 # 5.0 # Unary operators Negative := -42 # -42 Positive := +42 # 42 (for alignment) # Integer division (failable, returns rational) if (Result := 10 / 3): IntResult := Floor(Result) # 3 # Type conversion through multiplication IntValue:int = 42 FloatValue:float = IntValue * 1.0 # Converts to 42.0 ``` -------------------------------- ### Arrays of Functions Source: https://github.com/verselang/book/blob/main/docs/06_functions.md Functions sharing the same signature can be stored in arrays. This enables iterating over a collection of functions and applying them, for example, to sum their results. ```verse GetZero():int = 0 GetOne():int = 1 GetTwo():int = 2 SumFunctions(Functions:[]type{_():int}):int = var Result:int = 0 for (Fn : Functions): set Result += Fn() Result SumFunctions(array{GetZero, GetOne, GetTwo}) # Returns 3 ``` -------------------------------- ### Waiting for multiple spawned tasks Source: https://github.com/verselang/book/blob/main/docs/14_concurrency.md Shows how to spawn multiple tasks and wait for all of them to complete using a `sync` block. ```APIDOC ## Waiting for multiple spawned tasks ### Description Spawns multiple tasks and waits for all of them to complete, collecting their results. ### Request Example ```verse RunMultipleTasks():void = T1 := spawn{Task1()} T2 := spawn{Task2()} T3 := spawn{Task3()} # Wait for all to complete Results := sync: T1.Await() T2.Await() T3.Await() Print("All tasks complete: {Results(0)}, {Results(1)}, {Results(2)}") ``` ``` -------------------------------- ### GetCastableFinalSuperClassFromType Example Source: https://github.com/verselang/book/blob/main/docs/11_types.md Demonstrates using GetCastableFinalSuperClassFromType with type parameters instead of instances. This function returns the same castable subtype as its instance-based counterpart. ```verse # Same behavior, different syntax TypeFamily := GetCastableFinalSuperClassFromType[component, rigid_body] InstanceFamily := GetCastableFinalSuperClass[component, rigid_body{}] # Both return the same castable_subtype ``` -------------------------------- ### Shadowing Conflict Example Source: https://github.com/verselang/book/blob/main/docs/16_modules.md Illustrates a shadowing conflict where a local variable has the same name as a module member, requiring explicit qualification to distinguish them. ```verse MyModule := module: Value:int = 100 Process(Value:int):int = # Without explicit qualification, this is ambiguous Value + Value # Which Value? Module or parameter? ``` -------------------------------- ### Integer Literals and Variables in Verse Source: https://github.com/verselang/book/blob/main/docs/02_primitives.md Shows how to declare and initialize integer variables using literals. Integer literals must fit within a 64-bit signed range. ```verse A :int= -42 # civilian size #B := 42424242424242424242424242424242424242424242424242 # scary numbers... # ...can be computed but not written as literals AnswerToTheQuestion :int= 42 # A variable that never changes CoinsPerQuiver :int= 100 # A quiver costs this many coins ArrowsPerQuiver :int= 15 # A quiver contains this many arrows # Mutable variables (see Mutability chapter for details on var and set) var Coins :int= 225 # The player currently has 225 coins var Arrows :int= 3 # The player currently has 3 arrows var TotalPurchases :int= 0 # Track total purchases ``` -------------------------------- ### Assigning Functions to Types with Optional Parameters Source: https://github.com/verselang/book/blob/main/docs/06_functions.md Demonstrates assigning functions to types, showing how optional parameters are handled and default values are used. ```verse F1:type{_(?Required:int):int} = Process F1(?Required := 5) # Returns 5 (uses default) ``` ```verse F2:type{_(?Required:int, ?Optional:int):int} = Process F2(?Required := 5, ?Optional := 3) # Returns 8 ``` ```verse DefaultAll(?A:int = 1, ?B:int = 2):int = A + B F3:type{_():int} = DefaultAll F3() # Returns 3 ``` -------------------------------- ### Invalid Expression Interpolation in Localization Source: https://github.com/verselang/book/blob/main/docs/12_access.md This example demonstrates an error when attempting to use an expression within the interpolation braces of a localized message. ```verse # ERROR: Expressions not allowed # ExprMessage(Name:string) : message = "{"Hello"}" # ERROR 3652 ``` -------------------------------- ### Instantiate Parametric Class with Different Types Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Demonstrates instantiating a parametric class with different concrete types, such as integers and custom player objects. ```verse container(t:type) := class: Value:t player := class: Name:string var Health:int = 100 ``` -------------------------------- ### Input-Output Variables for Clamping Source: https://github.com/verselang/book/blob/main/docs/15_live_variables.md Illustrates input-output variables to manage values within dynamic constraints. The output variable is live and automatically reclamped when constraints change. ```Verse clamp := class: var Lower:int = 0 var Upper:int = 100 Evaluate(Value:int):int = if (Value < Upper) then: if (Value > Lower) then Value else Lower else: Upper Clamp := clamp{} var BaseHealth->Health: Clamp.Evaluate = 50 # Health = 50 (clamped to [0, 100]) set Health = 75 # BaseHealth = 75, Health = 75 set Health = 120 # BaseHealth = 120, Health = 100 (clamped) set Clamp.Upper = 60 # BaseHealth = 120, Health = 60 (reclamped) ``` -------------------------------- ### Define Base and Derived Classes Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Demonstrates defining a base class 'entity' and a derived class 'player' that inherits from it. ```verse entity := class: ID:int player := class(entity): Name:string ``` -------------------------------- ### Equivalence of Empty Options and False Source: https://github.com/verselang/book/blob/main/docs/08_failure.md Illustrates that empty options and the boolean value 'false' are equivalent in Verse. Comparisons between them will succeed. ```verse EmptyOption:?int = false EmptyOption = false # This comparison succeeds ``` -------------------------------- ### Compatible Type Constraint for Operations Source: https://github.com/verselang/book/blob/main/docs/11_types.md Example of a where clause ensuring type compatibility for operations like merging arrays, requiring elements to be comparable. ```verse # Constraint that ensures compatible types for an operation Merge(Container1:[]t, Container2:[]t where t:subtype(comparable)):[]t = var Result:[]t = Container1 for (Element : Container2, not Contains[Result, Element]): set Result += array{Element} Result # Function type constraints ApplyTwice(F:type{_(:t):t}, Value:t where t:type):t = F(F(Value)) ``` -------------------------------- ### Verse Module and Type Declarations Source: https://github.com/verselang/book/blob/main/docs/VerseSyntaxValidation.md Illustrates Verse syntax for module imports, enum types, immutable structs, and classes with methods and computed properties. Includes examples of type system features and functional programming style. ```verse # Module declaration - start by importing utility functions using { /Verse.org/VerseCLR } # Define item rarity as an enumeration - showing Verse's type system item_rarity := enum: common uncommon rare epic legendary # Struct for immutable item data - functional programming style item_stats := struct: Damage:float = 0.0 Defense:float = 0.0 Weight:float = 1.0 Value:int = 0 # Class for game items - object-oriented features with functional constraints game_item := class: Name:string Rarity:item_rarity = item_rarity.common Stats:item_stats = item_stats{} StackSize:int = 1 # Method with decides effect - can fail GetRarityMultiplier():float = case(Rarity): item_rarity.common => 1.0 item_rarity.uncommon => 1.5 item_rarity.rare => 2.0 item_rarity.epic => 3.0 _ => false # Fails if the item is legenday or unexpected # Computed property using closed-world function GetEffectiveValue() :int= Floor[Stats.Value * GetRarityMultiplier[]] ``` -------------------------------- ### Storing Types in a Map Registry Source: https://github.com/verselang/book/blob/main/docs/02_primitives.md Example of using a map to store type values associated with string keys, creating a type registry. ```verse # Store type in data structure TypeRegistry:[string]type = map{ "Integer" => int, "Text" => string, "Flag" => logic } ``` -------------------------------- ### Aliasing Modules for Clarity Source: https://github.com/verselang/book/blob/main/docs/16_modules.md Shows how to use 'import' to create aliases for modules, which is useful for avoiding name collisions and making the origin of definitions explicit, especially when dealing with modules that might share identifier names. ```verse Physics := import(/MyProject/Systems/Physics) Graphics := import(/MyProject/Systems/Graphics) # Clear which Transform is being used PhysicsTransform := Physics.Transform{} GraphicsTransform := Graphics.Transform{} ``` -------------------------------- ### Prediction Effect for Client-Side Responsiveness Source: https://github.com/verselang/book/blob/main/docs/13_effects.md Example of a function using the `` effect to run predictively on clients for immediate feedback, with server validation. ```verse HandleJumpInput():void = # Runs immediately on the client for responsiveness StartJumpAnimation() PlayJumpSound() # Server will validate and correct if needed PerformJump() ``` -------------------------------- ### String Length in Verse Source: https://github.com/verselang/book/blob/main/docs/02_primitives.md Get the number of UTF-8 code units in a string using the `.Length` property. Note that this is not the same as the number of Unicode characters. ```verse "José".Length = 5 # succeeds; 5 UTF-8 code units "Jose".Length = 4 # succeeds; 4 UTF-8 code units ``` -------------------------------- ### Structured Concurrency with Race Source: https://context7.com/verselang/book/llms.txt Illustrates the 'race' construct where multiple concurrent tasks are started, and the first one to complete determines the result, canceling the others. ```Verse # race — first to finish wins; others are canceled FastestOf():int = Winner := race: SlowOperation() # takes 5 s FastOperation() # takes 1 s → wins MediumOperation() # takes 3 s Winner # result of FastOperation ``` -------------------------------- ### Define Modules with Colon or Bracket Syntax Source: https://github.com/verselang/book/blob/main/docs/16_modules.md Demonstrates the two supported syntaxes for defining modules and their contents, including constants and classes. Use this when creating new modules in your Verse project. ```verse # Colon syntax module1 := module: # Module contents here MyConstant:int = 42 MyClass := class: Value:int = 0 # Bracket syntax (also supported) module2 := module { # Module contents here AnotherConstant:string = "Hello" } ``` -------------------------------- ### Module Function Path Qualifier Error Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Using module function paths as qualifiers is not supported. This example illustrates the error that occurs when attempting such a pattern. ```verse M := module: f():void = (M.f:)X:int = 0 # ERROR ``` -------------------------------- ### Verse Function Definitions and Calls Source: https://context7.com/verselang/book/llms.txt Demonstrates defining functions with positional and named parameters, including default values. Shows how functions can be treated as first-class values. ```verse # Positional parameters Add(A:int, B:int):int = A + B Add(3, 4) # 7 # Named parameters with defaults Log(Message:string, ?Level:int = 1, ?Color:string = "white"): string = "[{Level}] {Message} ({Color})" Log("Starting") # "[1] Starting (white)" Log("Warning", ?Level := 2) # "[2] Warning (white)" Log("Error", ?Color := "red", ?Level := 3) # "[3] Error (red)" # Default values can reference earlier parameters CreateRange(?Start:int = 0, ?End:int = Start + 10):[]int = array{Start, End} CreateRange() # array{0, 10} CreateRange(?Start := 5) # array{5, 15} # Functions as values Apply(F:int->int, X:int):int = F(X) Double := (N:int) => N * 2 Apply(Double, 5) # 10 # Parametric (generic) function with where clause Identity(X:t where t:type):t = X Identity(42) # t inferred as int → 42 Identity("verse") # t inferred as string → "verse" ``` -------------------------------- ### Invalid Inheritance: Multiple Base Classes Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md An example illustrating an invalid inheritance scenario where a class attempts to inherit from multiple base classes, which is not supported. ```verse # Invalid: cannot inherit from multiple classes # invalid := class(base1, base2): # ERROR ``` -------------------------------- ### Variadic-like Function Calls with Tuples Source: https://github.com/verselang/book/blob/main/docs/03_containers.md Demonstrates how tuples can be passed as arguments to functions expecting arrays, providing a variadic-like syntax. ```verse Sum(Nums:[]int): var Total:int = 0 for (N : Nums): set Total += N Total Sum(1, 2, 3, 4) # Returns 10 Sum((5, 6)) # Returns 11 Values := (10, 20, 30) Sum(Values) # Returns 60 ``` -------------------------------- ### Declare Jagged Array in Verse Source: https://github.com/verselang/book/blob/main/docs/03_containers.md Creates a jagged array where each row has a different length, determined by the row index. This example produces a triangular structure. ```verse Example : [][]int = for (Row := 0..3): for (Column := 0..Row): Row * Column ``` -------------------------------- ### Hyperbolic Functions in Verse Source: https://github.com/verselang/book/blob/main/docs/02_primitives.md Illustrates the use of hyperbolic sine, cosine, tangent, and their inverse functions. Includes examples with special values like infinity. ```verse # Signatures # Sinh(X:float):float # Hyperbolic sine # Cosh(X:float):float # Hyperbolic cosine # Tanh(X:float):float # Hyperbolic tangent # ArSinh(X:float):float # Inverse hyperbolic sine # ArCosh(X:float):float # Inverse hyperbolic cosine # ArTanh(X:float):float # Inverse hyperbolic tangent Sinh(0.0) # Returns 0.0 Sinh(1.0) # Returns 1.175... Cosh(0.0) # Returns 1.0 Cosh(1.0) # Returns 1.543... Tanh(0.0) # Returns 0.0 Tanh(1.0) # Returns 0.761... # Special values Sinh(-Inf) # Returns -Inf Sinh(Inf) # Returns Inf Cosh(-Inf) # Returns Inf Cosh(Inf) # Returns Inf Tanh(-Inf) # Returns -1.0 Tanh(Inf) # Returns 1.0 ArSinh(0.0) # Returns 0.0 ArCosh(1.0) # Returns 0.0 ArTanh(0.0) # Returns 0.0 # Special values ArSinh(-Inf) # Returns -Inf ArSinh(Inf) # Returns Inf ArCosh(Inf) # Returns Inf ArCosh(-1.0) # Returns NaN (domain error) ``` -------------------------------- ### Module and Type Definitions Source: https://github.com/verselang/book/blob/main/docs/VerseSyntaxValidation.md Demonstrates module import paths and public type declarations within Verse. ```APIDOC ## Module import path: /UnrealEngine.com/SceneGraph (/UnrealEngine.com:)SceneGraph := module: using {/Verse.org/Native} Temporary := module: # Module import path: /UnrealEngine.com/Temporary/UI UI := module: using {/Verse.org/Assets} using {/Verse.org/Colors} using {/UnrealEngine.com/Temporary/SpatialMath} using {/Verse.org/Simulation} # Returns the `player_ui` associated with `Player`. # Fails if there is no `player_ui` associated with `Player`. GetPlayerUI(Player:player):player_ui # Text justification values: # Left: Justify the text logically to the left based on current culture. # Center: Justify the text in the center. # Right: Justify the text logically to the right based on current culture. # The Left and Right value will flip when the local culture is right-to-left. text_justification := enum: Left Center Right InvariantLeft InvariantRight # Base widget for text widget. text_base := class(widget): # Sets the opacity of the displayed text. SetTextOpacity(InOpacity:type {_X:float where 0.000000 <= _X, _X <= 1.000000}):void # Gets the opacity of the displayed text. GetTextOpacity():type {_X:float where 0.000000 <= _X, _X <= 1.000000} # Module import path: /UnrealEngine.com/Temporary/SpatialMath (/UnrealEngine.com/Temporary:)SpatialMath := module: using {/Verse.org/SpatialMath} using {/Verse.org/Native} using {/Verse.org/Simulation} @editable @import_as("/Script/EpicGamesTemporary.FVerseRotation_Deprecated") (/UnrealEngine.com/Temporary/SpatialMath:)rotation := struct: @vm_no_effect_token # Makes a `rotation` by applying `YawRightDegrees`, `PitchUpDegrees`, and `RollClockwiseDegrees`, in that order: # * first a *yaw* about the Z axis with a positive angle indicating a clockwise rotation when viewed from above, # * then a *pitch* about the new Y axis with a positive angle indicating 'nose up', # * followed by a *roll* about the new X axis axis with a positive angle indicating a clockwise rotation when viewed along +X. # Note that these conventions differ from `MakeRotation` but match `ApplyYaw`, `ApplyPitch`, and `ApplyRoll`. (/UnrealEngine.com/Temporary/SpatialMath:)MakeRotationFromYawPitchRollDegrees(YawRightDegrees:float, PitchUpDegrees:float, RollClockwiseDegrees:float):(/UnrealEngine.com/Temporary/SpatialMath:)rotation JSON := module: value := class: # Retrieve an object value or fail if value is not a json object AsObject():[string]value # Parse a JSON string returning a value with its contents Parse(JSONString:string):value ``` -------------------------------- ### Best Practices for Translatable Messages Source: https://github.com/verselang/book/blob/main/docs/12_access.md This example demonstrates a well-designed localized message that is clear, complete, and flexible for translation. It contrasts with less ideal approaches. ```verse # Good: Clear, complete, flexible PlayerJoined(PlayerName:string, TeamName:string) : message = "{PlayerName} joined team {TeamName}" # Avoid: Fragments that might be concatenated # PlayerPrefix(Name:string) : message = "Player {Name}" # JoinedSuffix(Team:string) : message = "joined {Team}" ``` -------------------------------- ### Direct Field Initialization with Archetype Expressions Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Demonstrates the simplest form of object construction in Verse using archetype expressions. This method is suitable for basic cases where fields can be directly initialized without complex logic. ```Verse player := class: Name:string var Health:int = 100 Level:int = 1 ``` -------------------------------- ### Verse Float Literals Source: https://github.com/verselang/book/blob/main/docs/01_expressions.md Shows float literals with decimal points and the optional 'f64' suffix for explicit bit-depth. Includes examples of scientific notation. ```verse Pi := 3.14159 Half := 0.5 Explicit := 12.34f64 # Explicit bit-depth suffix ``` ```verse Large := 1.0e10 # 10,000,000,000 (sign optional) Small := 1.0e-5 # 0.00001 WithSign := 2.5e+3 # 2,500 (explicit + sign) Compact := 1.5e2 # 150 (no sign defaults to +) ``` -------------------------------- ### Handle Constructor Failure Source: https://github.com/verselang/book/blob/main/docs/10_classes_interfaces.md Shows how to use the failure syntax with a validated constructor 'MakeValidPlayer'. It checks if the construction succeeded before adding the player, handling cases where the level might be out of range. ```Verse # Constructor can fail - use with failure syntax if (Player := MakeValidPlayer["Hero", 5]): # Construction succeeded AddPlayer(Player) else: # Construction failed - level out of range ``` -------------------------------- ### Iterating Over String Characters with Filtering Source: https://github.com/verselang/book/blob/main/docs/07_control.md Iterate over a string character by character and apply filter conditions within the loop header. This example counts vowels. ```Verse CountVowels(Text:string):int = var Count:int = 0 for (Char : Text, Char = 'a' or Char = 'e' or Char = 'i' or Char = 'o' or Char = 'u'): set Count += 1 Count ```