Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Last active October 12, 2021 06:22
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/e00ab58c900b0110bd5a3619b098fece to your computer and use it in GitHub Desktop.
Save JustinSDK/e00ab58c900b0110bd5a3619b098fece to your computer and use it in GitHub Desktop.
代數資料型態:Java 17
package cc.openhome;
import java.util.Arrays;
sealed interface List<T> permits Nil, Cons<T> {
default T head() { return null; }
default List<T> tail() { return null; }
}
final class Nil implements List {
static final Nil INSTANCE = new Nil();
private Nil() {}
public String toString() { return "[]"; }
}
record Cons<T>(T head, List<T> tail) implements List<T> {
public String toString() { return head() + ":" + tail(); }
}
public class AlgebraicType {
@SafeVarargs
@SuppressWarnings("unchecked")
public static <T> List<T> list(T... elems) {
if(elems.length == 0) return Nil.INSTANCE;
var remain = Arrays.copyOfRange(elems, 1, elems.length);
return new Cons<T>(elems[0], list(remain));
}
// Java 17 使用預覽的 switch pattern matching
public static Integer sum(List<Integer> lt) {
return switch(lt) {
case Nil nil -> 0;
case Cons<Integer> cons -> cons.head() + sum(cons.tail());
};
}
/* switch pattern matching 結合未來版本的 deconstruction pattern 可以這樣? */
// public static Integer sum(List<Integer> lt) {
// return switch(lt) {
// case Nil nil -> 0;
// case Cons(head, tail) -> head + sum(tail);
// };
// }
public static void main(String[] args) {
var lt = list(1, 2, 3);
System.out.println(lt); // 1:2:3:[]
var n = sum(lt);
System.out.println(n); // 6
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment