Mercurial > repos > other > SevenLanguagesInSevenWeeks
changeset 80:a83309cdf5d3
Add details of Clojure's loop recursion approach
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Thu, 06 Jun 2019 20:26:42 +0100 |
parents | 29025305bbb7 |
children | 0f57e5c2ae82 |
files | 6-Clojure/README.txt 6-Clojure/loop_recur.clj |
diffstat | 2 files changed, 20 insertions(+), 1 deletions(-) [+] |
line wrap: on
line diff
--- 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. +
--- /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