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

79
LINES

< > BotCompany Repo | #1030986 // VStack [backup before restructuring]

JavaX fragment (include)

sclass VStack implements Steppable {
  new L<Computable> stack;
  O latestResult;
  
  // was last instruction a return?
  // can be used by computations to switch without a label
  transient bool justReturned;
  transient O subComputationResult;
  
  // the null sentinel replaces a null function result
  // when stored in latestResult
  sclass NullSentinel {}
  static new NullSentinel nullSentinel;

  *() {}
  *(Computable computation) { push(computation); }
  *(Iterable<Computable> l) { pushAll(l); }
  
  // A is what the function returns
  interface Computable<A> {
    public void step(VStack stack, O subComputationResult);
  }
  
  private O deSentinel(O o) {
    ret o instanceof NullSentinel ? null : o;
  }
  
  private O sentinel(O o) {
    ret o == null ? nullSentinel : o;
  }
  
  // called by computations or users to start a subroutine
  void push aka call(Computable computation) {
    stack.add(computation);
  }
  
  // perform a computation step. returns false iff done
  public bool step() {
    if (empty(stack)) false;
    justReturned = latestResult != null;
    subComputationResult = deSentinel(latestResult);
    latestResult = null;
    last(stack).step(this, subComputationResult);
    subComputationResult = null;
    true;
  }
  
  // called from a computation to return a value
  void _return(O value default null) {
    latestResult = sentinel(value);
    removeLast(stack);
  }
  
  // called from a computation to tail-call another routine
  void tailCall aka replace(Computable computation) {
    removeLast(stack);
    stack.add(computation);
  }

  // all-in-one evaluation function - call on an empty stack 
  <A> A compute(Computable<A> computation) {
    if (computation == null) null;
    push(computation);
    stepAll(this);
    ret (A) latestResult;
  }
  
  // return result of just completed computation
  O result aka subResult() {
    ret deSentinel(latestResult);
  }

  bool hasSubResult() { ret justReturned; }
  
  void pushAll(Iterable<Computable> l) {
    fOr (Computable c : l)
      push(c);
  }
}

Author comment

Began life as a copy of #1030376

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, vouqrxazstgt

No comments. add comment

-
Snippet ID: #1030986
Snippet name: VStack [backup before restructuring]
Eternal ID of this version: #1030986/1
Text MD5: c9822bca9533b008cf477ebf9d8f4db2
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-04-18 14:55:05
Source code size: 2137 bytes / 79 lines
Pitched / IR pitched: No / No
Views / Downloads: 163 / 183
Referenced in: