在 Clojure 中使用 java 方法作为函数参数

编程入门 行业动态 更新时间:2024-10-19 08:56:37
本文介绍了在 Clojure 中使用 java 方法作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Clojure 中使用 java 方法作为函数参数?

How can I use java methods as a functions arguments in Clojure?

比如我想做一个函数组合:

For example, I want to make a functions composition:

user> (Integer. (str 9))
9
user> ((comp Integer. str) 9)
CompilerException java.lang.ClassNotFoundException: Integer., compiling:(NO_SOURCE_PATH:1:2) 

那行不通.

memfn 也没有帮助:

user> (map (comp (memfn  Integer.) str) "891")
IllegalArgumentException No matching method found: Integer. for class java.lang.String  clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:53)

有什么想法吗?

相关问题(尽管没有给出正确答案):

Related questions (that, though, do not give the right answer to the question):

在地图函数(Clojure)中使用互操作构造函数为什么 Clojure说没有匹配方法"为非法论点?我如何使用 Clojure带有 Java 构造函数的 memfn?如何获取调用 Java 的 Fn方法?(答案中有很好的解释) Using interop constructor in map function(Clojure) Why does Clojure say "no matching method" for an illegal argument? How do I use Clojure memfn with a Java constructor? How to get an Fn which calls a Java method? (has a nice explanation in the answers)

(注意:dave 建议的答案似乎是使用匿名函数作为包装器的最佳解决方案)

推荐答案

与 Clojure 函数不同,Java 方法并非设计为一流的.当您在 Clojure 中使用 Java 互操作时,您实际上是在使用 Java 方法,因此您不会获得为 Clojure 函数实现的额外好处.有关更多信息,请参阅下面的评论.

Unlike Clojure functions, Java methods weren't designed to be first class. When you use Java inter-op in Clojure, you're literally working with Java methods, so you don't get the added benefits that were implemented for Clojure functions. For more info, see the comments below.

作为使用 Java 方法作为参数的一种解决方法,您可以将它们包装在一个匿名函数中,像这样,有效地使它们成为 Clojure 函数:

As a workaround to use Java methods as arguments, you can wrap them in an anonymous function, like this, effectively making them Clojure functions:

((comp #(Integer. %) str) 9)

这篇关于在 Clojure 中使用 java 方法作为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-27 08:53:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/686671.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   参数   方法   Clojure   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!