Created
August 30, 2010 03:05
-
-
Save jutememo/556957 to your computer and use it in GitHub Desktop.
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 Cons<A> implements IList<A> { | |
/** | |
* リストの先頭要素 | |
*/ | |
private A x; | |
/** | |
* リストの残りの要素 | |
*/ | |
private IList<A> xs; // 型変数を忘れないように! | |
public Cons(A x, IList<A> xs) { | |
this.x = x; | |
this.xs = xs; | |
} | |
public Cons<A> cons(A x) { | |
return new Cons<A>(x, this); | |
} | |
public int length() { | |
return 1 + this.xs.length(); | |
} | |
@Override | |
public String toString() { | |
return this.x.toString() + " " + this.xs.toString(); | |
} | |
} |
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 IList<A> { | |
/** | |
* リストの先頭に要素 a を追加する | |
* @param a 追加する要素 | |
* @return リスト | |
*/ | |
public IList<A> cons(A x); | |
/** | |
* リストの要素数を返す | |
* @return リストの要素数 | |
*/ | |
public int length(); | |
} |
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) { | |
// 型変数を忘れないように! | |
IList<Integer> list = new Nil<Integer>().cons(4).cons(3).cons(2).cons(1); | |
System.out.println(list); | |
System.out.println(list.length()); | |
} | |
} |
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 Nil<A> implements IList<A> { | |
public IList<A> cons(A a) { | |
return new Cons(a, this); | |
} | |
public int length() { | |
return 0; | |
} | |
@Override | |
public String toString() { | |
return ""; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment