How do I implement foreach loop in clojure?

℡╲_俬逩灬. 提交于 2019-12-21 03:27:42

问题


Implementing a for loop in clojure seems to be easy, but how can I implement a foreach statement that reads each element in the list(vector) and does something?

like this...

(foreach i list expression)

Thanks in advance!


回答1:


Just replace for with doseq and you're all set. Don't use map, which is just as lazy as for.




回答2:


map is the functional equivalent of foreach, whereas doseq is for imperative programming with side-effects.

map takes a function f and a seqable collection coll and returns the lazily-evaluated result of applying f to each element in the collection.

Example:

(map inc [1 2 3 4])
=> (2 3 4 5)

(map (fn [x] (* x 2)) [1 2 3 4])
=> (2 4 6 8)

(map dec (take 5 (range)))
=> (-1 0 1 2 3)


来源:https://stackoverflow.com/questions/5285822/how-do-i-implement-foreach-loop-in-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!