📜  使用示例在Java中对函数进行柯里化

📅  最后修改于: 2022-05-13 01:55:26.090000             🧑  作者: Mango

使用示例在Java中对函数进行柯里化

函数柯里化是将具有多个参数的函数分解为具有单个参数的多个函数的概念,其输出相同。换句话说,它是一种将多值参数函数简化为单值参数多功能函数的技术。

考虑这个例子来清除这个概念:

柯里化将高阶函数分解为一系列较小的级联函数,这些函数接受一个参数并返回一个函数,除了最后一个返回所需值的级联函数。

例如:

让有一个函数映射为
f:(u, v) -> w

柯里化上述函数会产生
g:(u->(v->w))

因此g地图来自u到一个函数,该函数又映射自vw
上述数学表达式也可以表示为:
{g(u)}(v)=f(u, v)

因此, curry(f) = g

下面是一些Java示例来演示函数柯里化:

示例 1:使用函数柯里化添加 2 个数字

// Java Program to demonstrate Function Currying
  
import java.util.function.Function;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Using Java 8 Functions
        // to create lambda expressions for functions
        // and with this, applying Function Currying
  
        // Curried Function for Adding u & v
        Function >
            curryAdder = u -> v -> u + v;
  
        // Calling the curried functions
  
        // Calling Curried Function for Adding u & v
        System.out.println("Add 2, 3 :"
                           + curryAdder
                                 .apply(2)
                                 .apply(3));
  
        }
}
输出:
Add 2, 3 :5

示例 2:使用函数柯里化将 2 个数字相乘

// Java Program to demonstrate Function Currying
  
import java.util.function.Function;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Using Java 8 Functions
        // to create lambda expressions for functions
        // and with this, applying Function Currying
  
        // Curried Function for Multiplying u & v
        Function >
            curryMulti = u -> v -> u * v;
  
        // Calling the curried functions
         
        // Calling Curried Function for Multiplying u & v
        System.out.println("Multiply 2, 3 :"
                           + curryMulti
                                 .apply(2)
                                 .apply(3));
    }
}
输出:
Multiply 2, 3 :6

示例 3:使用函数柯里化添加 3 个数字

// Java Program to demonstrate Function Currying
  
import java.util.function.Function;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Using Java 8 Functions
        // to create lambda expressions for functions
        // and with this, applying Function Currying
  
        // Curried Function for Adding u, v & w
        Function > >
            triadder = u -> w -> v -> u + w + v;
  
        // Calling the curried functions
  
        // Calling Curried Function for Adding u, v & w
        System.out.println("Add 2, 3, 4 :"
                           + triadder
                                 .apply(2)
                                 .apply(3)
                                 .apply(4));
    }
}
输出:
Add 2, 3, 4 :9