feat: add Example for HaskellStyle Pattern Matching

This commit is contained in:
Ruben 2024-10-25 14:04:03 +02:00
parent 4d1950d0ba
commit b4da20e1d4
2 changed files with 23 additions and 11 deletions

View File

@ -1,14 +1,26 @@
import java.lang.Boolean;
sealed interface List<T> permits LinkedElem, Elem {}
public record LinkedElem<T>(T a, List<T> l) implements List<T> {}
public record Elem<T>(T a) implements List<T> {}
public class PaternMatchingHaskellStyle {
public append(LinkedElem(a, Elem(e)), l2) {
return new LinkedElem<>(a, new LinkedElem<>(e, l2));
}
public append(LinkedElem(a, r), l2) {
return new LinkedElem<>(a, append(r, l2));
}
}
public append(LinkedElem(a, b), list2) {
if (b instanceof Elem<?>) {
return handleElem(a, (Elem<?>) b, list2);
} else if (b instanceof LinkedElem<?>) {
return handleLinkedElem(a, (LinkedElem<?>) b, list2);
}
return null;
}
private handleElem(a, Elem(e), list2) {
return new LinkedElem<>(a, new LinkedElem<>(e, list2));
}
private handleLinkedElem(a, LinkedElem(a,r), list2) {
return new LinkedElem<>(a, append(r, list2));
}
}

View File

@ -869,11 +869,11 @@ public class TestComplete {
var instance = clazz.getDeclaredConstructor().newInstance();
var m = clazz.getDeclaredMethod("append", R, I);
//var x = rctor.newInstance(rctor.newInstance(0, rctor.newInstance(0, r2ctor.newInstance(0))), 0);
//var y = rctor.newInstance(r2ctor.newInstance(0), 0);
var x = rctor.newInstance(rctor.newInstance(0, rctor.newInstance(0, r2ctor.newInstance(0))), r2ctor.newInstance(0));
var y = rctor.newInstance(r2ctor.newInstance(0), r2ctor.newInstance(0));
//assertEquals(m.invoke(instance, x, y), 10);
//assertEquals(m.invoke(instance, y, y), 40.0);
assertEquals(m.invoke(instance, x, y), 10);
assertEquals(m.invoke(instance, y, y), 0);
}