Clojure:map作为函数参数

时间:2014-12-16 10:38:42

标签: clojure

我试图从书中运行一些代码"使用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: Don't know how to create ISeq from: clojure.lang.Symbol, compiling:(picture_gallery/routes/upload.clj:32:1)

为什么?

1 个答案:

答案 0 :(得分:5)

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

  1. 从传递的参数中取出:filename键,并将其值绑定到filename
  2. 将整个参数保留为file
  3. 所以如果你通过:

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

    作为参数,函数范围中的filename将等于foofile将等于整个哈希映射。

    参考文献: