English 中文(简体)
绘制地图记录
原标题:Distinguishing a record instance from a map
  • 时间:2012-05-14 18:51:11
  •  标签:
  • clojure

I m trying to call clojure.walk/stringify-keys on a map that might include record instances. Since stringify-keys is recursive, it attempts to convert the keys on my record, (since (map? record-var) is true) which causes an error. Is there any way to tell if a var is a record rather than just a Clojure map? I d like to provide my own implementation of stringify-keys that is record-aware.

现有<条码>星号的实施 原因如下:

(use  [clojure.walk :only [stringify-keys]])

(defrecord Rec [x])    

(let [record (Rec. "foo")
      params {:x "x" :rec record}]
    (stringify-keys params))

造成以下例外: 未支持的行动 例外 Can t 造成空洞:用户。 接收用户。 收入(单位:千美元)

最佳回答

记录似乎采用了“记录标记”接口:

user=> (defrecord Rec [x])    
user.Rec

user=> (require  [clojure.reflect :as r])
nil
user=> (:bases (r/reflect Rec))
#{java.io.Serializable clojure.lang.IKeywordLookup clojure.lang.IPersistentMap clojure.lang.IRecord java.lang.Object clojure.lang.IObj clojure.lang.ILookup java.util.Map}

user=> (instance? clojure.lang.IRecord (Rec. "hi"))
true

Update 1.6 now has the record? functions

问题回答

你可以检查每个成员的类型,看看它是否真的是一个地图或其他东西(如果其他东西被推定为记录)。

user> (type {:a 1 :b 2})
clojure.lang.PersistentArrayMap




相关问题
How to improve Clojures error messages

I ve been playing a bit with Clojure and so far is fairly impressed, but one thing that I keep running into is wierd error messages from Clojure. This comes in two forms: Java errors, like null ...

clojure rmi classpath problem

I am trying to use clojure to implement a "plugin" for some vendor supplied software. Here is a little background on the vendor supplied software. It expects me to implement a particular interface ...

Help translating this Java codeblock to Clojure?

I m getting my feet wet with Clojure, and trying to get used to functional programming. I ve been translating various imperative functions from other languages into their Clojure equivalents -- and ...

Is functional Clojure or imperative Groovy more readable?

OK, no cheating now. No, really, take a minute or two and try this out. What does "positions" do? Edit: simplified according to cgrand s suggestion. (defn redux [[current next] flag] [(if flag ...

taking java method names as function arg in clojure

All, I want to create a function that takes a symbol representing a java method and applies it to some object: (user=> (defn f [m] (. "foo" (m))) When I execute this, I get a result much ...

how to efficiently apply a medium-weight function in parallel

I m looking to map a modestly-expensive function onto a large lazy seq in parallel. pmap is great but i m loosing to much to context switching. I think I need to increase the size of the chunk of work ...

热门标签