如何在 Clojure 中实现 For 循环 [英] How to implement a For loop in Clojure

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

问题描述

我想在 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...
}

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

如果有人能帮助我,我将不胜感激.谢谢!!

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

推荐答案

将命令式 for 循环转换为 Clojure 的一种方法是使用 for 宏.

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

然而,对于这种简单的情况,map 函数可能是更好的选择,因为它旨在调用带有集合参数的函数.下面的例子相当于上面的for的使用.

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)

mapfor 都返回由 my-function 返回的值组成的值集合.这是因为 Clojure 的数据结构是不可变的,所以需要返回一个新的集合.如果这不是您所需要的,或者您的函数有副作用,您可以使用 doseq 而不是 for,后者返回 nil.

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 中实现 For 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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