Created
January 28, 2015 11:20
-
-
Save anonymous/7afcd5e16ced4b97b14f to your computer and use it in GitHub Desktop.
Functiona Composition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 関数インターフェース用の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)); | |
} | |
}; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 関数用のインターフェース | |
// 作成したい関数をこのインターフェースを実装したクラスとして作成する | |
public interface IFunction<A, B>{ | |
public abstract B func(A a); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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