我应该如何建立一个列表并在clojure中返回它?
我还在学习这个外星的功能范例 我如何用Clojure和函数式的方式编写以下代码? 假设该缺失部分已在其他地方定义,其行为如注释中所述。 这里是Python,我很熟悉我应该如何建立一个列表并在clojure中返回它?,clojure,functional-programming,porting,Clojure,Functional Programming,Porting,我还在学习这个外星的功能范例 我如何用Clojure和函数式的方式编写以下代码? 假设该缺失部分已在其他地方定义,其行为如注释中所述。 这里是Python,我很熟悉 usernames = [] # just the usernames of all the connections I want to open. cancelfunctions = {} # this global contains anonymous functions to cancel connections, keyed
usernames = []
# just the usernames of all the connections I want to open.
cancelfunctions = {}
# this global contains anonymous functions to cancel connections, keyed by username
def cancelAll():
for cancel in cancelfunctions.values():
cancel()
def reopenAll():
cancelfunctions = {}
for name in usernames:
# should return a function to close the connection and put it in the dict.
cancelfunctions[name] = openConnection()
我真正需要知道的是如何建立一个新的回调命令,就像在REPOWEALL函数中一样,但我在这里包含了更多的上下文,因为我可能犯下了某种函数范式的暴行,而您很可能希望修复整个程序。:) 在Clojure中构建数据结构通常涉及
reduce
,它将一系列输入提供给一个函数,该函数累积最终返回值。下面是两种编写函数的方法,该函数将用户名映射到打开连接的返回值
;; Using reduce directly
(defn reopen-all [usernames]
(reduce
(fn [m name] (assoc m name (open-connection)))
{} usernames))
;; Using into, which uses reduce under the hood
(defn reopen-all [usernames]
(into {} (for [name usernames]
[name (open-connection)])))
请注意,这两个函数返回一个值,不会像Python代码那样改变全局状态。全局状态本身并不坏,但将价值生成与状态操纵分开是好的。对于state,您可能需要一个atom
:
(def usernames [...])
(def cancel-fns (atom nil))
(defn init []
(reset! cancel-fns (reopen-all usernames)))
为了完整起见,这里有取消所有:
(defn cancel-all []
(doseq [cancel-fn (vals @canel-fns)]
(cancel-fn)))
以下是python中的函数方法:
def reopen(usernames):
return dict((name, openConnection()) for name in usernames)
在尝试使用函数式语言之前,您可能会发现在python中“翻译”成函数式风格更容易。我知道这可能不合适,但当我看到您对“”的引用时,我忍不住分享了。