Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a For loop in Clojure

I'd like to implement this little code in Clojure, but I am struggling:

struct mystruct {    int id;    int price; };  mystruct mydata[10];  for (int i=0; i<10; i++) {   myfunction(mydata[i].id, mydata[i].price);   //other things... } 

I am a beginner with Clojure and it's really complicated for me to do something simple like this, but I am really trying to learn as much as possible as I know that there are great advantages with Clojure such as using refs...

I would really appreciate it if somebody could help me. Thanks!!

like image 256
nuvio Avatar asked Apr 02 '12 18:04

nuvio


People also ask

Do while loops Clojure?

The process is repeated starting from the evaluation of the condition in the while statement. This loop continues until the condition evaluates to false. When the condition is false, the loop terminates. The program logic then continues with the statement immediately following the while statement.

What is SEQ in Clojure?

Clojure defines many algorithms in terms of sequences (seqs). A seq is a logical list, and unlike most Lisps where the list is represented by a concrete, 2-slot structure, Clojure uses the ISeq interface to allow many data structures to provide access to their elements as sequences.

How do you define a list in Clojure?

List is a structure used to store a collection of data items. In Clojure, the List implements the ISeq interface. Lists are created in Clojure by using the list function.


1 Answers

One way to translate an imperative for loop to Clojure is to use the for macro.

(for [i (range 10)] (inc i)) 

The above function will return all the numbers from 0 to 9 incremented by 1. However, it appears you simply want to iterate over a sequential collection and use each item. If that's all that you need, then you don't need to reference an index value, instead you can reference each item directly.

(for [d my-vec-of-data] (my-function d)) 

However, for this simple case, the map function would probably be a better choice because it is designed to invoke functions with arguments from collections. The following example is equivalent to the use of for above.

(map my-function my-vec-of-data) 

Both map and for return a collection of values made up of the values returned by my-function. This is because Clojure's data structures are immutable, so it's necessary to have a new collection returned. If that isn't what you need or if your function has side effects, you could use doseq instead of for, which returns nil.

like image 129
Jeremy Avatar answered Sep 25 '22 13:09

Jeremy