简体   繁体   English

使用 for 循环在宏中运行主体与在主体上映射 `exec' 之间的区别

[英]Difference between using a for loop to run a body in a macro versus mapping `exec' over the body

What's the difference between using (map exec ~body) versus (for [node ~body] node) in the following code?在以下代码中使用(map exec ~body)(for [node ~body] node)有什么区别?

(defmacro with-cwd [dir #* body]
          `(let [ cwd (.cwd Path) ]
               (try (.chdir os ~dir)

                    ;; Should I use this?
                    (map exec ~body)

                    ;; Or this?
                    (for [node body] node)

                    ;; UPDATE: Or this...
                    (do ~@body)

                    ;; UPDATE: Or this?
                    ~@body

                    (finally (.chdir os cwd)))))

Which one is safer, or are they both alright?哪个更安全,或者它们都好吗? exec() doesn't seem to run strings of code anymore, which I believe was changed in Python 3 , so is it alright now? exec()似乎不再运行代码字符串了,我相信这在Python 3中已经改变了,所以现在可以了吗? I just want to use something more concise;我只是想使用更简洁的东西; I'm not good at naming variables.我不擅长命名变量。

UPDATE: I also just realized (do ~@body) is also an option, which seems to be what most people do;更新:我也刚刚意识到(do ~@body)也是一种选择,这似乎是大多数人所做的; what is the difference between that and simply doing ~@body ?那和简单地做~@body有什么区别?

What's the difference between using (map exec ~body) versus (for [node ~body] node)使用(map exec ~body)(for [node ~body] node)有什么区别

map collects results whereas for ignores them. map收集结果,而for忽略它们。 exec runs a string of Python code or a Python code object, so it probably won't do anything useful with whatever the return value of body is. exec运行一串 Python 代码或 Python 代码对象,因此无论body的返回值是什么,它都可能不会做任何有用的事情。

exec() doesn't seem to run strings of code anymore exec()似乎不再运行代码字符串

It does.确实如此。 You gotta read the documentation, my man.你必须阅读文档,我的男人。

(do ~@body) is also an option, which seems to be what most people do; (do ~@body)也是一个选项,这似乎是大多数人所做的; what is the difference between that and simply doing ~@body ?那和简单地做~@body有什么区别?

In this position, nothing, because try already evaluates its body forms in sequence and returns the last one, just like do .在这个位置,什么都没有,因为try已经按顺序计算了它的主体形式并返回最后一个,就像do

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM