【问题标题】:Clojure single function argument of large hash-map?大型哈希映射的Clojure单个函数参数?
【发布时间】:2015-03-12 16:32:57
【问题描述】:

我正在尝试解析返回 CSV 数据(没有标题)的旧 API 的结果。 parse-response 函数效果很好,但是当我尝试使用 verify-response 检查时,它会因 ArityException Wrong number of args (0) passed to: PersistentHashMap 而失败。如何通过检查关键字段并在无效时创建替代错误哈希映射的函数传递哈希映射?

(def response-fields
  [:response_code :response_text
   :address :city :state :zip_code :country
   :phone :fax :email
   :first_name :last_name :company  
   :special_instructions :SpecialCode
   ])

(defn parse-response
  "One line CSV file"
  [response]
  (zipmap response-fields
    (first (csv/read-csv (:body response)))))

(defn verify-response
  "Get response if code is valid"
  [response-map]
  (cond (some? (:response_code response-map)) (response-map)
        :else
        {:response_code "911"
         :response_text "API Failure"}))

【问题讨论】:

  • 看起来像响应映射周围的一组错误的括号。
  • 太好了,@Alex 就是这样。谢谢!
  • @Alex,这应该是一个答案并被接受,所以这个问题不会显示为“未回答”。

标签: dictionary clojure hashmap argument-passing destructuring


【解决方案1】:

verify-response 的正文中,response-map 周围有一组错误的括号。 (response-map) 将映射调用为不带参数的函数。 Clojure 中的映射实现了IFn 接口;可以使用 1 或 2 个参数调用它们以对自己进行查找,并使用可选的默认值。

user=> ({:a 1} :a)
1
user=> ({:a 1} :b :foo)
:foo
user=> ({:a 1})
;; ArityException Wrong number of args (0) passed to: PersistentArrayMap

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 2017-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多