【问题标题】:Is it possible to apply two functions to a list in Clojure?是否可以将两个函数应用于 Clojure 中的列表?
【发布时间】:2020-02-17 17:43:13
【问题描述】:

我想调用我编写的函数并将元素添加到哈希映射中。我想知道如何将这两个函数应用于同一个列表。

例如,我有以下 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

【问题讨论】:

  • 需要更多细节。
  • 那……离工作代码还很远,而且……仍然不清楚你想要什么。

标签: clojure


【解决方案1】:

类似:

(assoc {} your-key (your-func your-list))

【讨论】:

  • 这可行,但我希望列表中的元素成为地图中的键,但我也想在它们上调用我的函数
  • 这个怎么样:(reduce (fn [acc item] (assoc acc item (your-function your-list))) {} your-list)
【解决方案2】:

你在寻找类似的东西

(into {} (for [x your-list] [x (val-func x)])

=> (into {} (for [x [1 2 3]] [x (str x)]))
{1 "1", 2 "2", 3 "3"}

或者一个也有按键功能的:

=> (into {} (for [x [1 2 3]] [(str x) (* x x)]))
{"1" 1, "2" 4, "3" 9}

【讨论】:

  • 我喜欢 for 循环的想法,但是我不知道如何在同一个 for 循环中执行多个操作。
【解决方案3】:

使用when,您可以执行多个操作而无需返回。

例如

(when condition
    (assoc {} key value)
    (recursive-func arg1 arg2)
)

【讨论】:

    猜你喜欢
    • 2015-03-09
    • 1970-01-01
    • 2018-12-19
    • 2014-06-01
    • 2013-09-30
    • 2021-05-10
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    相关资源
    最近更新 更多