top | item 37461230

(no title)

miahwilde | 2 years ago

  # The Belt.
  def belt():
      # return itertools.cycle([1,2,3,4,5])
      x = 1
      while True:
          yield x
          x += 1
          if x > 5:
              x = 1
  
  # The +1
  def add1(iterable):
      for x in iterable:
          yield x + 1
  
  # The +y
  def add(y):
      def _(iterable):
          for x in iterable:
              yield x + y
      return _
  
  # The Oddifier
  def oddonly(iterable):
      for x in iterable:
          if x % 2 == 1:
              yield x

  # The Reaper
  def partition(n):
      assert n > 0
      def _(iterable):
          batch = []
          for x in iterable:
              batch.append(x)
              if len(batch) == n:
                  yield batch
                  batch = []
          if batch:
              yield batch
      return _
  
  # The Composer
  def compose(iterable, t1, t2):
      yield from t2(t1(iterable))
  
  # The Plumber
  def pipe(iterable, p):
      for xform in p:
          iterable = xform(iterable)
      yield from iterable
  
  # The Press.
  def printall(iterator):
      import time
      for x in iterator:
          print(x, end=", ", flush=True)
          time.sleep(0.3)
  
  # printall(pipe(belt(), [add(1)]))  # 2, 3, 4, 5, 6, 2, 3, 4...
  # printall(pipe(belt(), [add(1), oddonly]))  # 3, 5, 3, 5, ...
  printall(pipe(belt(), [add(1), oddonly, partition(3)]))  # [3, 5, 3], [5, 3, 5], ...

discuss

order

No comments yet.