File tree Expand file tree Collapse file tree 2 files changed +21
-1
lines changed
Expand file tree Collapse file tree 2 files changed +21
-1
lines changed Original file line number Diff line number Diff line change @@ -520,7 +520,7 @@ as macro
520520* TODO time
521521* DONE to-array
522522* TODO to-array-2d
523- * TODO trampoline
523+ * DONE trampoline
524524* transient
525525* DONE tree-seq
526526* DONE true?
Original file line number Diff line number Diff line change @@ -2831,6 +2831,22 @@ reduces them without incurring seq initialization"
28312831 (swap! mem assoc args ret)
28322832 ret)))))
28332833
2834+ (defn trampoline
2835+ " trampoline can be used to convert algorithms requiring mutual
2836+ recursion without stack consumption. Calls f with supplied args, if
2837+ any. If f returns a fn, calls that fn with no arguments, and
2838+ continues to repeat, until the return value is not a fn, then
2839+ returns that non-fn value. Note that if you want to return a fn as a
2840+ final value, you must wrap it in some data structure and unpack it
2841+ after trampoline returns."
2842+ ([f]
2843+ (let [ret (f )]
2844+ (if (fn? ret)
2845+ (recur ret)
2846+ ret)))
2847+ ([f & args]
2848+ (trampoline #(apply f args))))
2849+
28342850(defn rand
28352851 " Returns a random floating point number between 0 (inclusive) and
28362852 n (default 1) (exclusive)."
@@ -3450,6 +3466,10 @@ reduces them without incurring seq initialization"
34503466
34513467 ; ; split-with
34523468 (assert (= [[1 2 3 ] [4 5 ]] (split-with (partial >= 3 ) [1 2 3 4 5 ])))
3469+
3470+ ; ; trampoline
3471+ (assert (= 10000 (trampoline (fn f [n] (if (>= n 10000 ) n #(f (inc n)))) 0 )))
3472+
34533473 :ok
34543474 )
34553475
You can’t perform that action at this time.
0 commit comments