Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Last active October 13, 2021 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinSDK/54a75e17ab16bf00b0836d452df7c167 to your computer and use it in GitHub Desktop.
Save JustinSDK/54a75e17ab16bf00b0836d452df7c167 to your computer and use it in GitHub Desktop.
代數資料型態:Visitor 實現
package cc.openhome;
import java.util.Arrays;
interface List {
default Integer head() { return null; }
default List tail() { return null; }
Integer sum();
// 實現模式比對
static Integer sum(Nil nil) { return 0; }
static Integer sum(Cons cons) { return cons.head() + cons.tail().sum(); }
}
class Nil implements List {
static final Nil INSTANCE = new Nil();
private Nil() {}
public String toString() { return "[]"; }
@Override
public Integer sum() {
return List.sum(this);
}
}
class Cons implements List {
private Integer head;
private List tail;
Cons(Integer head, List tail) {
this.head = head; this.tail = tail;
}
public Integer head() { return head; }
public List tail() { return tail; }
public String toString() { return head() + ":" + tail(); }
@Override
public Integer sum() {
return List.sum(this);
}
}
public class AlgebraicType {
public static List list(Integer... elems) {
if(elems.length == 0) return Nil.INSTANCE;
var remain = Arrays.copyOfRange(elems, 1, elems.length);
return new Cons(elems[0], list(remain));
}
public static void main(String[] args) {
var lt = list(1, 2, 3);
System.out.println(lt); // 1:2:3:[]
var n = lt.sum();
System.out.println(n); // 6
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment