closure3.zy 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // closure3.zy https://github.com/glycerine/zygomys/issues/23
  2. // anonymous functions as closures.
  3. //
  4. (def res (let [x 123] (fn [] ((fn [] x)))))
  5. (assert (== (res) 123))
  6. (def mypkg (package "mypkg"
  7. (defn Double [x]
  8. (+ x x))
  9. (defn DoubleAll [xs]
  10. (println (Double 10))
  11. (map (fn [x] (Double x)) xs))))
  12. (def v [3, 4])
  13. (def w (mypkg.DoubleAll v))
  14. //error in __anon276:3: Error calling 'infix': Error calling 'map': symbol `Double` not found
  15. // assert that we get [6, 8] back.
  16. (assert (== (:0 w) 6))
  17. (assert (== (:1 w) 8))
  18. // check going through 3 functions
  19. (defn outer [x] (defn middle [] (defn inner [] x) inner) middle)
  20. (assert (== 7 (((outer 7)))))
  21. (assert (== 8 (((outer 8)))))
  22. // check that the let 'y' overrides the global 'y'.
  23. (def y 999)
  24. (assert (== 777 ((let [x 123] (fn [] (let [y 777] ((fn [] y))))))))
  25. // the let 'x' should override the global 'x'
  26. (def x 1)
  27. (assert (== 10 ((let [x 3] (fn [] (let [y 7] ((fn [] (+ y x)))))))))
  28. // going through 4 functions to find 'x89'
  29. (defn superOuter [x89] (defn outer [] (defn middle [] (defn inner [] x89) inner) middle) outer)
  30. (assert (== 7 ((((superOuter 7))))))
  31. // going through lots functions and lets to find 'x99'
  32. (defn ultimate [x99] (def ups -10) (let [stellar -2] (defn superDuper [] (let [z9 60] (defn outer [] (defn middle [] (def ups -8) (defn inner [] (+ z9 x99 stellar ups)) inner) middle) outer)) superDuper))
  33. (assert (== 57 (((((ultimate 7)))))))