# HG changeset patch # User IBBoard # Date 1559849202 -3600 # Node ID a83309cdf5d35e4d5c06d11a150cd1f9727a61e5 # Parent 29025305bbb7441f78412af107f2811e046020eb Add details of Clojure's loop recursion approach diff -r 29025305bbb7 -r a83309cdf5d3 6-Clojure/README.txt --- a/6-Clojure/README.txt Sat Jun 01 20:10:59 2019 +0100 +++ b/6-Clojure/README.txt Thu Jun 06 20:26:42 2019 +0100 @@ -79,4 +79,7 @@ As well as the map function, there's "apply" and "filter". -Also, some helper functions exist, like "odd?". \ No newline at end of file +Also, some helper functions exist, like "odd?". + +Functional languages do lazy tail recursion. Unless they're Clojure, because the JVM doesn't support it. Clojure does it with a "loop" and a "recur" function. "loop" takes x and y with initial values and a function to call. See loop_recur.clj. + diff -r 29025305bbb7 -r a83309cdf5d3 6-Clojure/loop_recur.clj --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/6-Clojure/loop_recur.clj Thu Jun 06 20:26:42 2019 +0100 @@ -0,0 +1,16 @@ +; Define a function that takes a single parameter (which needs to be a list-like thing) +(defn size [_vec] + ; Loop over _list with starting value of our parameter and _size with starting value of 0 + (loop [_list _vec, _size 0] + ; Code to execute is just an "if" block + (if (empty? _list) + ; if our list is empty, return the size + _size + ; else call loop's body again (the "if" block) but this time pass in + ; the tail of the list and the incremented size counter + (recur (rest _list) (inc _size))))) + +(println (size [1 2 3 5 7 9])) +(println (size (list 1 2 3))) +(println (size #{})) +(println (size #{1})) \ No newline at end of file