代码示例中的错误:"Can only recur from tail position"

Error in Code Example: "Can only recur from tail position"

follwing函数使用通道实现映射功能,类似于普通clojure的行为map

我从 Paul Butcher 的七周七并发模型一书中获得了这个代码示例。这段代码似乎已经过时了,因为在执行它时,它会抛出以下错误消息。有谁知道如何修复该功能?

错误信息:

Can only recur from tail position {:exprs nil, :form (recur)

代码:

   (defn map-chan [f from]
    (let [to (chan)]
     (go-loop []
      (when-let [x (<! from)]
       (>! to (f x))
       (recur))
     (close! to))
    to))

我的第一次修复尝试: // 与原点相同的错误

(defn map-chan [f from]
  (go-loop []
         (do
          (let [to (chan)]
          (when-let [x (<! from)]
           (>! to (f x))
           (recur))))
          (close! to)
         )
 )

确实不行; errata to the book.

中也提到了这一点

您可以将 close! 函数调用放在循环之外,以确保 recur 处于最终位置(请注意,您必须使用 goloop 来代替go-loop 的):

(defn map-chan [f from]
  (let [to (chan)]
    (go (loop []
          (when-let [x (<! from)]
            (>! to (f x))
            (recur)))
        (close! to))
    to))