flan/test/programs/when-value.flan

74 lines
2.4 KiB
Plaintext

;;;; A when whose value is kept answers an Option: Some of its body when the
;;;; test holds, None when it does not. As a statement it answers nothing.
;;;; Where a dyn is wanted it answers the body or nil, since dyn has no
;;;; Option. A body that is already an Option is that Option, flattened one
;;;; level (decision 140), unless an Option of it is what is wanted.
(defn show [o (Option i32)] ()
(match o (Some v) (println v) None (println "none")))
;; Returned: the return type is the want.
(defn half [n i32] (Option i32) (when (= 0 (% n 2)) (/ n 2)))
;; An (Option (Option i32)) is wanted, so the body is Some of it and the
;; failed test is the outer None.
(defn wrap [c bool o (Option i32)] (Option (Option i32)) (when c o))
;; Flattened: None from the body and a failed test are one answer.
(defn flat [c bool o (Option i32)] (Option i32) (when c o))
(defn level [oo (Option (Option i32))] ()
(match oo
(Some o) (match o (Some v) (println v) None (println "some none"))
None (println "none")))
;; Dyn: the body or nil.
(defn dyn-when [x] dyn (when x 5))
;; An if-let arm that returns stays Never; the when after it decides.
(defn early [a (Option i32)] (Option i32)
(if-let [(Some x) a] (return None) (when true 3)))
;; A lambda's last form is kept at the return type its position wants.
(defn call-it [f (Fn [] (Option i32))] () (show (f)))
;; A kept cond with no :else is a when over several tests.
(defn pick [n i32] (Option i32) (cond (= n 1) 10 (= n 2) 20))
(defn dpick [n] dyn (cond (= n 1) "a" (= n 2) "b"))
(defn main [] ()
(show (half 10))
(show (half 7))
;; A let's value.
(let [a (when (> 3 2) 42)
b (when (> 2 3) 42)]
(show a)
(show b))
;; An argument.
(show (when true 9))
(level (wrap true (Some 1)))
(level (wrap true None))
(level (wrap false (Some 1)))
(show (flat true (Some 4)))
(show (flat true None))
(show (flat false (Some 4)))
(let [o (the (Option i32) (Some 8))
f (when true o)]
(show f))
(println (dyn-when true))
(println (dyn-when nil))
(show (early None))
(show (early (Some 1)))
(call-it (fn [] (when true 6)))
(call-it (fn [] (when false 6)))
(show (pick 2))
(show (pick 3))
(let [k (cond (> 3 5) 1 (> 3 2) 2)] (show k))
(println (dpick 1))
(println (dpick 9))
(cond (> 3 5) (println "no") (> 3 2) (println "cond stmt"))
;; Statements, unchanged.
(when true (println "ran"))
(when false (println "not run"))
(println "end"))