/** * Sets a {@link Supplier} to execute if this matches. */ public <R> FluentMatchingR<T, R> get(Supplier<R> supplier) { return get(new FluentMatchingR<>(value), supplier); }
/** * Specifies an match on a decomposing matcher with 0 extracted fields and then returns a fluent * interface for specifying the action to take if the value matches this case. */ public <U extends T> InitialMatching0<T, U> when( DecomposableMatchBuilder0<U> decomposableMatchBuilder) { return new InitialMatching0<>(decomposableMatchBuilder.build(), value); }
/** * Sets a {@link Consumer0} to execute if this matches. */ public FluentMatchingC<T> then(Consumer0 consumer) { return then(new FluentMatchingC<>(value), consumer); } }
private long factMatching(long i) { return match(i) .when(eq(0L)).get(() -> 1L) .when(any()).get(x -> x * factMatching(x - 1)) .getMatch(); } }
/** * Specifies an exact match and then returns a fluent interface for specifying the action to take * if the value matches this case. */ public <U extends T> InitialMatching0<T, U> when(MatchesExact<U> o) { List<Matcher<Object>> matchers = Lists.of(ArgumentMatchers.eq(o.t)); return new InitialMatching0<>( new DecomposableMatchBuilder0<>(matchers, new IdentityFieldExtractor<U>()).build(), value); }
/** * Fizzbuzz benchmark using motif pattern matching. */ @Benchmark public void fizzBuzzPatternMatching() { IntStream.range(0, 101).forEach( n -> System.out.println( match(Tuple2.of(n % 3, n % 5)) .when(tuple2(eq(0), eq(0))).get(() -> "FizzBuzz") .when(tuple2(eq(0), any())).get(y -> "Fizz") .when(tuple2(any(), eq(0))).get(x -> "Buzz") .orElse(String.valueOf(n)) .getMatch() ) ); } }
/** * An implementation of factorial using motif pattern matching. */ public long factMatching(long n) { return match(n) .when(caseLong(0)).get(() -> 1L) .when(caseLong(any())).get(i -> i * factMatching(i - 1)) .getMatch(); } }