Stuck in a Clojure Cycle, Must Be Guided

I'm stuck in a Clojure loop and you need help to get out.

First I want to define a vector

(def lawl [1 2 3 4 5]) 

I do

 (get lawl 0) 

And get a "1" in return. Now, I want a loop that gets every number in the vector, so I do:

 (loop [i 0] (if (< i (count lawl)) (get lawl i) (recur (inc i)))) 

In my mind it is assumed that the value of i is nil, then, if I am lower, then the lawl vector counts, it should get each lawl value, and then increase the i-variable from 1 and try again, getting the next value in the vector.

However, this does not work, and I spent some time trying to get it to work and was completely stuck, I would be happy to help. I also tried changing the “if” to “when” with the same result, it does not provide any data, REPL just goes on a new line and blinks.

EDIT: Fixed repetition.

+4
source share
2 answers

You need to think about what “get every lawl value” lawl . Your get call really "gets" the appropriate value, but since you never do anything with it, it is simply discarded; Bozidar’s suggestion to add println is good and will allow you to see that the loop really has access to all lawl elements (just replace (get ...) with (println (get ...)) , after fixing (inc) => (inc i) thing mentioned by Bozidar).

However, if you just want to do something with each number, in turn, loop / recur not a good way to do this at all. Here are some others:

 ;;; do some side-effecty thing to each number in turn: (dotimes [i (count lawl)] (println (str i ": " (lawl i)))) ; you don't really need the get either ;; doseq is more general than dotimes, but doesn't give you equally immediate ;; acess to the index (doseq [n lawl] (println n)) ;;; transform the lawl vector somehow and return the result: ; produce a seq of the elements of lawl transformed by some function (map inc lawl) ; or if you want the result to be a vector too... (vec (map inc lawl)) ; produce a seq of the even members of lawl multiplied by 3 (for [n lawl :when (even? n)] (* n 3)) 

This is just the beginning. For a good tour of the Clojure Standard Library, see the article Clojure - Functional Programming for the JVM by Mark Volkman.

+7
source

(recur (inc)) should be (recur (inc i))

Even if this code simply returns 1 at the end, if you want to specify a number that you could add to the expression to print :-) Based on index-based scripts, no scripts are required at all.

 (loop [list [1 2 3 4 5] ] (if (empty? list) (println "done") (do (println (first list)) (recur (rest list))))) 
+3
source

Source: https://habr.com/ru/post/1315316/


All Articles