View Javadoc
1   package com.github.lstephen.ai.search.action;
2   
3   import java.util.Arrays;
4   import java.util.Collection;
5   import java.util.Set;
6   import java.util.concurrent.atomic.AtomicReference;
7   import java.util.stream.Stream;
8   
9   import com.google.common.collect.ImmutableList;
10  import com.google.common.collect.ImmutableSet;
11  import com.google.common.collect.Sets;
12  
13  /**
14   *
15   * @author lstephen
16   */
17  public final class SequencedAction<S> implements Action<S> {
18  
19      private final ImmutableList<Action<S>> actions;
20  
21      private SequencedAction(Iterable<Action<S>> actions) {
22          this.actions = ImmutableList.copyOf(actions);
23      }
24  
25      @Override
26      public S apply(S initial) {
27        AtomicReference<S> state = new AtomicReference<>(initial);
28  
29        actions.stream().forEach((a) -> state.getAndUpdate(a::apply));
30  
31        return state.get();
32      }
33  
34      @SafeVarargs
35      @SuppressWarnings("varargs")
36      public static <S> SequencedAction<S> create(Action<S>... as) {
37          return new SequencedAction<>(Arrays.asList(as));
38      }
39  
40      public static <S> Stream<SequencedAction<S>> allPairs(Collection<? extends Action<S>> actions) {
41          return merged(actions, actions);
42      }
43  
44      public static <S> Stream<SequencedAction<S>> merged(
45          Collection<? extends Action<S>> firsts,
46          Collection<? extends Action<S>> seconds) {
47  
48        return merged(firsts.stream(), seconds);
49      }
50  
51      public static <S> Stream<SequencedAction<S>> merged(
52          Stream<? extends Action<S>> firsts,
53          Collection<? extends Action<S>> seconds) {
54  
55        return firsts.flatMap((f) -> seconds.stream().map((s) -> SequencedAction.create(f, s)));
56      }
57  
58  }