Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Last active October 13, 2021 02:43
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/1e58f76e777a7646b8deee1cf902fa90 to your computer and use it in GitHub Desktop.
Save JustinSDK/1e58f76e777a7646b8deee1cf902fa90 to your computer and use it in GitHub Desktop.
代數資料型態:子型態多型+模式比對
package cc.openhome;
import java.util.Arrays;
sealed interface List permits Nil, Cons {
default Integer head() { return null; }
default List tail() { return null; }
default Integer sum() {
return switch(this) {
case Nil nil -> 0;
case Cons cons -> cons.head() + cons.tail().sum();
};
}
}
final class Nil implements List {
public static final Nil INSTANCE = new Nil();
private Nil() {}
public String toString() { return "[]"; }
}
record Cons(Integer head, List tail) implements List {
public String toString() { return head() + ":" + tail(); }
}
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