根据 http://www.assembla.com/spaces/clojure/wiki/Datatypes
我应该能够在 lein 回复中输入以下内容:
(deftype Bar [abcde])
(def b (小节 1 2 3 4 5))
但是,当我这样做时,我得到以下输出:
java.lang.Exception:需要 var,但 Bar 映射到类 user.Bar (NO_SOURCE_FILE:31)
我很困惑,并且是 clojure 的完全新手,感谢所有帮助!
注意:在标准 clojure repl 中尝试了相同的代码并遇到了相同的问题。
回答:嗯,我通过一些额外的搜索回答了我自己的问题。结果发现样品很糟糕。实例化 Bar 的正确方法是:
(def b (小节 1 2 3 4 5))
.在 Bar 的末尾,这个用法很重要。仍然不太明白为什么(所以各位 clojure 专家如果有时间请详细说明,因为我想知道详细信息;))。
谢谢大家!
Per http://www.assembla.com/spaces/clojure/wiki/Datatypes
I should be able to type the following into a lein reply:
(deftype Bar [a b c d e])
(def b (Bar 1 2 3 4 5))
However when I do I get the following output:
java.lang.Exception: Expecting var, but Bar is mapped to class user.Bar (NO_SOURCE_FILE:31)
I'm confused and am a complete newb to clojure all help is appreciated!
NOTE: Tried same code in standard clojure repl and get same problem.
ANSWER: Well I answered my own question with a little additional searching. Turns out the sample was bad. The correct way to instantiate Bar would be:
(def b (Bar. 1 2 3 4 5))
The . at the end of Bar in that usage is important. Still don't quite understand why (so you clojure experts please elaborate if you have time since I would like to know the details ;) ).
Thanks everyone!
发布评论
评论(2)
我对 deftype 不太熟悉,但据我所知,您需要一个点来实例化类型,请尝试以下操作:
注意它不是
Bar
,而是Bar .
。请参阅此处的示例:(new foo ...)
而不是(foo. ...)
)该线程似乎表明这是
deftype
中的更改:或者,换句话说,您链接到的页面上的文档似乎已经过时了。
希望这有帮助。
I'm not that familiar with
deftype
, but from what I see you need a point to instantiate a type, try this:Note it's not
Bar
, butBar.
. See examples e.g. here:(new foo ...)
instead of(foo. ...)
)This thread seems to indicate this was a change in
deftype
:or, to put it the other way around, the docs on the page you link to seem outdated.
Hope this helps.
有两种方法可以实现您想要做的事情。首先,让我们看一下
deftype
示例。在这里,您会注意到一些事情。如前所述,您需要“.”。实例化您的类型。此外,您无法获得关键字访问(“:”符号),只能获得字段访问(同样,使用“.”)。
另一种方法是使用
defrecord
定义记录:这为您提供了字段和关键字访问权限。如果您决定让其中一个字段包含另一条记录,那么这种访问也很容易嵌套。
There are two ways of achieving what you are attempting to do. First, let's go over the
deftype
example.You'll notice a few things, here. As was mentioned, you need the "." to instantiate your type. Furthermore, you don't get keyword access (":" notation), only field access (again, with a ".").
The other method is by defining a record with
defrecord
:This gives you both field and keyword access. This access is easily nested, as well, should you decide to have one of your fields contain another record.