about summary refs log tree commit diff stats
path: root/js/baba-yaga/docs/03_pattern-matching.md
diff options
context:
space:
mode:
Diffstat (limited to 'js/baba-yaga/docs/03_pattern-matching.md')
-rw-r--r--js/baba-yaga/docs/03_pattern-matching.md42
1 files changed, 42 insertions, 0 deletions
diff --git a/js/baba-yaga/docs/03_pattern-matching.md b/js/baba-yaga/docs/03_pattern-matching.md
index 43c4c65..0bd663e 100644
--- a/js/baba-yaga/docs/03_pattern-matching.md
+++ b/js/baba-yaga/docs/03_pattern-matching.md
@@ -30,6 +30,48 @@ checkType : val ->
     _      then "Other";
 ```
 
+## Pattern Guards
+
+Use the `if` keyword to add conditional guards to patterns:
+
+```baba
+// Basic guards with range conditions
+categorizeNumber : n ->
+  when n is
+    x if (x > 0) then "positive"
+    x if (x < 0) then "negative"
+    0 then "zero";
+
+// Guards with complex conditions
+gradeStudent : score ->
+  when score is
+    s if (s >= 90) then "A"
+    s if (s >= 80 and s < 90) then "B"
+    s if (s >= 70 and s < 80) then "C"
+    s if (s >= 60 and s < 70) then "D"
+    s if (s < 60) then "F"
+    _ then "Invalid score";
+
+// Type guards
+processValue : value ->
+  when value is
+    Int if value > 100 then "large integer"
+    Int if value > 0 then "positive integer"
+    String if (length value) > 10 then "long string"
+    String if (length value) > 0 then "short string"
+    _ then "other";
+
+// Guards with wildcard patterns
+checkRange : x ->
+  when x is
+    _ if (x >= 1 and x <= 10) then "small"
+    _ if (x >= 11 and x <= 100) then "medium"
+    _ if (x > 100) then "large"
+    _ then "invalid";
+```
+
+Guards are evaluated after the underlying pattern matches. The guard expression has access to any variables bound by the pattern. This allows for sophisticated conditional matching without conflicting with the `..` string concatenation operator.
+
 ## Typed discriminants
 
 When using typed functions that return `Result`, you can pattern match on variants and bind inner values.