如何在 clojure 中将静态方法传递给 comp?
似乎我在访问 comp 中的 Integer.parseInt
时遇到问题。我可以像这样正常访问它:
user=> (Integer/parseInt "123")
123
但如果我把它放在 comp 中,我会收到一个错误:
user=> (def vect-to-int (comp Integer/parseInt (partial apply str)))
java.lang.Exception: Unable to find static field: parseInt in class java.lang.Integer (NO_SOURCE_FILE:3)
在我看来,它在应该寻找方法时试图在 Integer 上找到一个字段。我怎样才能像这样使用Integer.parseInt
?有没有更好的方法将字符向量转换为int?
It seems as though I'm having problems accessing Integer.parseInt
in comp. I can access it normally like this:
user=> (Integer/parseInt "123")
123
But if I put it in comp, I get an error:
user=> (def vect-to-int (comp Integer/parseInt (partial apply str)))
java.lang.Exception: Unable to find static field: parseInt in class java.lang.Integer (NO_SOURCE_FILE:3)
It sounds to me like it's trying to find a field on Integer when it should be looking for a method. How can I use Integer.parseInt
like this? And is there a better way to convert a vector of chars into an int
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Clojure 函数是 java 方法,但 java 方法不是 clojure 函数 例如,Clojure 函数具有元数据等。如果你想使用一个调用 Clojure 函数的 java 方法,那么你有两种选择来包装它,
memfn
和fun 或 #( )
memfn 已经过时了将 java 方法包装在 clojure 函数中的函数(知道它存在是件好事,即使它不经常使用)。包装 java 方法的普遍接受的方法是:或 对于静态方法
Clojure functions are java methods but java methods are not clojure functions For instance Clojure functions have meta-data and such. If you want to use a java method where a Clojure function is called for then you have two choices in wrapping it up,
memfn
andfun or #( )
memfn is an obsolete function that wrapped up a java method in a clojure function (its good to know it exists even if its not used often). The generally accepted way to wrap up java methods is:or for static methods
或者
partial
和comp
在 Clojure 中通常不像使用#()
来创建匿名 fn 那样简洁。就我个人而言,我会这样写:您可以使用普通的
def
来完成此操作,但是使用def
而不是defn
会得到什么,真的?使用def
掩盖了您正在定义函数的事实。defn
还为您设置def
没有的附加元数据(参数列表)。无论如何,这是一种更通用的方法来完成您正在做的事情:
并且更通用:
取决于您是否希望能够处理整数以外的事物。
Or
partial
andcomp
usually aren't as succinct in Clojure as using#()
to make an anonymous fn. Personally I'd write it this way:You can do this with plain
def
, but what do you gain usingdef
instead ofdefn
, really? Usingdef
obscures the fact that you're defining a function.defn
also sets up additional metadata for you (arglists) thatdef
doesn't.In any case, this is a more general way to do what you're doing:
And still more general:
Depends whether you want to be able to handle things other than Integers.