一、简介
函数式编程是非常常用和非常重要的一种编程范式,有的语言直接提供支持,C++则通过()运算符重载和模板提供了还算灵活的支持,而Java中的函数式编程则由于语言本身的局限没有得到广泛应用,Apache Commons Functor 项目是一个正在开发中的函数式编程库,但目前看来并不是类型安全的;J2SE 5.0提供了有限的generic能力,除了用于Collection之外,类型安全的functor也是其用武之地,已有一个开源项目Generic Algorithms for Java开始了这方面的工作
二、示例
public interface UnaryFunction<R, P> { R evaluate(P obj); }
public interface UnaryPredicate<T> { boolean test(T obj); }
public interface UnaryProcedure<T> { void run(T obj); }
public interface BinaryFunction<R, T, S> { R evaluate(T left, S right); }
public interface BinaryPredicate<T, S> { boolean test(T left, S right); }
public interface BinaryProcedure<T, S> { void run(T left, S right); }
public interface Filter<T> extends UnaryFunction<T, T>{ }
public static <Destination, Source> List<Destination> transform(Collection<Source> source, UnaryFunction<Destination, Source> transformer){ List<Destination> result = new ArrayList<Destination>(); for(Source item : source){ result.add(transformer.evaluate(item)); } return result; }
public static <T> List<T> select(Collection<T> source, UnaryPredicate<T> selector){ List<T> result = new ArrayList<T>(); for(T item : source){ if(selector.test(item)){ result.add(item); } } return result; }
public static <T> void foreach(Collection<T> source, UnaryProcedure<T> procedure){ for(T item : source){ procedure.run(item); } }
public class And<T> implements UnaryPredicate<T>, Serializable{ private UnaryPredicate<T>[] predicates; public And(UnaryPredicate<T>... predicates){ this.predicates = predicates; } public boolean test(T obj) { for(UnaryPredicate<T> predicate : predicates){ if( !predicate.test(obj) ){ return false; } } return true; } public static <T> And<T> and(UnaryPredicate<T>... predicates){ return new And<T>(predicates); } }
public class Or<T> implements UnaryPredicate<T>, Serializable{ private UnaryPredicate<T>[] predicates; public Or(UnaryPredicate<T>... predicates){ this.predicates = predicates; } public boolean test(T obj) { for(UnaryPredicate<T> predicate : predicates){ if( predicate.test(obj) ){ return true; } } return false; } public static <T> Or<T> or(UnaryPredicate<T>... predicates){ return new Or<T>(predicates); } }
public class Not<T> implements UnaryPredicate<T>, Serializable{ private UnaryPredicate<T> predicate; public Not(UnaryPredicate<T> predicate){ this.predicate = predicate; } public boolean test(T obj) { return !predicate.test(obj); } public static <T> Not<T> not(UnaryPredicate<T> predicate){ return new Not<T>(predicate); } } 
|