;; recursive function (ƒ penultimate [xs] (match xs ([] ⇒ 0) ([_] ⇒ 0) ([a _] ⇒ a) (_ :: t ⇒ (penultimate t)))) (fib : Z → Z) (ƒ fib [x] (match x (0 ⇒ 0) (1 ⇒ 1) (_ ⇒ (+ (fib (- x 1)) (fib (- x 2)))))) (asserteq (fib 5) 5) (print (int2str (fib 5))) (ƒ fibc [x] (cond ((= x 0) ⇒ 0) ((= x 1) ⇒ 1) (else ⇒ (+ (fibc (- x 1)) (fibc (- x 2)))))) (asserteq (fibc 5) 5) (print (int2str (fibc 5))) (ƒ fact [n] (if (≤ n 1) 1 (* n (fact (- n 1))))) (let f5 (fact 5)) (asserteq f5 120) (print (int2str f5)) (ƒ fact-wrap [n] (let [fact (λ n → (if (≤ n 1) 1 (* n (fact (- n 1)))))] (fact n))) (let f5 (fact-wrap 5)) (print (int2str f5)) (ƒ factc [n] (cond ((≤ n 1) → 1) (else → (* n (factc (- n 1)))))) (let fc5 (factc 5)) (asserteq fc5 120) (print (int2str fc5)) ;; record data type (let profile {:name "ntha" :age 3}) (asserteq (:name profile) "ntha") (print (:name profile)) ;; destructuring (let (a . b) (4 . "d")) (let d ((4 . true) . ("test" . 'c' . a))) (let ((_ . bool) . (_ . _ . _)) d) (asserteq bool true) (print (bool2str bool)) ;; algebraic data type and pattern matching (data Tree a Empty-Tree (Leaf a) (Node (Tree a) a (Tree a))) (let t (Node (Leaf 5) 4 (Leaf 3))) (depth : (Tree α) → Z) (ƒ depth [t] (match t (Empty-Tree => 0) ((Leaf _) => 1) ((Node l _ r) => (inc (max (depth l) (depth r)))))) (asserteq (depth t) 2) (print (int2str (depth t))) (asserteq (depth (Leaf 3)) 1) (print (int2str (depth (Leaf 3)))) (asserteq (depth Empty-Tree) 0) (print (int2str (depth Empty-Tree))) ;; lambda and high-order function (let l [1 2]) (ƒ double [x] (* 2 x)) (let ll1 (map double l)) (asserteq ll1 [2 4]) (let ll2 (map (λ x => (* 2 x)) l)) (asserteq ll2 [2 4]) (let l2 [[1 2 3] [4 5 6]]) (asserteq (map len l2) [3 3]) ;; curried function (ƒ add [x y] (+ x y)) (let inc (add 1)) (let three (inc 2)) (asserteq three 3) (print (int2str three)) ;; lexical scope (let a 3) (let f (λ x → (* a x))) (let a 5) (asserteq (f 5) 15) (print (int2str (f 5))) ;; monad (let m (do Maybe (a <- (Just 3)) (b <- (Just (+ a 3))) (return (* b 3)))) (asserteq m (Just 18)) (begin (let name "ntha") (print name) (print "language")) ;; negative number (asserteq (+ -1 2) 1) ;; letrec https://github.com/zjhmale/Ntha/issues/1 (let [ev? (λ n → (match (λ n → (if (zero? n) false (ev? (dec n)))) (od? → (if (zero? n) true (od? (dec n)))))) od? (λ n → (match (λ n → (if (zero? n) true (od? (dec n)))) (ev? → (if (zero? n) false (ev? (dec n))))))] (begin (print (bool2str (ev? 11))) (print (bool2str (ev? 12))) (print (bool2str (od? 11))) (print (bool2str (od? 12))))) (id : α → α) (ƒ id [a] a) (asserteq (id 3) 3) (asserteq (id true) true) (asserteq ((λ(x: α) : α → x) 3) 3) (asserteq ((λ(x: α) : α → x) true) true) (let id' (λ(x: α) : α → x)) (asserteq (id' 3) 3) (asserteq (id' true) true) (foo : (x : Z | (> x 5)) → (z : Z | (> z 0))) (ƒ foo [x] (- x 5)) (add : (x : Z | (≥ x 3)) → (y : Z | (≥ y 3)) → (z : Z | (≥ z 6))) (ƒ add [x y] (+ x y)) (max : Z → Z → (z : Z | (∧ (≥ z x) (≥ z y)))) (ƒ max [x y] (if (≤ x y) y x))