Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

71
LINES

< > BotCompany Repo | #1035383 // BStack backup

JavaX fragment (include)

1  
sclass BStack > VStack {
2  
  static int idCounter;
3  
  int stackID = ++idCounter;
4  
  
5  
  // alternative to backtrack to
6  
  IF0<BStack> alternative;
7  
  
8  
  // steps to undo before switching to the alternative
9  
  L<AutoCloseable> undos;
10  
  
11  
  *() {}
12  
  *(Computable computation) { push(computation); }
13  
  *(Iterable<Computable> l) { pushAll(l); }
14  
  
15  
  BStack cloneStack() {
16  
    new BStack s;
17  
    s.stack = shallowCloneElements(stack);
18  
    ret s;
19  
  }
20  
  
21  
  void addUndo(AutoCloseable undo) {
22  
    if (undo == null) ret;
23  
    if (undos == null) undos = new L;
24  
    undos.add(undo);
25  
  }
26  
  
27  
  <A extends VStack.Computable> void options(A function,
28  
    IVF1<A>... options) {
29  
    // Check if there is more than one option
30  
    if (l(options) > 1) {
31  
      // Then remember this option in a cloned stack
32  
      IVF1<A> option2 = second(options);
33  
      addAlternative(clonedStack -> {
34  
        A clonedFunction = (A) last(clonedStack.stack);
35  
        option2.get(clonedFunction);
36  
      });
37  
    }
38  
39  
    // Execute the first option
40  
    first(options).get(function);
41  
  }
42  
  
43  
  void addAlternative(IVF1<BStack> action) {
44  
    BStack clonedStack = cloneStack();
45  
    alternative = -> {
46  
      action.get(clonedStack);
47  
      ret clonedStack;
48  
    };
49  
  }
50  
  
51  
  // Try to backtrack one step and return a new stack
52  
  // Returns null if no backtracking possible
53  
  BStack backtrack() ctex {
54  
    if (undos != null)
55  
      for (undo : reversed(getAndClearList(undos)))
56  
        undo.close();
57  
        
58  
    ret alternative?!;
59  
  }
60  
  
61  
  Object nextResult() {
62  
    stepAll(this);
63  
    return latestResult;
64  
  }
65  
  
66  
  // calculate next result and print stack at every step
67  
  Object nextResultWithPrintStruct() {
68  
    stepAllWithPrintStruct(this);
69  
    return latestResult;
70  
  }
71  
}

Author comment

Began life as a copy of #1035381

download  show line numbers  debug dex  old transpilations   

Travelled to 2 computer(s): mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1035383
Snippet name: BStack backup
Eternal ID of this version: #1035383/1
Text MD5: 0f0cf60c645f3bf3b7fddcdcb1ffea9f
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-05-04 19:26:33
Source code size: 1782 bytes / 71 lines
Pitched / IR pitched: No / No
Views / Downloads: 50 / 61
Referenced in: [show references]