Last active
October 13, 2021 02:43
-
-
Save JustinSDK/1e58f76e777a7646b8deee1cf902fa90 to your computer and use it in GitHub Desktop.
代數資料型態:子型態多型+模式比對
This file contains hidden or 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
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