迭代函数
在Java中可以做这样的事情吗?
for (Object o : objects) {
for (Function f : functions) {
f(o);
}
}
我只调用了几个函数,但我需要组合它们,如下所示:
for (Object o : objects) {
for (Function f : functions) {
for (Function g : functions) {
f(g(o));
}
}
}
而且我想避免写出数百行函数调用。
我尝试研究函数指针和函子,但没有找到任何相关的东西。
Is something like this possible to do in Java?
for (Object o : objects) {
for (Function f : functions) {
f(o);
}
}
I'm only calling a handful of functions, but I need to compose them, like so:
for (Object o : objects) {
for (Function f : functions) {
for (Function g : functions) {
f(g(o));
}
}
}
And I'd like to avoid writing out hundreds of lines of function calls.
I've tried researching function pointers and functors, but haven't found anything pertinent.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能使用
f(g(o))
语法,但可以使用(通过合适的接口)f.call(g.call(o))
。示例用法(这与 Java 中的仿函数最接近,至少在闭包进入该语言之前):
如果您不想创建无数的类,基于反射的方法可能会更好(例如
double
-> java.lang.Math 中的double
函数,但可以轻松适应其他场景):(已省略异常消息显然,我将它们放入生产代码中。)
示例用法:
You can't use the
f(g(o))
syntax, but you can use (with a suitable interface)f.call(g.call(o))
.Example usage (this is as close as you can get to functors in Java, at least until closures make it into the language):
If you don't want to create a zillion classes, a reflection-based approach may work better (example for
double
->double
functions injava.lang.Math
, but easily adaptable to other scenarios):(Exception messages have been left out for brevity. Obviously, I'd put them in for production code.)
Sample usage:
Java 并没有真正精确地处理函子,但您可以通过接口来非常接近函子。我建议也许尝试这样的事情。
然后在您的代码中,您将创建一个包含 Function1、Function2 ... 对象的数组或列表,并运行看起来很像您的代码的内容。
或者,对于两层嵌套:
Java doesn't really do functors exactly, but you can get pretty close with an interface. I'd reccommend maybe trying something like this.
And then in your code you'd create an array or list containing Function1, Function2 ... objects and run something that looks a lot like your code.
Or, for two levels of nesting:
@Seth——这是你的泛型示例。由于泛型在运行时不存在,我不明白为什么您担心失去“灵活性”。如果您使用泛型,那么您只是在使用对象。
如果你希望 F 的行为根据 G 的返回类型而变化,那么你只需声明你的 F 做类似 F 的事情,很简单。
@Seth -- Here is your example with generics. Since generics don't exist at runtime, I do not understand why you fear a loss of "flexibility". If you use generics, then you are just using Objects.
If you want F's behavior to vary based on the return type of G, then you would just declare your F to do something like F, easy peasy.
也许你可以尝试一个流畅的界面,它可以让你将这些组合在一起。这可能是一个不错的设计,但我无法从你的例子中看出。
Maybe you can try a fluent interface that would let you gang these together. It might be a nice design, but I can't tell from your example.