commit a9b840aa5eda5390b9d78d6a641b589efd478175
parent 09c4642550e26d09adabbd8503901cf229613792
Author: Andrew Laack <andrew@laack.co>
Date: Fri, 28 Aug 2026 18:54:29 -0500
notes about pattern matching
Diffstat:
2 files changed, 33 insertions(+), 0 deletions(-)
diff --git a/ch3/follow-along/pattern-match.ml b/ch3/follow-along/pattern-match.ml
@@ -0,0 +1,5 @@
+let res = match not true with
+| true -> "true"
+| false -> "false" in
+
+print_endline res;;
diff --git a/ch3/my-problems/sum.ml b/ch3/my-problems/sum.ml
@@ -0,0 +1,28 @@
+(* 1
+
+NEW IDEA: pattern matching on a list. A list is either empty, written [], or a
+head element attached to a tail, written h :: t. Those are the only two shapes,
+so a match with those two cases covers everything.
+
+ match lst with
+ | [] -> ...
+ | h :: t -> ...
+
+sum_list lst adds up a list of ints. The empty list sums to 0.
+
+sum_list [1; 2; 3] = 6, sum_list [] = 0, sum_list [7] = 7.
+
+*)
+
+(*
+ since a list is either nil or a cons of elements with nil, we pattern match as such, knowing eventually that t will be []
+ and that will call the recursive function one last time as the base case.
+*)
+
+let rec sum_list lst =
+ match lst with
+ | h :: t -> h + sum_list t
+ | [] -> 0;;
+
+print_int (sum_list (10 :: 34 :: 34 :: []));;
+print_int (sum_list [1; 2; 3]);;