gpt4 book ai didi

Clojure:映射作为函数参数

转载 作者:行者123 更新时间:2023-12-05 08:58:02 26 4
gpt4 key购买 nike

我正在尝试运行“使用 Clojure 进行 Web 开发”一书中的一些代码。有一个我无法理解的功能:

(defn handle-upload [{:keys [filename] :as file}]
(upload-page
(if (empty? filename)
"please select a file to upload"
(try
(upload-file (gallery-path) file)
(save-thumbnail file)
(db/add-image (session/get :user) filename)
(image {:height "150px"}
(str "/img/"
(session/get :user)
"/"
thumb-prefix
(url-encode filename)))
(catch Exception ex
(str "error uploading file " (.getMessage ex)))))))

在哪里

(defn upload-page [info]
(layout/common
[:h2 "Upload an image"]
[:p info]
(form-to {:enctype "multipart/form-data"}
[:post "/upload"]
(file-upload :file)
(submit-button "upload"))))

函数handle-upload的参数是什么意思?

改变之后

(defn handle-upload [{:keys [filename] :as file}]
...

(defn handle-upload [{:keys filename :as file}]
...

我收到一条错误消息:

java.lang.IllegalArgumentException:不知道如何从 clojure.lang.Symbol 创建 ISeq,编译:(picture_gallery/routes/upload.clj:32:1)

为什么?

最佳答案

{:keys [filename] :as file} 表示:

  1. 从传递的参数中获取 :filename 键并将其值绑定(bind)到 filename
  2. 将整个参数保留为 文件

所以如果你通过了:

{:filename "foo"
:somethingelse "bar"}

作为参数,那么函数作用域中的filename 将等于foo 并且file 将等于整个 HashMap .

引用资料:

关于Clojure:映射作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27502643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com