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

71
LINES

< > BotCompany Repo | #1035383 // BStack backup

JavaX fragment (include)

sclass BStack > VStack {
  static int idCounter;
  int stackID = ++idCounter;
  
  // alternative to backtrack to
  IF0<BStack> alternative;
  
  // steps to undo before switching to the alternative
  L<AutoCloseable> undos;
  
  *() {}
  *(Computable computation) { push(computation); }
  *(Iterable<Computable> l) { pushAll(l); }
  
  BStack cloneStack() {
    new BStack s;
    s.stack = shallowCloneElements(stack);
    ret s;
  }
  
  void addUndo(AutoCloseable undo) {
    if (undo == null) ret;
    if (undos == null) undos = new L;
    undos.add(undo);
  }
  
  <A extends VStack.Computable> void options(A function,
    IVF1<A>... options) {
    // Check if there is more than one option
    if (l(options) > 1) {
      // Then remember this option in a cloned stack
      IVF1<A> option2 = second(options);
      addAlternative(clonedStack -> {
        A clonedFunction = (A) last(clonedStack.stack);
        option2.get(clonedFunction);
      });
    }

    // Execute the first option
    first(options).get(function);
  }
  
  void addAlternative(IVF1<BStack> action) {
    BStack clonedStack = cloneStack();
    alternative = -> {
      action.get(clonedStack);
      ret clonedStack;
    };
  }
  
  // Try to backtrack one step and return a new stack
  // Returns null if no backtracking possible
  BStack backtrack() ctex {
    if (undos != null)
      for (undo : reversed(getAndClearList(undos)))
        undo.close();
        
    ret alternative?!;
  }
  
  Object nextResult() {
    stepAll(this);
    return latestResult;
  }
  
  // calculate next result and print stack at every step
  Object nextResultWithPrintStruct() {
    stepAllWithPrintStruct(this);
    return latestResult;
  }
}

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: 45 / 56
Referenced in: [show references]