(input) (output "3.14 12.00 0.00" "held once: a 1" "nested: -(2 + 3) = -5" "tagged only: 1") (return 0) ;;; A sum is a tag enum, a payload struct per variant that carries ;;; fields, the record holding both, and a constructor each. match is ;;; a switch over the tag whose arms bind the payload as locals, and ;;; the compiler refuses one that leaves a variant out -- which is the ;;; thing the form exists for. (include stdio.h) (sum shape ((circle ((r float))) (rect ((w float) (h float))) (empty ()))) (fn area ((s shape)) float (var out float 0.0) (match s ((circle (r)) (= out (* 3.14159 r r))) ((rect (w h)) (= out (* w h))) ((empty ()) (= out 0.0))) (return out)) ;;; Recursive through pointers, because a value cannot hold itself (sum expr ((lit ((v float))) (neg ((e (* const expr)))) (add ((l (* const expr)) (r (* const expr)))))) (fn eval ((self (* const expr))) float (match (* self) ((lit (v)) (return v)) ((neg (e)) (return (- (eval e)))) ((add (l r)) (return (+ (eval l) (eval r)))))) (fn show ((self (* const expr))) void (match (* self) ((lit (v)) (printf "%g" v)) ((neg (e)) (printf "-") (show e)) ((add (l r)) (printf "(") (show l) (printf " + ") (show r) (printf ")")))) ;;; No fields anywhere: the record is the tag alone, with no union (sum light ((red ()) (green ()))) (fn mk-shape () shape (return (shape/circle 1.0))) (sum held ((a ((x int) (y int))) (b ()))) (fn mk-held () held (return (held/a 1 2))) (pub fn main () int (printf "%.2f %.2f %.2f\n" (area (mk-shape)) (area (shape/rect 3.0 4.0)) (area (shape/empty))) ;; the scrutinee is a call, so it is read into a local once (match (mk-held) ((a (x _)) (printf "held once: a %d\n" x)) ; `_' drops y (else (printf "held once: other\n"))) (var two expr (expr/lit 2.0)) (var three expr (expr/lit 3.0)) (var both expr (expr/add (& two) (& three))) (var e expr (expr/neg (& both))) (printf "nested: ") (show (& e)) (printf " = %g\n" (eval (& e))) (var l light (light/green)) (match l ((red ()) (printf "tagged only: 0\n")) ((green ()) (printf "tagged only: 1\n"))) (return 0))