Java是否支持Currying? [英] Does Java support Currying?

查看:89
本文介绍了Java是否支持Currying?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法可以用Java来解决这个问题。我认为,如果没有原生支持闭包,这是不可能的。

解决方案Java 8(2014年3月18日发布)不支持currying。 missfaktor的回答中发布的示例Java代码可以被重写为:

  import java.util.function。*; 
import static java.lang.System.out;

//测试JDK 1.8.0-ea-b75
public class CurryingAndPartialFunctionApplication
{
public static void main(String [] args)
{
IntBinaryOperator simpleAdd =(a,b) - > a + b;
IntFunction< IntUnaryOperator> curriedAdd = a - > b - > a + b;

//演示简单的添加:
out.println(simpleAdd.applyAsInt(4,5));

//演示curried add:
out.println(curriedAdd.apply(4).applyAsInt(5));

// Curried版本让你执行部分应用程序:
IntUnaryOperator adder5 = curriedAdd.apply(5);
out.println(adder5.applyAsInt(4));
out.println(adder5.applyAsInt(6));
}
}

...这是相当不错的。就个人而言,在Java 8可用的情况下,我没有理由使用诸如Scala或Clojure之类的替代JVM语言。当然,它们提供了其他语言功能,但这还不足以证明转换成本和较弱的IDE /工具/库支持,IMO。


I was wondering if there is any way to pull that in Java. I think it is not possible without native support for closures.

解决方案

Java 8 (released March 18th 2014) does support currying. The example Java code posted in the answer by missingfaktor can be rewritten as:

import java.util.function.*;
import static java.lang.System.out;

// Tested with JDK 1.8.0-ea-b75
public class CurryingAndPartialFunctionApplication
{
   public static void main(String[] args)
   {
      IntBinaryOperator simpleAdd = (a, b) -> a + b;
      IntFunction<IntUnaryOperator> curriedAdd = a -> b -> a + b;

      // Demonstrating simple add:
      out.println(simpleAdd.applyAsInt(4, 5));

      // Demonstrating curried add:
      out.println(curriedAdd.apply(4).applyAsInt(5));

      // Curried version lets you perform partial application:
      IntUnaryOperator adder5 = curriedAdd.apply(5);
      out.println(adder5.applyAsInt(4));
      out.println(adder5.applyAsInt(6));
   }
}

... which is quite nice. Personally, with Java 8 available I see little reason to use an alternative JVM language such as Scala or Clojure. They provide other language features, of course, but that's not enough to justify the transition cost and the weaker IDE/tooling/libraries support, IMO.

这篇关于Java是否支持Currying?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆