functions.zy 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 factTc [n accum]
  17. (cond (== n 0) accum
  18. (let [newn (- n 1)
  19. newaccum (* accum n)]
  20. (factTc newn newaccum))))
  21. (assert (== 120 (factTc 5 1)))
  22. (assert (== 3628800 (factTc 10 1)))
  23. (defn sumTc [l a]
  24. (cond (empty? l)
  25. a (sumTc (rest l) (+ a (first l)))))
  26. (assert (== 0 (sumTc [] 0)))
  27. (assert (== 6 (sumTc [1 2 3] 0)))
  28. // testing anonymous dispatch
  29. ((fn [a] (assert (== a 0))) 0)
  30. // function declarations
  31. (func driveIt [a:int64 b:string] [n:int64 err:error] { (sprintf "a='%v', b='%s'\n" a b)})
  32. //{y = (driveIt 1 2)}
  33. (assert (== (driveIt 54 "hi") "a='54', b='hi'\n"))
  34. // method declarations
  35. (method [(p *Car)] DriveAway [][s:string] (return "road-road-road"))