Skip to content

Instantly share code, notes, and snippets.

Created January 28, 2015 11:20
Show Gist options
  • Save anonymous/7afcd5e16ced4b97b14f to your computer and use it in GitHub Desktop.
Save anonymous/7afcd5e16ced4b97b14f to your computer and use it in GitHub Desktop.
Functiona Composition
// 関数インターフェース用のUtilityクラス
public class FunctionUtil{
 // 2つの関数インターフェースを受け取り
 // 、2番めの関数インターフェースを実行してから
 // 、1番目の関数インターフェースをじっこうすr関数インターフェースを返す
public static <A, B, C> IFunction<A, C> composition(final IFunction<B, C> f1, final IFunction<A, B> f2){
return new IFunction<A, C>() {
@Override
public C func(A a) {
return f1.func(f2.func(a));
}
};
}
}
// 関数用のインターフェース
// 作成したい関数をこのインターフェースを実装したクラスとして作成する
public interface IFunction<A, B>{
public abstract B func(A a);
}
public class Main {
public static void main(String [] _args) {
// 数値を受け取って5を×関数
final IFunction<Integer, Integer> f1 =
new IFunction<Integer, Integer> () {
@Override
public Integer func (final Integer n){
return new Integer(n*5);
}
};
// Intgerを文字列化する関数
final IFunction<Integer, String> f2 =
new IFunction<Integer, String> () {
@Override
public String func (final Integer n){
return Integer.toString(n);
}
};
System.out.println(FunctionUtil.composition(f2, f1).func(5));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment