Clojure中doseq和for的区别 [英] Difference between doseq and for in Clojure

查看:19
本文介绍了Clojure中doseq和for的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Clojure 中的 doseq 和 for 有什么区别?什么情况下您会选择使用一种而不是另一种?

What's the difference between doseq and for in Clojure? What are some examples of when you would choose to use one over the other?

推荐答案

区别在于 for 构建了一个惰性序列并返回它,而 doseq 用于执行方——效果并返回 nil.

The difference is that for builds a lazy sequence and returns it while doseq is for executing side-effects and returns nil.

user=> (for [x [1 2 3]] (+ x 5))
(6 7 8)
user=> (doseq [x [1 2 3]] (+ x 5))
nil
user=> (doseq [x [1 2 3]] (println x))
1
2
3
nil

如果要基于其他序列构建新序列,请使用 for.如果您想根据某些序列中的元素产生副作用(打印、写入数据库、发射核弹头等),请使用 doseq.

If you want to build a new sequence based on other sequences, use for. If you want to do side-effects (printing, writing to a database, launching a nuclear warhead, etc) based on elements from some sequences, use doseq.

这篇关于Clojure中doseq和for的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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