diff options
author | Joel Kronqvist <joel.kronqvist@iki.fi> | 2025-08-21 12:50:31 +0300 |
---|---|---|
committer | Joel Kronqvist <joel.kronqvist@iki.fi> | 2025-08-21 12:50:31 +0300 |
commit | 7e5482763bea64116a10c047ed87fd67e3a0aaa9 (patch) | |
tree | a78f5caff094b609af18d1ade8391fac1a2900e0 | |
parent | d1c97e405230b6616ef834cf38be351e566a228e (diff) | |
download | myslip-7e5482763bea64116a10c047ed87fd67e3a0aaa9.tar.gz myslip-7e5482763bea64116a10c047ed87fd67e3a0aaa9.zip |
doc: added section on coproducts and documented their pattern matching in TUTORIAL.md
-rw-r--r-- | TUTORIAL.md | 39 |
1 files changed, 38 insertions, 1 deletions
diff --git a/TUTORIAL.md b/TUTORIAL.md index 0f6a21a..9c85478 100644 --- a/TUTORIAL.md +++ b/TUTORIAL.md @@ -222,6 +222,21 @@ calculate the sum of a vector of integers. Through type conversions, this works for lists too. +Coproducts +---------- + +Coproducts ("either-or -type") are instantiated with the +`coprod` operator: +```console +> (coprod (+ 1 2) Bool) +(coprod 3 Bool) : (Sum Int Bool) +> (coprod Int +) +(coprod Int +) : (Sum Int ((Int ...) -> Int)) +``` +They can be destructured with pattern matching as covered in +the next section. + + Pattern matching ---------------- @@ -272,6 +287,25 @@ myvec saved 1 : Int ``` +Coproducts are destructured with `inl` and `inr`: +```console +> (case myprod ((inl x) x) ((inr b) (if b 1 0)) (_ -1)) +2 : Int +> (case myprod ((inl 2) true) (_ false)) +true : Bool +``` +Even if when both an `inl` and `inr` arm are supplied, +a wildcard pattern is required as myslip doesn't feature an +exhaustiveness checker. That is the tradeoff for having +nesting: +```console +> (case (quote myprod 1) (((inl 2) _) true) (_ false)) +true : Bool +``` +(though with a careful rewrite of type checking for pattern +matching, at least exhaustiveness for inl/inr arms would be +fairly trivial, but that won't happen this summer) + General recursion ----------------- @@ -296,6 +330,7 @@ The factorial function could be implemented as such: )) ``` + Printing -------- @@ -323,10 +358,12 @@ These exercises are meant to make you familiar with the language. The solutions can be found in the `solutions` folder under the project root. + Exercise 1: Fibonacci sequence ------------------------------ -Write a function that calculates the n:th fibonacci number. +Write a function that calculates the n:th fibonacci number, +when n is given as the sole argument. This should make you familiar with function definitions and fixed point recursion. |