Clojure:重复使用不同数量的匿名函数

Clojure: Recur anonymous function with different arity

类似于 我想以不同的数量重复出现。但在我的例子中,我通过 let 定义函数,因为我想使用 let (file-list) 中的另一个值而不传递它:

(let [file-list (drive/list-files! google-drive-credentials google-drive-folder-id)
      download-file (fn
                      ([name]
                       (download-file ; <-- attempt to recur
                         name
                         (fn []
                           (throw
                             (ex-info
                               (str name " not found on Google Drive"))))))
                      ([name not-found-fn]
                       (if-let [file (->> file-list
                                          (filter #(= (:original-filename %)
                                                      name))
                                          first)]
                         (drive/download-file! google-drive-credentials file)
                         (not-found-fn))))]
  ;; #
  )

我收到这个错误:Exception in thread "main" java.lang.RuntimeException: Unable to resolve symbol: download-file in this context

您可以给 fn 一个本地名称:

(let [download-file (fn download-file
                      ([name] (download-file name (fn ...))))

你也可以使用 letfn:

(letfn [(download-file
          ([name] (download-file name (fn ...)))
          ([name not-found-fn] ...)])

为了使异常错误消息更具可读性,我经常将 -fn 附加到内部函数名称,如下所示:

(let [download-file (fn download-file-fn [name] ...) ]
   <use download-file> ...)