2006年8月21日星期一

FP(functional programming) in java

FP是老的死掉的语言吗?不过最近在我脑子里活了起来。
以前没学过lambda,其实可以在本科教的,何必一定要研究生课,其实很简单,初中课程也可以。
(虽然我现在还不具体了解,~_~!),属于知道的就知道,不知道就不知道的问题吧。
几年前我还培训过公司新员工的java。有人交作业,好像是写在纸上的。
其中有一块是遍历一个list,然后对每个元素做一个相同的操作。
一般写法就是for循环里面写上操作。但是一个人他写的好像是for(func((list))之类的,
总之怎么写的不记得,作为人能看懂他是什么意思。但是也能明白他不会java。
更严重的是很可能连面向过程式和面向对象的编程都不了解。我无语了,觉得不是一句话
能把他教懂的问题了。无语是自己没想明白其中的奥妙。
但是事隔几年,我发现这样的语言也有阿,就是FP啊。那个人真是天才啊。
或者发明FP的人是白痴?
现在我发现可以自己用Java实现map, reduce, filter这三个基本的FP概念。
虽然我还没想到什么好方法来实现lambda.
下面是参考程序:
package neoe.fp;
import java.util.ArrayList;
import java.util.List;
public class Fp {
public static abstract class Func {
public abstract Object run(Object o);
}
public static abstract class Func2 {
public abstract Object run(Object o1, Object o2);
}
/** make a list, element is func(data's element) */
public static List map(List data, Func func) {
if (data == null) {
return null;
}
List res = new ArrayList();
for (Object o : data) {
res.add(func.run(o));
}
return res;
}
/**
* t also takes a function and a list. But unlike map, the function passed
* to filter returns a boolean value. If, and only if, the value is NOT
* NULL, the element is copied over to the new list
*/
public static List filter(List data, Func func) {
if (data == null) {
return null;
}
List res = new ArrayList();
for (Object o : data) {
if (null != func.run(o)) {
res.add(o);
}
}
return res;
}
/**
* the method takes not one but two arguments: the first argument is the
* current element of the list, the other is the result from the previous
* call of the function (if there was one).
*/
public static Object reduce(List data, Func2 func) {
if (data == null || data.size() < 2) {
return null;
}
Object res = data.get(0);
int size = data.size();
for (int i = 1; i < size; i++) {
res = func.run(res, data.get(i));
}
return res;
}
}
注:如果你看不懂就千万不要用它们。
-----

没有评论:

博客归档

neoedmund's shared items

我的简介

ZIP Code File