# 实验5：复合函数

--------------------------

## 1.映射f

f(x) = x+1
f(x)= x *x
f(x) = (x+1)* (x+1)

package chap4.compositeFunction;
@FunctionalInterface
public interface F {//IntUnaryOperator
public int f(int x) ;
}
package chap4.compositeFunction;
import static yqj2065.util.Print.*;
public class Demo{
//参数化F
public static int eval(F y, int x) {
return y.f(x);
}
public static void test() {
F y = x -> x + 1;
int r = eval(y, 2);       pln(r);
int r2 = eval(x -> x + 1, 2);        pln(r2);
int r3 = eval(x -> x*x, y.f(2)); pln(r3);
int r4 = eval(x -> x*x, eval(x -> x + 1, 2)); pln(r4);
}
}


## 2.g(f(x))

    public static void compsite(){
F y = x -> x + 1; //函数 y = x+1
F comp = x -> y.f(x) * y.f(x);//z=y*y
int r =comp.f(2); pln(r);
}




## 3.高阶函数G

package chap4.compositeFunction;
@FunctionalInterface
public interface G {//IntUnaryOperator
public F g(F y);
}

class Z1 implements G{
@Override  public F g(F y){
return (x) -> y.f(x) * y.f(x);
}
}

G z = y ->{
return (x) -> y.f(x) * y.f(x); //
};

package higherOrderFunction;
import static util.Print.*;
public class MathDemo {
public static void main(String[] a) {
G z = y -> x -> y.f(x) * y.f(x);
F y = x -> x + 1;
F f3 = z.g(y);
pln(f3.f(2));
}
}


    public static void testGn(){
G h = y -> x -> y.f(x) * y.f(x) + 2 * y.f(x);//
G g = y -> x -> y.f(x) * y.f(x);
G z = y -> x -> y.f(x)+1;
F comp = h.g(g.g(z.g(F.identity)));

int r =comp.f(2);pln(r);
}

        G z = y -> {
pln("z:" + y);
return (x) -> {
pln("in z: x=" + x);
int i = y.f(x);
pln("in z: i=" + i);
return i * i;
};
};

   public static void main(String[] a) {
//        G z = y -> x -> y.f(x) * y.f(x);
Function<IntUnaryOperator,IntUnaryOperator> g3 = y ->  x -> y.applyAsInt(x) * y.applyAsInt(x);
IntUnaryOperator op =x -> x + 1;
//        F y = x -> x + 1;
pln(g3.apply(op).applyAsInt(2));

}

    public static void main(String[] a) {
Function<Integer, Integer> f = x -> x + 1;
Function<Integer, Integer> g = x -> x * x;
pln(g.compose(f).apply(2));

}