### Setup and Teardown Patterns Source: https://github.com/moonbitlang/core/blob/main/test/README.mbt.md Example of using helper functions for common test setup and teardown. ```mbt ///| test "with setup helper" { fn setup_test_data() -> Array[Int] { [10, 20, 30, 40, 50] } fn cleanup_test_data(_data : Array[Int]) -> Unit { // Cleanup logic here } let data = setup_test_data() // Perform tests inspect(data.length(), content="5") inspect(data[0], content="10") inspect(data[4], content="50") cleanup_test_data(data) } ``` -------------------------------- ### Isolation Example Source: https://github.com/moonbitlang/core/blob/main/bench/README.mbt.md Demonstrates how to isolate the operation of interest for accurate benchmarking, ensuring setup is done outside the benchmarked function and results are kept to prevent optimization. ```mbt ///| #skip("slow tests") test "isolation example" { let bencher = @bench.new() // Good: Measure only the operation of interest let data = Array::makei(10, fn(i) { i }) // Setup outside benchmark bencher.bench(name="array_sum", fn() { let mut sum = 0 for x in data { sum = sum + x } bencher.keep(sum) // Prevent optimization }) let results = bencher.dump_summaries() inspect(results.length() > 0, content="true") } ``` -------------------------------- ### Performance Examples Source: https://github.com/moonbitlang/core/blob/main/set/README.mbt.md Provides examples of creating large sets, adding many elements, fast membership testing, and efficient set operations like intersection. ```mbt ///| test "performance examples" { // Large set operations let large_set = @set.Set([], capacity=1000) // Add many elements for i in 0..<100 { large_set.add(i) } inspect(large_set.length(), content="100") // Fast membership testing inspect(large_set.contains(50), content="true") inspect(large_set.contains(150), content="false") // Efficient set operations on large sets let another_set = @set.Set([]) for i in 50..<150 { another_set.add(i) } let intersection = large_set.intersection(another_set) inspect(intersection.length(), content="50") // Elements 50-99 } ``` -------------------------------- ### Example Usage Source: https://github.com/moonbitlang/core/blob/main/array/SORT_IMPLEMENTATION.md Demonstrates how to use the sort function on an array of numbers. ```mbt let arr = [5, 4, 3, 2, 1] arr.sort() assert_eq(arr, [1, 2, 3, 4, 5]) ``` -------------------------------- ### Get or Initialize Source: https://github.com/moonbitlang/core/blob/main/hashmap/README.mbt.md Use `get_or_init()` to get a value or initialize it if missing: ```mbt ///| test { let map : @hashmap.HashMap[String, Int] = @hashmap.HashMap([]) let val = map.get_or_init("key", () => 42) assert_eq(val, 42) assert_eq(map.get("key"), Some(42)) } ``` -------------------------------- ### Practical Examples Source: https://github.com/moonbitlang/core/blob/main/string/README.mbt.md Common string manipulation tasks. ```mbt ///| test "practical examples" { let text = "The quick brown fox" // Split into words (using whitespace) - returns Iter[View] let words = text.split(" ").collect() inspect(words.length(), content="4") inspect(words[0].to_owned(), content="The") inspect(words[3].to_owned(), content="fox") // Join words back together - convert views to strings first let word_strings = words.map(fn(v) { v.to_owned() }) let mut result = "" for i, word in word_strings.iter2() { if i > 0 { result = result + "-" } result = result + word } inspect(result, content="The-quick-brown-fox") // Case conversion (works on views) let upper = text[:].to_upper().to_owned() inspect(upper, content="THE QUICK BROWN FOX") let lower = text[:].to_lower().to_owned() inspect(lower, content="the quick brown fox") } ``` -------------------------------- ### Coverage-Driven Testing Example Source: https://github.com/moonbitlang/core/blob/main/coverage/README.mbt.md Demonstrates how to write tests that ensure all code paths are covered, using a multi-branch function as an example. ```mbt ///| test "coverage driven testing" { // Write tests to ensure all code paths are covered fn multi_branch_function(a : Int, b : Int) -> String { if a > b { "greater" } else if a < b { "less" } else { "equal" } } // Test all branches inspect(multi_branch_function(5, 3), content="greater") inspect(multi_branch_function(2, 7), content="less") inspect(multi_branch_function(4, 4), content="equal") // This ensures 100% branch coverage } ``` -------------------------------- ### Configuration Loading Source: https://github.com/moonbitlang/core/blob/main/env/README.mbt.md Example of loading a configuration file path based on the current directory. ```mbt ///| test "configuration loading" { fn load_config_path() -> String { match @env.current_dir() { Some(cwd) => cwd + "/config.json" None => "./config.json" // Fallback } } let config_path = load_config_path() inspect(config_path.length() > 10, content="true") // Should have path with config.json } ``` -------------------------------- ### Command Line Tool Pattern Source: https://github.com/moonbitlang/core/blob/main/env/README.mbt.md Example of parsing command line arguments for a tool. ```mbt ///| test "command line tool pattern" { fn parse_command(args : Array[String]) -> Result[String, String] { if args.length() < 2 { Err("Usage: program [args...]") } else { match args[1] { "help" => Ok("Showing help information") "version" => Ok("Version 1.0.0") "status" => Ok("System is running") cmd => Err("Unknown command: " + cmd) } } } // Test with mock arguments let test_args = ["program", "help"] let result = parse_command(test_args) debug_inspect(result, content="Ok(\"Showing help information\")") let invalid_result = parse_command(["program", "invalid"]) match invalid_result { Ok(_) => inspect(false, content="true") Err(msg) => inspect(msg.length() > 10, content="true") // Should have error message } } ``` -------------------------------- ### Warm-up Example Source: https://github.com/moonbitlang/core/blob/main/bench/README.mbt.md Illustrates the importance of warming up functions before benchmarking to ensure that JIT compilation or other initial overheads do not affect the measurements. ```mbt ///| #skip("slow tests") test "warmup example" { let bencher = @bench.new() fn expensive_operation() -> Int { let mut result = 0 for i in 0..<5 { result = result + i * i } result } // Warm up the function (not measured) for _ in 0..<5 { ignore(expensive_operation()) } // Now benchmark the warmed-up function bencher.bench(name="warmed_up", fn() { let result = expensive_operation() bencher.keep(result) }) let report = bencher.dump_summaries() inspect(report.length() > 30, content="true") // Should have benchmark data } ``` -------------------------------- ### Logging with Timestamps Source: https://github.com/moonbitlang/core/blob/main/env/README.mbt.md Example of creating log messages with timestamps. ```mbt ///| test "logging with timestamps" { fn log_message(level : String, message : String) -> String { let timestamp = @env.now() "[" + timestamp.to_string() + "] " + level + ": " + message } let log_entry = log_message("INFO", "Application started") inspect(log_entry.length() > 20, content="true") // Should have timestamp and message inspect(log_entry.length() > 10, content="true") // Should have substantial content } ``` -------------------------------- ### Builder Pattern Termination Example Source: https://github.com/moonbitlang/core/blob/main/unit/README.mbt.md This example simulates a builder pattern where the build operation returns Unit, indicating successful completion after applying configuration settings. ```mbt ///| test "builder pattern" { // Simulating a builder pattern where build() returns Unit let settings = ["debug=true", "timeout=30"] // Build operation returns Unit after applying configuration fn apply_config(config_list : Array[String]) -> Unit { // In real code: apply configuration settings let _has_settings = config_list.length() > 0 () } let result = apply_config(settings) inspect(result, content="()") } ``` -------------------------------- ### Working Directory Source: https://github.com/moonbitlang/core/blob/main/env/README.mbt.md Get the current working directory. ```mbt ///| test "working directory" { let cwd = @env.current_dir() match cwd { Some(path) => { // We have a current directory inspect(path.length() > 0, content="true") inspect(path.length() > 1, content="true") // Should be a meaningful path } None => // Current directory unavailable (some platforms/environments) inspect(true, content="true") // This is also valid } } ``` -------------------------------- ### Head Source: https://github.com/moonbitlang/core/blob/main/list/README.mbt.md Get the first element of the list as an Option. ```mbt ///| test { let list = @list.from_array([1, 2, 3, 4, 5]) assert_true(list.head() == Some(1)) } ``` -------------------------------- ### Coverage Reporting Example Source: https://github.com/moonbitlang/core/blob/main/coverage/README.mbt.md Shows how to generate and inspect coverage reports using `CoverageCounter`, simulating code execution and analyzing the results. ```mbt ///| test "coverage reporting" { let counter = @coverage.CoverageCounter::new(3) // Simulate some code execution counter.incr(0) // Line 1 executed counter.incr(0) // Line 1 executed again counter.incr(2) // Line 3 executed // Line 2 (index 1) never executed let report = counter.to_string() inspect(report, content="[2, 0, 1]") // In real usage, you might analyze this data: fn analyze_coverage(_coverage_str : String) -> (Int, Int) { // This would parse the coverage data and return (covered, total) // For demonstration, we'll return mock values (2, 3) // 2 out of 3 lines covered } let (covered, total) = analyze_coverage(report) inspect(covered, content="2") inspect(total, content="3") } ``` -------------------------------- ### Utilities Source: https://github.com/moonbitlang/core/blob/main/array/README.mbt.md Provides examples of additional array utilities like joining a string array with `join` and random shuffling with `shuffle`. ```mbt ///| test "utilities" { // Join string array let words = ["hello", "world"] let joined = words.join(" ") inspect(joined, content="hello world") // Random shuffling let nums = [1, 2, 3, 4, 5] // Using deterministic `rand` function below for demonstration // NOTE: When using a normal `rand` function, the actual result may vary let shuffled = nums.shuffle(rand=_ => 1) debug_inspect(shuffled, content="[1, 3, 4, 5, 2]") } ``` -------------------------------- ### Performance Regression Test Example Source: https://github.com/moonbitlang/core/blob/main/bench/README.mbt.md Shows how to integrate benchmarks into a testing workflow to catch performance regressions, demonstrating benchmarking a critical algorithm. ```mbt ///| #skip("slow tests") test "performance regression test" { let bencher = @bench.new() // Benchmark a critical path bencher.bench(name="critical_algorithm", fn() { let data = [5, 2, 8, 1, 9, 3, 7, 4, 6] let sorted = Array::new() for x in data { sorted.push(x) } sorted.sort() bencher.keep(sorted) }) let results = bencher.dump_summaries() // In a real scenario, you might parse results and assert performance bounds inspect(results.length() > 50, content="true") // Should have substantial data } ``` -------------------------------- ### Testing Integration Example Source: https://github.com/moonbitlang/core/blob/main/coverage/README.mbt.md Demonstrates how coverage counters are used within MoonBit's testing framework to track execution of different code branches. ```mbt ///| test "testing integration" { // In real usage, coverage counters are typically generated automatically // by the compiler for coverage analysis fn test_function_with_coverage() -> Bool { // This would normally have auto-generated coverage tracking let counter = @coverage.CoverageCounter::new(2) fn helper(condition : Bool, cov : @coverage.CoverageCounter) -> String { if condition { cov.incr(0) "true_branch" } else { cov.incr(1) "false_branch" } } // Test both branches let result1 = helper(true, counter) let result2 = helper(false, counter) result1 == "true_branch" && result2 == "false_branch" } let test_passed = test_function_with_coverage() inspect(test_passed, content="true") } ``` -------------------------------- ### Math Functions Source: https://github.com/moonbitlang/core/blob/main/float/README.mbt.md Provides examples for common mathematical functions like square root, signum, min, and max. ```mbt ///| test "math functions" { inspect(Float::sqrt(9.0), content="3") inspect(Float::signum(-5.0), content="-1") inspect(Float::min(1.0, 2.0), content="1") inspect(Float::max(1.0, 2.0), content="2") } ``` -------------------------------- ### File Path Operations Source: https://github.com/moonbitlang/core/blob/main/env/README.mbt.md Example of resolving a relative file path against the current directory. ```mbt ///| test "file path operations" { fn resolve_relative_path(relative : String) -> String { match @env.current_dir() { Some(base) => base + "/" + relative None => relative } } let resolved = resolve_relative_path("data/input.txt") inspect(resolved.length() > 10, content="true") // Should have resolved path } ``` -------------------------------- ### Get with default and get_or_init Source: https://github.com/moonbitlang/core/blob/main/sorted_map/README.mbt.md Illustrates `get_or_default()` for fallback values and `get_or_init()` for lazy initialization and insertion if a key is missing. ```mbt ///| test { let map = @sorted_map.from_array([(1, "one")]) assert_eq(map.get_or_default(1, "???"), "one") assert_eq(map.get_or_default(2, "???"), "???") // get_or_init inserts the value if missing let val = map.get_or_init(3, fn() { "three" }) assert_eq(val, "three") assert_eq(map.contains(3), true) // now in the map } ``` -------------------------------- ### Use for Configuration and State Source: https://github.com/moonbitlang/core/blob/main/immut/hashset/README.mbt.md Example showing how immutable sets can be used for managing configurations and state, ensuring immutability and safe sharing. ```mbt ///| test "configuration usage" { let base_config = @hashset.from_array(["feature1", "feature2", "feature3"]) fn enable_feature( config : @hashset.HashSet[String], feature : String, ) -> @hashset.HashSet[String] { config.add(feature) } fn disable_feature( config : @hashset.HashSet[String], feature : String, ) -> @hashset.HashSet[String] { config.remove(feature) } // Create different configurations let dev_config = enable_feature(base_config, "debug_mode") let prod_config = disable_feature(base_config, "feature3") inspect(base_config.length(), content="3") // Base unchanged inspect(dev_config.length(), content="4") // Has debug_mode inspect(prod_config.length(), content="2") // Missing feature3 } ``` -------------------------------- ### Create a new project and test the bundled core Source: https://github.com/moonbitlang/core/blob/main/CONTRIBUTING.md Example of creating a new MoonBit project, running a simple program, and verifying the bundled core library. ```bash moon new hello cd hello echo "fn main { println([1, 2, 3].rev()) }" > src/main/main.mbt moon run src/main ``` -------------------------------- ### Iterator Source: https://github.com/moonbitlang/core/blob/main/immut/hashset/README.mbt.md Example of using the `iter()` method to get an iterator over set elements and convert it to an array. ```mbt ///| test "iter" { let set = @hashset.from_array([1, 2, 3]) let arr = set.iter().to_array() arr.sort() assert_eq(arr, [1, 2, 3]) } ``` -------------------------------- ### Set & Get Source: https://github.com/moonbitlang/core/blob/main/hashmap/README.mbt.md You can use `set()` to add a key-value pair to the map, and use `get()` to get a value. ```mbt ///| test { let map : @hashmap.HashMap[String, Int] = @hashmap.HashMap([]) map.set("a", 1) assert_eq(map.get("a"), Some(1)) assert_eq(map.get_or_default("a", 0), 1) assert_eq(map.get_or_default("b", 0), 0) map.remove("a") assert_eq(map.contains("a"), false) } ``` -------------------------------- ### Set & Get Source: https://github.com/moonbitlang/core/blob/main/builtin/LinkedHashMap.mbt.md You can use `set()` to add a key-value pair to the map, and use `get()` to get a key-value pair. ```mbt ///| test { let map : Map[String, Int] = {} map.set("a", 1) debug_inspect(map.get("a"), content="Some(1)") inspect(map.get_or_default("a", 0), content="1") inspect(map.get_or_default("b", 0), content="0") @json.json_inspect(map, content={ "a": 1 }) map.set("a", 2) // duplicate key @json.json_inspect(map, content={ "a": 2 }) } ``` -------------------------------- ### Clone the repository and set up the core library Source: https://github.com/moonbitlang/core/blob/main/CONTRIBUTING.md Steps to clone the moonbitlang/core repository and bundle it for local use. ```bash rm -rf ~/.moon/lib/core git clone https://github.com/moonbitlang/core ~/.moon/lib/core moon bundle --source-dir ~/.moon/lib/core ``` -------------------------------- ### Negatable flag success snapshot Source: https://github.com/moonbitlang/core/blob/main/argparse/README.mbt.md Example demonstrating negatable flags and snapshotting the parsed flags. ```mbt ///| test "negatable flag success snapshot" { let cmd = @argparse.Command("demo", flags=[FlagArg("cache", negatable=true)]) inspect( cmd.render_help(), content=( #|Usage: demo [options] #| #|Options: #| -h, --help Show help information. #| --[no-]cache #| ), ) let parsed = try! cmd.parse(argv=["--no-cache"], env={}) @debug.debug_inspect( parsed.flags, content=( #|{ "cache": false } ), ) } ``` -------------------------------- ### Container Operations - Get Source: https://github.com/moonbitlang/core/blob/main/sorted_map/README.mbt.md Get a value by its key. The return type is `Option[V]`. ```mbt ///| test { let map = @sorted_map.from_array([(1, "one"), (2, "two"), (3, "three")]) assert_true(map.get(2) == Some("two")) assert_true(map.get(4) == None) } ``` -------------------------------- ### Get map size Source: https://github.com/moonbitlang/core/blob/main/immut/sorted_map/README.mbt.md Demonstrates getting the number of key-value pairs using `length()`. ```mbt test { let map = @sorted_map.from_array([("a", 1), ("b", 2), ("c", 3)]) assert_eq(map.length(), 3) } ``` -------------------------------- ### Add, Get, Remove Source: https://github.com/moonbitlang/core/blob/main/immut/hashmap/README.mbt.md Shows how to add, get, and remove elements, emphasizing immutability. ```mbt ///| test "add_get_remove" { let map = @hashmap.new().add("a", 1).add("b", 2) debug_inspect(map.get("a"), content="Some(1)") inspect(map.contains("b"), content="true") inspect(map["a"], content="1") let map2 = map.remove("a") debug_inspect(map2.get("a"), content="None") // Original map is unchanged debug_inspect(map.get("a"), content="Some(1)") } ``` -------------------------------- ### String Regex Basics Source: https://github.com/moonbitlang/core/blob/main/string/README.mbt.md Demonstrates basic usage of Regex for matching and replacement in strings. ```mbt ///| test "string regex basics" { let regex = @string.Regex("[[:digit:]]+") guard regex.execute("id=42") is Some(m) else { fail("Expected match") } inspect(m.content(), content="42") let replaced = regex.replace_by("a1b22", _m => "#") inspect(replaced, content="a#b#") let replaced_limited = regex.replace_by("a1b22c333", _m => "#", limit=2) inspect(replaced_limited, content="a#b#c333") } ``` -------------------------------- ### Basic option + positional success snapshot Source: https://github.com/moonbitlang/core/blob/main/argparse/README.mbt.md Example of parsing a command with an option and a positional argument, and snapshotting the successful result. ```mbt ///| test "basic option + positional success snapshot" { let matches = @argparse.parse( Command("demo", options=[OptionArg("name")], positionals=[ PositionArg("target"), ]), argv=["--name", "alice", "file.txt"], env={}, ) @debug.debug_inspect( matches.values, content=( #|{ "name": ["alice"], "target": ["file.txt"] } ), ) } ``` -------------------------------- ### Size & Capacity Source: https://github.com/moonbitlang/core/blob/main/hashset/README.mbt.md You can use `size()` to get the number of keys in the set, or `capacity()` to get the current capacity. ```mbt ///| test { let set = @hashset.from_array(["a", "b", "c"]) assert_eq(set.length(), 3) assert_eq(set.capacity(), 8) } ``` -------------------------------- ### Benchmarking Different Algorithms Source: https://github.com/moonbitlang/core/blob/main/bench/README.mbt.md Compare the performance of different implementations. ```mbt ///| #skip("slow tests") test "algorithm comparison" { let bencher = @bench.new() // Benchmark linear search bencher.bench(name="linear_search", fn() { let arr = [1, 2, 3, 4, 5] let target = 3 let mut found = false for x in arr { if x == target { found = true break } } ignore(found) }) // Benchmark using built-in contains (likely optimized) bencher.bench(name="builtin_contains", fn() { let arr = [1, 2, 3, 4, 5] ignore(arr.contains(3)) }) let results = bencher.dump_summaries() inspect(results.length() > 10, content="true") // Should have benchmark data } ``` -------------------------------- ### Size & Capacity Source: https://github.com/moonbitlang/core/blob/main/hashmap/README.mbt.md You can use `size()` to get the number of key-value pairs in the map, or `capacity()` to get the current capacity. ```mbt ///| test { let map = @hashmap.from_array([("a", 1), ("b", 2), ("c", 3)]) assert_eq(map.length(), 3) assert_eq(map.capacity(), 8) } ``` -------------------------------- ### Working with Different Types Source: https://github.com/moonbitlang/core/blob/main/set/README.mbt.md Demonstrates the use of sets with integers and strings, and shows how to represent characters and booleans using their integer codes. ```mbt ///| test "different types" { // Integer set let int_set = @set.Set([1, 2, 3, 4, 5]) inspect(int_set.contains(3), content="true") // String set let string_set = @set.Set(["hello", "world", "moonbit"]) inspect(string_set.contains("world"), content="true") // Note: Char and Bool types don't implement Hash in this version // So we use Int codes for demonstration let char_codes = @set.Set([97, 98, 99]) // ASCII codes for 'a', 'b', 'c' inspect(char_codes.contains(98), content="true") // 'b' = 98 // Integer set representing boolean values let bool_codes = @set.Set([1, 0, 1]) // 1=true, 0=false inspect(bool_codes.length(), content="2") // Only 1 and 0 } ``` -------------------------------- ### Regex Find and Split Source: https://github.com/moonbitlang/core/blob/main/string/README.mbt.md Demonstrates using `find()` to get an iterator of matches and `split()` to divide a string based on regex matches. ```mbt ///| test "find and split" { let digits = @string.Regex("[[:digit:]]+") let matches = digits .find("a1b22c333") .map(fn(m) { m.content().to_owned() }) .collect() debug_inspect(matches, content="[\"1\", \"22\", \"333\"]") let parts = digits.split("a1b22c333").map(fn(v) { v.to_owned() }).collect() debug_inspect(parts, content="[\"a\", \"b\", \"c\", \""]") } ``` -------------------------------- ### Get Min and Max from ImmutableSet Source: https://github.com/moonbitlang/core/blob/main/immut/sorted_set/README.mbt.md Shows how to get the minimum and maximum values from a set, including Option versions. ```mbt ///| test { let set = @sorted_set.from_array([1, 2, 3, 4]) assert_eq(set.min(), 1) assert_eq(set.max(), 4) assert_eq(set.min_option(), Some(1)) assert_eq(set.max_option(), Some(4)) } ``` -------------------------------- ### Set constructor from prelude Source: https://github.com/moonbitlang/core/blob/main/prelude/README.mbt.md Demonstrates the usage of the Set constructor from the prelude. ```mbt ///| test "Set constructor from prelude" { let set = Set([1, 2, 3, 4]) inspect(set.length(), content="4") inspect(set.contains(3), content="true") } ``` -------------------------------- ### Best Practice 2: Validate Command Line Arguments Source: https://github.com/moonbitlang/core/blob/main/env/README.mbt.md Example demonstrating how to validate and parse command-line arguments, handling cases with no arguments, only program name, or program name with arguments. ```mbt check ///| test "argument validation" { fn validate_and_parse_args( args : Array[String], ) -> Result[(String, Array[String]), String] { if args.length() == 0 { Err("No program name available") } else if args.length() == 1 { Ok((args[0], [])) // Program name only, no arguments } else { let program = args[0] let arguments = Array::new() for i in 1.. { inspect(prog, content="myprogram") inspect(args.length(), content="2") } Err(_) => inspect(false, content="true") } } ``` -------------------------------- ### Size & Capacity Source: https://github.com/moonbitlang/core/blob/main/builtin/LinkedHashMap.mbt.md You can use `size()` to get the number of key-value pairs in the map, or `capacity()` to get the current capacity. ```mbt ///| test { let map = { "a": 1, "b": 2, "c": 3 } inspect(map.length(), content="3") inspect(map.capacity(), content="4") } ``` -------------------------------- ### Creating Sets Source: https://github.com/moonbitlang/core/blob/main/set/README.mbt.md Demonstrates various methods for creating sets, including empty sets, sets with initial capacity, and sets initialized from arrays or iterators. Duplicates are automatically handled. ```mbt ///| test "creating sets" { // Empty set let empty_set : @set.Set[Int] = @set.Set([]) inspect(empty_set.length(), content="0") inspect(empty_set.is_empty(), content="true") // Set with initial capacity let set_with_capacity : @set.Set[Int] = @set.Set([], capacity=16) inspect(set_with_capacity.capacity(), content="16") // From array let from_array = @set.Set([1, 2, 3, 2, 1]) // Duplicates are removed inspect(from_array.length(), content="3") // From fixed array let from_fixed = @set.Set([10, 20, 30]) inspect(from_fixed.length(), content="3") // From iterator let from_iter = @set.Set::from_iter([1, 2, 3, 4, 5].iter()) inspect(from_iter.length(), content="5") } ``` -------------------------------- ### uint basics Source: https://github.com/moonbitlang/core/blob/main/uint/README.mbt.md Demonstrates basic properties of UInt, including default, maximum, and minimum values. ```mbt ///| test "uint basics" { // Default value is 0 inspect(@uint.default(), content="0") // Maximum and minimum values inspect(@uint.MAX_VALUE, content="4294967295") inspect(@uint.MIN_VALUE, content="0") } ``` -------------------------------- ### Integration with QuickCheck Source: https://github.com/moonbitlang/core/blob/main/quickcheck/splitmix/README.mbt.md Shows a conceptual example of how the SplitMix generator can be used within QuickCheck for property-based testing with randomly generated data. ```mbt check ///| test "quickcheck integration concept" { // Conceptual usage in property-based testing fn test_property_with_random_data() -> Bool { let rng = @splitmix.new() // Generate test data let test_int = rng.next_positive_int() let test_double = rng.next_double() // Test some property test_int > 0 && test_double >= 0.0 && test_double < 1.0 } let property_holds = test_property_with_random_data() inspect(property_holds, content="true") } ``` -------------------------------- ### Query array properties Source: https://github.com/moonbitlang/core/blob/main/immut/array/README.mbt.md Shows how to retrieve elements by index using `get()` (or array indexing `[]`), get the array's length with `length()`, and check if it's empty with `is_empty()`. ```mbt ///| test { let arr = @array.from_array([1, 2, 3, 4, 5]) assert_eq(arr[2], 3) assert_eq(arr.length(), 5) assert_eq(arr.is_empty(), false) } ``` -------------------------------- ### Get & Set Source: https://github.com/moonbitlang/core/blob/main/immut/vector/README.mbt.md Use index syntax `v[i]` or `at()` for direct access. Use `get()` for a safe lookup that returns `Option`. `set()` returns a new vector with the element at the given index replaced. ```mbt ///| test { let v = @vector.from_array([10, 20, 30, 40, 50]) assert_eq(v[2], 30) assert_true(v.get(2) == Some(30)) assert_true(v.get(99) == None) assert_true(v.peek() == Some(50)) // last element } ``` ```mbt ///| test { let v1 = @vector.from_array([1, 2, 3]) let v2 = v1.set(1, 20) @debug.assert_eq(v1.to_array(), [1, 2, 3]) // original unchanged @debug.assert_eq(v2.to_array(), [1, 20, 3]) } ``` -------------------------------- ### Length Source: https://github.com/moonbitlang/core/blob/main/list/README.mbt.md Get the number of elements in the list. ```mbt ///| test { let list = @list.from_array([1, 2, 3, 4, 5]) assert_eq(list.length(), 5) } ``` -------------------------------- ### Tail Source: https://github.com/moonbitlang/core/blob/main/list/README.mbt.md Get the list without its first element. ```mbt ///| test { let list = @list.from_array([1, 2, 3, 4, 5]) @debug.assert_eq(list.unsafe_tail(), @list.from_array([2, 3, 4, 5])) } ``` -------------------------------- ### String Creation and Conversion Source: https://github.com/moonbitlang/core/blob/main/string/README.mbt.md Create strings from various sources. ```mbt ///| test "string creation" { // From character array let chars = ['H', 'e', 'l', 'l', 'o'] let str1 = String::from_array(chars) inspect(str1, content="Hello") // From character iterator let str2 = String::from_iter(['W', 'o', 'r', 'l', 'd'].iter()) inspect(str2, content="World") // Default empty string let empty = String::default() inspect(empty, content="") } ``` -------------------------------- ### Nth Element Source: https://github.com/moonbitlang/core/blob/main/list/README.mbt.md Get the nth element of the list as an Option. ```mbt ///| test { let list = @list.from_array([1, 2, 3, 4, 5]) assert_true(list.nth(2) == Some(3)) } ``` -------------------------------- ### Creating Arrays Source: https://github.com/moonbitlang/core/blob/main/array/README.mbt.md Demonstrates various methods for creating arrays, including array literals, creating with indices using `Array::makei`, and creating from an iterator using `Array::from_iter`. ```mbt ///| test "array creation" { // Using array literal let arr1 = [1, 2, 3] debug_inspect(arr1, content="[1, 2, 3]") // Creating with indices let arr2 = Array::makei(3, i => i * 2) debug_inspect(arr2, content="[0, 2, 4]") // Creating from iterator let arr3 = Array::from_iter("hello".iter()) debug_inspect(arr3, content="['h', 'e', 'l', 'l', 'o']") } ``` -------------------------------- ### Iterators from LazyList Source: https://github.com/moonbitlang/core/blob/main/lazy_list/README.md Shows how to get independent iterators from a LazyList. ```MoonBit let xs = @lazy_list.from_iter([1, 2, 3].iter()) let i1 = xs.iter() let i2 = xs.iter() debug_inspect(i1.next(), content="Some(1)") // Independent state per iterator. debug_inspect(i2.next(), content="Some(1)") ``` -------------------------------- ### Container Operations - Size Source: https://github.com/moonbitlang/core/blob/main/sorted_map/README.mbt.md Get the size of the map. ```mbt ///| test { let map = @sorted_map.from_array([(1, "one"), (2, "two"), (3, "three")]) assert_eq(map.length(), 3) } ``` -------------------------------- ### Array Views Source: https://github.com/moonbitlang/core/blob/main/array/README.mbt.md Shows how to use array views for lightweight array slicing and demonstrates mapping a view to a new array. ```mbt ///| test "array views" { let arr = [1, 2, 3, 4, 5] let view = arr[1:4] debug_inspect( view, content=( #| ), ) // Map view to new array let doubled = view.map(x => x * 2) debug_inspect(doubled, content="[4, 6, 8]") } ``` -------------------------------- ### Container Operations - Size Source: https://github.com/moonbitlang/core/blob/main/sorted_set/README.mbt.md Get the size of the set. ```mbt ///| test { let set = @sorted_set.from_array([1, 2, 3, 4]) assert_eq(set.length(), 4) } ``` -------------------------------- ### Iterators Source: https://github.com/moonbitlang/core/blob/main/hashmap/README.mbt.md Or use `iter()`, `keys()`, or `values()` to get iterators: ```mbt ///| test { let map = @hashmap.from_array([("a", 1)]) let _iter = map.iter() let _keys = map.keys() let _vals = map.values() } ``` -------------------------------- ### StringBuilder Source: https://github.com/moonbitlang/core/blob/main/builtin/README.mbt.md Efficient string building. ```mbt check ///| test "string builder" { let builder = StringBuilder() builder.write_string("Hello") builder.write_string(", ") builder.write_string("World!") let result = builder.to_string() inspect(result, content="Hello, World!") } ``` -------------------------------- ### Query Source: https://github.com/moonbitlang/core/blob/main/immut/vector/README.mbt.md Get the length of the vector and check if it's empty. ```mbt ///| test { let v = @vector.from_array([1, 2, 3]) assert_eq(v.length(), 3) assert_eq(v.is_empty(), false) let empty : @vector.Vector[Int] = @vector.new() assert_eq(empty.is_empty(), true) } ``` -------------------------------- ### Default Value Source: https://github.com/moonbitlang/core/blob/main/int16/README.mbt.md Shows how to get the default value for Int16, which is 0. ```mbt ///| test "int16 default" { let x = Int16::default() inspect(x, content="0") } ``` -------------------------------- ### View Conversion and Usage Source: https://github.com/moonbitlang/core/blob/main/string/DESIGN.mbt.md Illustrates how String can be implicitly converted to a View and how to use Views in function parameters. ```mbt ///| test "view conversion" { fn process_text(text : StringView) -> Int { text.length() } let str = "Hello World" let view = str.view(start_offset=0, end_offset=5) // Both work due to implicit conversion let _ = process_text(str) // String implicitly converts to View let _ = process_text(view) // Direct View usage } ``` -------------------------------- ### Create and Clear Source: https://github.com/moonbitlang/core/blob/main/queue/README.mbt.md You can create a queue manually by using the `new` or construct it using the `from_array`. ```mbt ///| test { let _queue : @queue.Queue[Int] = @queue.Queue([]) let _queue1 = @queue.from_array([1, 2, 3]) } ``` -------------------------------- ### Creating a Min-Heap with @cmp.Reverse Source: https://github.com/moonbitlang/core/blob/main/priority_queue/README.mbt.md Shows how to create a min-heap (smallest element first) by using `@cmp.Reverse` to reverse the comparison order of elements. ```mbt ///| test { // Create a min-heap by wrapping elements with @cmp.Reverse let min_heap = @priority_queue.from_array([ @cmp.Reverse(5), @cmp.Reverse(2), @cmp.Reverse(8), @cmp.Reverse(1), ]) // The smallest wrapped value (1) should be at the top debug_inspect(min_heap.peek(), content="Some(Reverse(1))") } ``` -------------------------------- ### Best Practice 1: Handle Missing Environment Data Gracefully Source: https://github.com/moonbitlang/core/blob/main/env/README.mbt.md Example of gracefully handling missing environment data by providing a fallback value for the current working directory. ```mbt check ///| test "graceful handling" { fn get_work_dir() -> String { match @env.current_dir() { Some(dir) => dir None => "~" // Fallback to home directory symbol } } let work_dir = get_work_dir() inspect(work_dir.length() > 0, content="true") } ``` -------------------------------- ### Concatenation and Comparison Source: https://github.com/moonbitlang/core/blob/main/bytes/README.mbt.md Shows examples of concatenating and comparing `Bytes` objects. ```mbt ///| test "bytes operations" { let b1 = Bytes::from_array([b'a', b'b']) let b2 = Bytes::from_array([b'c', b'd']) // Concatenation let combined = b1 + b2 inspect( combined, content=( #|b"abcd" ), ) // Comparison let same = Bytes::from_array([b'a', b'b']) let different = Bytes::from_array([b'x', b'y']) inspect(b1 == same, content="true") inspect(b1 == different, content="false") inspect(b1 < b2, content="true") } ``` -------------------------------- ### Data Extraction - Keys and Values Source: https://github.com/moonbitlang/core/blob/main/sorted_map/README.mbt.md Get all keys or values from the map. ```mbt ///| test { let map = @sorted_map.from_array([(3, "three"), (1, "one"), (2, "two")]) @debug.assert_eq(map.keys().collect(), [1, 2, 3]) @debug.assert_eq(map.values().collect(), ["one", "two", "three"]) } ``` -------------------------------- ### Set Relationships Source: https://github.com/moonbitlang/core/blob/main/set/README.mbt.md Explains how to test relationships between sets, including subset, superset, disjointness, and equality, demonstrating the use of corresponding methods. ```mbt ///| test "set relationships" { let small_set = @set.Set([1, 2]) let large_set = @set.Set([1, 2, 3, 4]) let disjoint_set = @set.Set([5, 6, 7]) // Subset testing inspect(small_set.is_subset(large_set), content="true") inspect(large_set.is_subset(small_set), content="false") // Superset testing inspect(large_set.is_superset(small_set), content="true") inspect(small_set.is_superset(large_set), content="false") // Disjoint testing (no common elements) inspect(small_set.is_disjoint(disjoint_set), content="true") inspect(small_set.is_disjoint(large_set), content="false") // Equal sets let set1 = @set.Set([1, 2, 3]) let set2 = @set.Set([3, 2, 1]) // Order doesn't matter inspect(set1 == set2, content="true") } ``` -------------------------------- ### Iteration Source: https://github.com/moonbitlang/core/blob/main/immut/vector/README.mbt.md Use `iter()` to get an iterator, or `each()` / `eachi()` for direct traversal. ```mbt ///| test { let v = @vector.from_array([1, 2, 3, 4, 5]) // iterator debug_inspect(v.iter().to_array(), content="[1, 2, 3, 4, 5]") // each let buf = [] v.each(fn(x) { buf.push(x) }) @debug.assert_eq(buf, [1, 2, 3, 4, 5]) // eachi (with index) let pairs = [] v.eachi(fn(i, x) { pairs.push((i, x)) }) @debug.assert_eq(pairs, [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]) } ``` -------------------------------- ### Basic Benchmarking Source: https://github.com/moonbitlang/core/blob/main/bench/README.mbt.md Use the `single_bench` function to benchmark individual operations. ```mbt ///| #skip("slow tests") test "basic benchmarking" { fn simple_calc(n : Int) -> Int { n * 2 + 1 } // Benchmark a simple computation let summary = @bench.single_bench(name="simple_calc", fn() { ignore(simple_calc(5)) }) // The benchmark ran successfully (we can't inspect exact timing) inspect(summary.to_json().stringify().length() > 0, content="true") } ``` -------------------------------- ### Clear Test Names Source: https://github.com/moonbitlang/core/blob/main/test/README.mbt.md Examples of descriptive test names. ```mbt ///| test "user_can_login_with_valid_credentials" { // Test implementation } ``` ```mbt ///| test "login_fails_with_invalid_password" { // Test implementation } ``` ```mbt ///| test "shopping_cart_calculates_total_correctly" { // Test implementation } ``` -------------------------------- ### Create Source: https://github.com/moonbitlang/core/blob/main/list/README.mbt.md You can create an empty list or a list from an array. ```mbt ///| test { let empty_list : @list.List[Int] = @list.new() assert_true(empty_list.is_empty()) let list = @list.from_array([1, 2, 3, 4, 5]) @debug.assert_eq(list, @list.from_array([1, 2, 3, 4, 5])) } ``` -------------------------------- ### Peek Source: https://github.com/moonbitlang/core/blob/main/queue/README.mbt.md You can get the first element of the queue without removing it using the `peek` method. ```mbt ///| test { let queue = @queue.from_array([1, 2, 3]) assert_eq(queue.peek(), Some(1)) } ``` -------------------------------- ### uint methods Source: https://github.com/moonbitlang/core/blob/main/uint/README.mbt.md Demonstrates using the to_int64() method for UInt conversion. ```mbt ///| test "uint methods" { let num = 1000U // Using method syntax inspect(num.to_int64(), content="1000") } ``` -------------------------------- ### Random State Creation Source: https://github.com/moonbitlang/core/blob/main/quickcheck/splitmix/README.mbt.md Demonstrates how to create and initialize random number generators using default or specific seeds, and how to clone existing states. ```mbt check ///| test "random state creation" { // Create with default seed let rng1 = @splitmix.new() inspect(rng1.to_string().length() > 0, content="true") // Create with specific seed let rng2 = @splitmix.new(seed=12345UL) inspect(rng2.to_string().length() > 0, content="true") // Clone existing state let rng3 = rng2.clone() inspect(rng3.to_string().length() > 0, content="true") } ``` -------------------------------- ### Get all keys Source: https://github.com/moonbitlang/core/blob/main/immut/sorted_map/README.mbt.md Shows retrieving all keys in ascending order using `keys_as_iter()`. ```mbt test { let map = @sorted_map.from_array([("a", 1), ("b", 2), ("c", 3)]) let keys = map.keys_as_iter() // ["a", "b", "c"] assert_eq(keys.collect(), ["a", "b", "c"]) } ``` -------------------------------- ### Sorting Source: https://github.com/moonbitlang/core/blob/main/array/README.mbt.md Demonstrates sorting utilities including basic sorting with `sort`, custom comparison sorting with `sort_by`, and sorting by key with `sort_by_key`. ```mbt ///| test "sorting" { let arr = [3, 1, 4, 1, 5, 9, 2, 6] // Basic sorting - creates new sorted array let sorted1 = arr.copy() sorted1.sort() debug_inspect(sorted1, content="[1, 1, 2, 3, 4, 5, 6, 9]") // Custom comparison let strs = ["aa", "b", "ccc"] let sorted2 = strs.copy() sorted2.sort_by((a, b) => a.length().compare(b.length())) debug_inspect( sorted2, content=( #|["b", "aa", "ccc"] ), ) // Sort by key let pairs = [(2, "b"), (1, "a"), (3, "c")] let sorted3 = pairs.copy() sorted3.sort_by_key(p => p.0) debug_inspect( sorted3, content=( #|[(1, "a"), (2, "b"), (3, "c")] ), ) } ```