Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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