functions.glisp 779 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. (assert (= 3
  2. ((fn [a b] a) 3 2)))
  3. (defn add4 [a] (+ a 4))
  4. (assert (= 7 (add4 3)))
  5. ; testing recursion
  6. (defn fact [n]
  7. (cond (= n 0) 1 (* n (fact (- n 1)))))
  8. (assert (= 120 (fact 5)))
  9. (assert (= 3628800 (fact 10)))
  10. (defn sum [l]
  11. (cond (empty? l)
  12. 0 (+ (first l) (sum (rest l)))))
  13. (assert (= 0 (sum [])))
  14. (assert (= 6 (sum [1 2 3])))
  15. ; testing tail recursion
  16. (defn fact-tc [n accum]
  17. (cond (= n 0) accum
  18. (let [newn (- n 1)
  19. newaccum (* accum n)]
  20. (fact-tc newn newaccum))))
  21. (assert (= 120 (fact-tc 5 1)))
  22. (assert (= 3628800 (fact-tc 10 1)))
  23. (defn sum-tc [l a]
  24. (cond (empty? l)
  25. a (sum-tc (rest l) (+ a (first l)))))
  26. (assert (= 0 (sum-tc [] 0)))
  27. (assert (= 6 (sum-tc [1 2 3] 0)))
  28. ; testing anonymous dispatch
  29. ((fn [a] (assert (= a 0))) 0)