diff options
Diffstat (limited to 'js/baba-yaga/docs/00_crash-course.md')
-rw-r--r-- | js/baba-yaga/docs/00_crash-course.md | 169 |
1 files changed, 163 insertions, 6 deletions
diff --git a/js/baba-yaga/docs/00_crash-course.md b/js/baba-yaga/docs/00_crash-course.md index e050973..0327e5e 100644 --- a/js/baba-yaga/docs/00_crash-course.md +++ b/js/baba-yaga/docs/00_crash-course.md @@ -68,7 +68,7 @@ greeting : "Hello"; // Type inferred as String ``` **Type Hierarchy:** -- `Int` ⊂ `Float` ⊂ `Number` (Int can be used where Float expected) +- `Int` ⊂ `Float` ⊂ `Number` (`Int` can be used where `Float` expected) - `String`, `Bool`, `List`, `Table`, `Result` are distinct types ## Functions @@ -482,6 +482,8 @@ processResult : result -> ## Error Handling with Result Type +Baba Yaga uses the `Result` type for explicit error handling instead of exceptions. See [Error Handling](./06_error-handling.md) for comprehensive coverage. + ```baba // Function returning Result divide : x y -> @@ -658,7 +660,85 @@ random : math.random; // Random float 0 <= x < 1 randomInt : math.randomInt 1 6; // Random integer 1-6 inclusive ``` +### Enhanced Random Operations +```baba +// Enhanced random utilities +numbers : [1, 2, 3, 4, 5]; +choice : random.choice numbers; // Random element from list +shuffled : random.shuffle numbers; // Shuffled copy of list +randomNum : random.range 1 10; // Random integer 1-10 +random.seed 42; // Set random seed (placeholder) +``` + +### Data Validation +```baba +// Input validation utilities +isValid : validate.notEmpty "hello"; // true +isEmpty : validate.notEmpty ""; // false +inRange : validate.range 1 10 5; // true +validEmail : validate.email "user@domain.com"; // true +correctType : validate.type "Int" 42; // true +``` + +### Text Processing +```baba +// Enhanced text utilities +multiline : "line1\nline2\nline3"; // Note: \n is literal, not newline +lines : text.lines multiline; // ["line1\\nline2\\nline3"] (single item) +words : text.words "hello world test"; // ["hello", "world", "test"] +padded : text.padLeft 10 "hi"; // " hi" +aligned : text.padRight 10 "hi"; // "hi " +``` + +### Data Transformation +```baba +// Sorting with custom criteria +people : [ + {name: "Alice", age: 30}, + {name: "Bob", age: 25}, + {name: "Charlie", age: 35} +]; +byAge : sort.by people (p -> p.age); // Sorted by age: Bob, Alice, Charlie + +// Grouping data +numbers : [1, 2, 3, 4, 5, 6]; +grouped : group.by numbers (x -> x % 2 = 0); // Groups by even/odd +evenNums : grouped."true"; // [2, 4, 6] +oddNums : grouped."false"; // [1, 3, 5] +``` + +### Utility Functions +```baba +// Array chunking (APL-style windowing) +data : [1, 2, 3, 4, 5, 6]; +chunks : chunk data 2; // [[1, 2], [3, 4], [5, 6]] + +// Range generation +sequence : range 1 5; // [1, 2, 3, 4, 5] +countdown : range 5 1; // [5, 4, 3, 2, 1] + +// Value repetition +repeated : repeat 3 "hello"; // ["hello", "hello", "hello"] +``` + +### Debug and Development Tools +```baba +// Enhanced debugging with type information +debug.print 42; // [DEBUG] 42 (Int) +debug.print (x -> x * 2); // [DEBUG] <function: (x) -> ...> (Unknown) + +// Detailed value inspection +myFunc : x -> x + 1; +details : debug.inspect myFunc; // Returns detailed type information + +// Assertions with custom messages +assert (2 + 2 = 4) "Math should work"; // Passes silently +// assert (2 + 2 = 5) "This fails"; // Throws: "Assertion failed: This fails" +``` + ### I/O Operations + +**Basic Output:** ```baba // Output to console io.out "Hello World"; @@ -669,6 +749,68 @@ io.out [1, 2, 3]; input : io.in; ``` +**Enhanced Output with `io.print`:** + +The `io.print` function provides formatting for different data types, making output more easily readable: + +```baba +// Automatic grid detection for 2D arrays +gameBoard : [ + [1, 0, 1], + [0, 1, 0], + [1, 0, 1] +]; + +io.print gameBoard; +// Output: +// █·█ +// ·█· +// █·█ + +// Labeled output with format strings +io.print "Game Board" gameBoard; +io.print "Score" 1500; +io.print "Player" "Alice"; + +// Perfect for Conway's Game of Life, chess boards, mazes, etc. +glider : [ + [0, 1, 0, 0, 0], + [0, 0, 1, 0, 0], + [1, 1, 1, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0] +]; + +io.print "Glider Pattern Evolution:"; +io.print "Step 0:"; +io.print glider; +// Output: +// Glider Pattern Evolution: +// Step 0: +// ·█··· +// ··█·· +// ███·· +// ····· +// ····· + +// Enhanced display of other data types +myFunction : x -> x * 2; +result : Ok 42; +error : Err "Something went wrong"; + +io.print "Function" myFunction; // Function: <function> +io.print "Success" result; // Success: Ok(42) +io.print "Failure" error; // Failure: Err(Something went wrong) +``` + +**Key `io.print` Features:** +- **Automatic Grid Detection**: 2D numeric arrays display as visual grids with `█` (alive/1) and `·` (dead/0) +- **Clean Function Display**: Shows `<function>` instead of complex internal representations +- **Enhanced Result Types**: Displays `Ok(value)` and `Err(message)` in readable format +- **Labeled Output**: Use format strings like `io.print "Label" data` for organized output +- **Educational Value**: Perfect for teaching algorithms, game development, data visualization +- **Backward Compatible**: Works as a drop-in replacement for `io.out` in most cases + ### Introspection ```baba // Get shape information about values @@ -785,10 +927,18 @@ result : processData "20"; // Returns Err "Result too small" (10 is not > 10) - **Modules**: No built-in import/export system. Larger programs are typically single-file or orchestrated by a host embedding (see `../IO.md`, WIP). - **Standard library scope**: - In addition to items earlier, available built-ins include: - - **General**: `length` (works on lists and strings) - - **String namespace `str`**: as documented - - **Math namespace `math`**: also includes `sign`, `trunc`, `exp`, `log`, `tan`, `asin`, `acos`, `atan`, `atan2`, `deg`, `rad` - - **IO namespace `io`**: `io.out`, `io.in`, and (host-enabled) event functions `io.emit`, `io.listen` -- also plan to add `io` functions for working with files. + - **General**: `length` (works on lists and strings), `chunk`, `range`, `repeat`, `assert` + - **Array Programming**: `scan`, `cumsum`, `cumprod`, `at`, `where`, `take`, `drop`, `broadcast`, `zipWith`, `reshape`, `flatMap` + - **Function Combinators**: `flip`, `apply`, `pipe`, `compose` + - **String namespace `str`**: `concat`, `split`, `join`, `length`, `substring`, `replace`, `trim`, `upper`, `lower` + - **Text namespace `text`**: `lines`, `words`, `padLeft`, `padRight` + - **Math namespace `math`**: `abs`, `sign`, `floor`, `ceil`, `round`, `trunc`, `min`, `max`, `clamp`, `pow`, `sqrt`, `exp`, `log`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `deg`, `rad`, `random`, `randomInt` + - **Random namespace `random`**: `choice`, `shuffle`, `range`, `seed` + - **Validation namespace `validate`**: `notEmpty`, `range`, `email`, `type` + - **Sorting namespace `sort`**: `by` + - **Grouping namespace `group`**: `by` + - **Debug namespace `debug`**: `print`, `inspect` + - **IO namespace `io`**: `out`, `in`, `print`, and (host-enabled) event functions `io.emit`, `io.listen` ## Syntax Clarifications @@ -806,7 +956,14 @@ result : processData "20"; // Returns Err "Result too small" (10 is not > 10) ## Advanced Pattern Matching - **Nested patterns**: Supported for lists and tables. You can match deep structures, e.g. `{user: {name: "Tziporah"}}`. -- **Guards**: Not supported on patterns; use a `then` expression that evaluates a condition instead. +- **Pattern Guards**: Use `if` keyword to add conditions to patterns: + ```baba + classify : x -> + when x is + n if (n > 0) then "positive" + n if (n < 0) then "negative" + 0 then "zero"; + ``` - **Lists/strings**: List patterns match exact shapes (no head/tail cons syntax). Strings can be matched by literal or `String` type. ## Function Behavior Edge Cases |