玩Java的Function功能
这篇文章是对某友人的帖子闭包进行的一个对Swift的致敬,他在那篇文章中通过Go语言写了一些高阶函数来娱乐。
正如原文中所述,这纯粹只是一种乐趣,对于寻求有用实现的人来说,请点击浏览器的返回按钮。
(注)鉴于我在深夜的情绪下写作,可能会有一些奇怪的地方,请理解一下m(_ _)m
本题 tí)
hoge1 ~ 4 可以传递进一步的参数,因为其返回值为 Function。
// Integerをとり、Integerを返す
Function<Integer, Integer> hoge1 = value -> value;
hoge1.apply(1); // return 1
// Integerをとり、IntegerをとりIntegerを返す関数を返す
Function<Integer, Function<Integer, Integer>> hoge2 = value -> (a -> value + a);
hoge2.apply(1).apply(2); // return 3
/// Integerをとり、IntegerをとりIntegerをとりIntegerを返す関数を返す
Function<Integer, Function<Integer, Function<Integer, Integer>>> hoge3 = value -> (a -> (b -> value + a + b));
hoge3.apply(1).apply(2).apply(4); // return 7
// Integerをとり、IntegerをとりIntegerをとりIntegerをとりIntegerを返す関数を返す
Function<Integer, Function<Integer, Function<Integer, Function<Integer, Integer>>>> hoge4 = value -> (a -> (b -> (c -> value + a + b + c)));
hoge4.apply(1).apply(2).apply(4).apply(8); // return 15
hoge5~7需要预先传递处理,因为它们的参数是闭包
(hoge5~7使用了hoge1~4的返回值,因为它们的参数是函数)
// IntegerをとりIntegerを返す関数をとり、IntegerをとりIntegerをとりIntegerをとりIntegerを返す関数を返す
Function<Function<Integer, Integer>, Function<Integer, Function<Integer, Function<Integer, Integer>>>> hoge5 = hoge -> (a -> (b -> (c -> hoge.apply(a + b + c))));
hoge5.apply(hoge1).apply(1).apply(2).apply(4); // return 7
hoge5.apply(hoge2.apply(1)).apply(2).apply(4).apply(8); // return 15
hoge5.apply(hoge3.apply(1).apply(2)).apply(4).apply(8).apply(16); // return 31
hoge5.apply(hoge4.apply(1).apply(2).apply(4)).apply(8).apply(16).apply(32); // return 63
// IntegerをとりIntegerをとりIntegerを返す関数をとり、IntegerをとりIntegerをとりIntegerをとりIntegerを返す関数を返す
Function<Function<Integer, Function<Integer, Integer>>, Function<Integer, Function<Integer, Function<Integer, Integer>>>> hoge6 = hoge -> (a -> (b -> (c -> hoge.apply(a).apply(b + c))));
hoge6.apply(hoge2).apply(1).apply(2).apply(4); // return 7
hoge6.apply(hoge3.apply(1)).apply(2).apply(4).apply(8); // return 15
hoge6.apply(hoge4.apply(1).apply(2)).apply(4).apply(8).apply(16); // return 31
// IntegerをとりIntegerをとりIntegerをとりIntegerを返す関数をとり、IntegerをとりIntegerをとりIntegerをとりIntegerを返す関数を返す
Function<Function<Integer, Function<Integer, Function<Integer, Integer>>>, Function<Integer, Function<Integer, Function<Integer, Integer>>>> hoge7 = hoge -> (a -> (b -> (c -> hoge.apply(a).apply(b).apply(c))));
hoge7.apply(hoge3).apply(1).apply(2).apply(4); // return 7
hoge7.apply(hoge4.apply(1)).apply(2).apply(4).apply(8); // return 15
当然可以将具有返回值的函数直接保留下来。
虽然传递了数字,但实际上并没有进行计算。
hoge7.apply(hoge3); // return Function
hoge7.apply(hoge3).apply(1); // return Function
hoge7.apply(hoge3).apply(1).apply(2); // return Function
继续循环,将所有数相加…
就像你所看到的,Java8之前我们使用for循环进行计算!
现在开始有点困了…w
int sum = IntStream.rangeClosed(1, 100).sum(); // return 5050
接受一个取T和T并返回T的闭包,并返回一个接受T和T并返回T的闭包(明天也可以啦…ww)
通过循环获取最大值(尝试用stream处理方法解决…)
最后
所有仔细阅读过的人,辛苦了。由于最后精力不足,我们会在下次再说…
请注意在实际产品中不要嵌入像上述那样难以阅读的烂代码。
学习函数式编程刚开始可能会感到困难,但一旦理解了就会感到愉快。首先,我打算尝试用Java进行函数式编程,并打算阅读很棒的H本。
补充:在Java中,对于Lambda表达式,最佳的换行位置应该是哪里呢?(・・?)