Created
October 31, 2009 06:20
-
-
Save jutememo/222954 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
import java.util.Arrays; | |
import java.util.List; | |
/** | |
* 検索クラス | |
*/ | |
public class Search { | |
private static List<Person> persons = Arrays.asList( | |
new Person("Tarou", "Tokyo"), | |
new Person("Jirou", "Osaka"), | |
new Person("Saburou", "Nagoya")); | |
// Maybe<Person> クラスのオブジェクトを返すことによって、 | |
// このメソッドを使うクライアントが、検索して見つからなかったときの | |
// 処理をしなければならいないように強制する。 | |
static Maybe<Person> find(String name) { | |
for (Person p : Search.persons) { | |
if (p.getName().equals(name)) { | |
return new Just(p); // 見つかったら Just で包む | |
} | |
} | |
return new Nothing(); // Haskell の Maybe a 型の値 Nothing に相当 | |
} | |
static String getAddress(String name) { | |
Maybe<Person> m = find(name); | |
if (m instanceof Just) { | |
return m.fromJust().getAddress(); | |
} else { | |
return name + " ha imasen"; | |
} | |
} | |
public static void main(String[] args) { | |
System.out.println(getAddress("Tarou")); | |
System.out.println(getAddress("Hanako")); | |
} | |
} | |
/** | |
* 「人」を表わすクラス | |
*/ | |
class Person { | |
private String name; | |
private String address; | |
Person() { | |
} | |
Person(String name, String address) { | |
this.name = name; | |
this.address = address; | |
} | |
String getName() { | |
return this.name; | |
} | |
String getAddress() { | |
return this.address; | |
} | |
@Override | |
public String toString() { | |
return this.name + ":" + this.address; | |
} | |
} | |
/** | |
* Hakell の Maybe a 型を真似たクラス | |
*/ | |
class Maybe<T> { | |
protected T a; | |
T fromJust() { | |
return this.a; | |
} | |
} | |
class Nothing extends Maybe { | |
} | |
class Just<T> extends Maybe { | |
Just(T a) { | |
this.a = a; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment