如何实现对于循环的Clojure [英] How to implement a For loop in Clojure

查看:146
本文介绍了如何实现对于循环的Clojure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现Clojure中的这个小code,但我奋力:

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...
}

我使用Clojure一个初学者,它真的复杂,我简单做一下这样的,但我真的想了解尽可能多的,因为我知道有使用Clojure很大的优势,如使用参...

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...

我真的AP preciate,如果有人可以帮助我。谢谢!

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

推荐答案

翻译的当务之急循环Clojure的一种方法是使用宏。

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

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

上面的函数将返回从0到9加1。但是,看来你只是想遍历顺序收集和使用的每一个项目的所有号码。如果这是你需要的一切,那么你就需要引用索引值,而不是直接引用的每个项目。

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)

两者地图返回由由我的功能。这是因为Clojure的数据结构是不变的,所以它需要有一个新的集合返回。如果这不是你所需要的,或如果你的函数有副作用,你可以使用 doseq 而不是,返回

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.

这篇关于如何实现对于循环的Clojure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆