| FazBrowse GitHub Viewer | Trending | | Home |
| Tools: [Download Repo ZIP] [Original HTTPS Page] |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -1,5 +1,38 @@ | |||
| 1 | 1 | package lambdasinaction.chap13; | |
| 2 | 2 | ||
| 3 | 3 | ||
| 4 | + import java.util.function.Function; | ||
| 5 | + import java.util.function.Supplier; | ||
| 6 | + | ||
| 4 | 7 | public class PatternMatching { | |
| 8 | + | ||
| 9 | + | ||
| 10 | + static class Expr { } | ||
| 11 | + static class Number extends Expr { int val; } | ||
| 12 | + static class BinOp extends Expr { String opname; Expr left, right; } | ||
| 13 | + | ||
| 14 | + | ||
| 15 | + | ||
| 16 | + static <T> T MyIf(boolean b, Supplier<T> truecase, Supplier<T> falsecase) { | ||
| 17 | + return b ? truecase.get() : falsecase.get(); | ||
| 18 | + } | ||
| 19 | + | ||
| 20 | + static interface TriFunction<S, T, U, R>{ | ||
| 21 | + R apply(S s, T t, U u); | ||
| 22 | + } | ||
| 23 | + static <T> T PatternMatchExpr( Expr e, | ||
| 24 | + TriFunction<String,Expr,Expr,T> binopcase, Function<Integer,T> numcase, | ||
| 25 | + Supplier<T> defaultcase) { | ||
| 26 | + | ||
| 27 | + if(e instanceof BinOp){ | ||
| 28 | + return binopcase.apply(((BinOp)e).opname, ((BinOp)e).left, ((BinOp)e).right); | ||
| 29 | + } | ||
| 30 | + else if(e instanceof Number){ | ||
| 31 | + return numcase.apply(((Number)e).val); | ||
| 32 | + } | ||
| 33 | + else{ | ||
| 34 | + return defaultcase.get(); | ||
| 35 | + } | ||
| 36 | + } | ||
| 37 | + | ||
| 5 | 38 | } | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
@@ -2,4 +2,31 @@ | |||
| 2 | 2 | ||
| 3 | 3 | ||
| 4 | 4 | public class PersistentDataStructures { | |
| 5 | + | ||
| 6 | + | ||
| 7 | + static class TrainJourney { | ||
| 8 | + public int price; | ||
| 9 | + public TrainJourney onward; | ||
| 10 | + public TrainJourney(int p, TrainJourney t) { | ||
| 11 | + price = p; | ||
| 12 | + onward = t; | ||
| 13 | + } | ||
| 14 | + } | ||
| 15 | + | ||
| 16 | + static TrainJourney link(TrainJourney a, TrainJourney b) { | ||
| 17 | + if (a==null){ | ||
| 18 | + return b; | ||
| 19 | + } | ||
| 20 | + TrainJourney t = a; | ||
| 21 | + while(t.onward != null){ | ||
| 22 | + t = t.onward; | ||
| 23 | + } | ||
| 24 | + t.onward = b; | ||
| 25 | + return a; | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + static TrainJourney append(TrainJourney a, TrainJourney b) | ||
| 29 | + { | ||
| 30 | + return a==null ? b : new TrainJourney(a.price, append(a.onward, b)); | ||
| 31 | + } | ||
| 5 | 32 | } | |
| Back | FazBrowse Home | New Git URL |
0 commit comments