[ prog / sol / mona ]

prog


e and the Stern-Brocot tree

35 2021-02-25 21:00

The additional building blocks used by the e spec:

# context
#    stack
#    matrixclass
#    storage
class Group:
   @ classmethod
   def kind (cls):
      pass

   def eval (self, ctx, stackpos):
      pass

   def show (self):
      pass

   def isfixed (self):
      pass

   def fixedlength (self):
      pass


class LoopGroup (ListGroup):
   class Loop:
      def __init__ (self, count, item):
         self.count = count
         self.item  = item

      def __len__ (self):
         return self.count

      def __getitem__ (self, key):
         return self.item
         # no slicing

   @ classmethod
   def kind (cls):
      return "loop"

   def __init__ (self, count, group):
      ListGroup.__init__ (self, LoopGroup.Loop (count, group))
      self.count = count
      self.group = group

   def show (self):
      return "Loop ({}, {})".format (self.count, self.group.show ())

   def isfixed (self):
      return self.group.isfixed ()

   def fixedlength (self):
      return self.count * self.group.fixedlength ()


class LoadGroup (Group):
   @ classmethod
   def kind (cls):
      return "load"

   def __init__ (self, name, fallback):
      self.name     = name
      self.fallback = fallback

   def eval (self, ctx, stackpos):
      MC      = ctx ["matrixclass"]
      stack   = ctx ["stack"      ]
      storage = ctx ["storage"    ]
      name    = self.name
      value   = storage.get (name)

      if value is None:
         self.fallback.eval (ctx, stackpos)
         storage [name] = MC.copy (stack [stackpos])
      else:
         MC.copyinto (value, stack [stackpos])

   def show (self):
      return "Load ({}, {})".format (self.name, self.fallback.show ())

   def isfixed (self):
      return False

   def fixedlength (self):
      raise Wrong


class StoreGroup (Group):
   @ classmethod
   def kind (cls):
      return "store"

   def __init__ (self, name, group):
      self.name  = name
      self.group = group

   def eval (self, ctx, stackpos):
      MC      = ctx ["matrixclass"]
      stack   = ctx ["stack"      ]
      storage = ctx ["storage"    ]
      name    = self.name
      group   = self.group

      group.eval (ctx, stackpos)
      # after
      m = storage.get (name)

      if m is None:
         storage [name] = MC.copy (stack [stackpos])
      else:
         MC.copyinto (stack [stackpos], m)

   def show (self):
      return "Store ({}, {})".format (self.name, self.group.show ())

   def isfixed (self):
      return self.group.isfixed ()

   def fixedlength (self):
      return self.group.fixedlength ()
54


VIP:

do not edit these