[英]Is it possible to apply two functions to a list in Clojure?
我想调用我编写的 function 并将元素添加到哈希映射中。 我想知道如何将这两个函数应用于同一个列表。
例如,我有以下 DFS 递归代码的代码
(defn dfs-recur [maze curr-loc goal-loc parent]
(;;Want to add elements of the following list to the parent map
;; and call dfs-recur on them
(def unvisited (filter #(not (contains? parent %)) (get-neighbors maze curr-loc)))
maze)
如果我要在 python 中实现它,它看起来像这样。 问题是,我不明白如何在 Clojure 中一次在 for 循环中做所有 4 件事
def dfs-recur(maze, curr-loc, goal-loc, parent):
neighbors = get-neighbors(maze, curr-loc)
for i in neighbors:
if i in parent:
break;
parent[i] = curr-loc
if i == goal-loc:
break;
parent = dfs-recur(maze, i, goal-loc, parent)
return parent
就像是:
(assoc {} your-key (your-func your-list))
你在寻找类似的东西
(into {} (for [x your-list] [x (val-func x)])
=> (into {} (for [x [1 2 3]] [x (str x)]))
{1 "1", 2 "2", 3 "3"}
或者一个带有 function 的钥匙也可以:
=> (into {} (for [x [1 2 3]] [(str x) (* x x)]))
{"1" 1, "2" 4, "3" 9}
when
您可以执行多个操作而无需返回时使用。
例如
(when condition
(assoc {} key value)
(recursive-func arg1 arg2)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.