Advertisement
SepandMeenu

evaluate nodes with a stack #2

Nov 9th, 2018
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.33 KB | None | 0 0
  1. # evaluate nodes with a stack -- functional algorithm
  2.  
  3. from collections import namedtuple
  4. #------------------------------------------------------------------------------80
  5.  
  6. PullOp = namedtuple("PullOp", "nid slot_id")
  7. Node = namedtuple("Node", "slots defaultArgs")
  8. Undefined = Ellipsis
  9.  
  10. nodeDB = {1: Node(slots=tuple(), defaultArgs=tuple()),
  11.           2: Node(slots=(PullOp(1,0),), defaultArgs=(Undefined,)),
  12.           3: Node(slots=(PullOp(2,1),), defaultArgs=(Undefined,)),
  13.           4: Node(slots=(PullOp(2,0), PullOp(3,2)), defaultArgs=(Undefined, Undefined)),
  14.           5: Node(slots=(PullOp(3,0),), defaultArgs=(Undefined,)),
  15.           6: Node(slots=(PullOp(4,0),), defaultArgs=(Undefined,))
  16. }
  17.  
  18. eval_stack = {2: ('a', 'b'), 4: (1, -1)}
  19. cc_stack = {(4,1): 'cc-x'}
  20.  
  21. nodes = {3: (Undefined,), 4: (Undefined, Undefined)}
  22. nodes_eval = (3, 4)
  23.  
  24.  
  25. def fresh_slot_value(nid, slot_id, slot_value):
  26.     ''' (PURE)
  27.    returns a fresh slot value from cc-stack, eval-stack or default
  28.    arguments, if the slot value is Undefined.
  29.  
  30.    The function needs read-only access to cc-stack, eval-stack, and nodeDB.
  31.    '''
  32.    
  33.     # if current slot-value is already 'defined' by a prior evaluation,
  34.     # then no need to change
  35.     if slot_value is not Undefined:
  36.         return slot_value
  37.  
  38.     #ELSE: if current slot-value is 'undefined'
  39.  
  40.     # 1) obtain value from cc-stack, if slot is in cc-stack
  41.     push_op = (nid, slot_id) # push operation (from cc-stack)
  42.     if push_op in cc_stack:
  43.         return cc_stack[(nid, slot_id)] # do push-operation
  44.    
  45.     # 2) obtain a value from eval-stack, if slot in eval-stack
  46.     pull_op = nodeDB[nid].slots[slot_id] # pull operation (from eval-stack)
  47.     if (pull_op.nid in eval_stack
  48.         and len(eval_stack[pull_op.nid])-1 >= pull_op.slot_id):
  49.         return eval_stack[pull_op.nid][pull_op.slot_id] # do pull-operation
  50.  
  51.     # otherwise take the default argument
  52.     return nodeDB[nid].defaultArgs[slot_id]
  53.     #END if
  54.    
  55.    
  56. new_nodes_eval = {nid:
  57.               tuple(fresh_slot_value(nid, slot_id, nodes[nid][slot_id])
  58.                     # for each slot of the current node
  59.                     for slot_id, _ in enumerate(nodeDB[nid].slots)
  60.                     )
  61.               # for all nodes in eval-nodes
  62.               for nid in nodes
  63.               }
  64.  
  65. print(new_nodes_eval)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement