Created
June 7, 2012 13:11
-
-
Save fumieval/2888725 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import itertools | |
class SingleMix(object): | |
def __init__(self, x): self._x = x | |
def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self._x) | |
class InfixMix(object): | |
def __init__(self, left, right): | |
self._left = left | |
self._right = right | |
def __repr__(self): | |
return "(%r %s %r)" % (self._left, self.__class__.op, self._right) | |
class Processor: | |
def __rshift__(self, other): | |
return ProcessorComposite(self, other) | |
class ProcessorComposite(Processor, InfixMix): | |
op = ">>" | |
__init__ = InfixMix.__init__ | |
def __call__(self, stream): | |
return self._right(self._left(stream)) | |
class Map(Processor, SingleMix): | |
__init__ = SingleMix.__init__ | |
def __call__(self, stream): | |
return itertools.imap(self._x, stream) | |
class Filter(Processor, SingleMix): | |
__init__ = SingleMix.__init__ | |
def __call__(self, stream): | |
return itertools.ifilter(self._x, stream) | |
class SplitBy(Processor, SingleMix): | |
"""split iterables by a element which satisfies the predicate.""" | |
def __init__(self, predicate): | |
SingleMix.__init__(self, predicate) | |
self.cont = True | |
def __iters(self, iterable): | |
for i in iterable: | |
if self._x(i): | |
return | |
yield i | |
self.cont = False | |
def __call__(self, stream): | |
while self.cont: | |
yield self.__iters(stream) | |
def iterate(function): | |
while True: | |
yield function() | |
#ここまでライブラリ | |
def iterstream(stream): | |
return (SplitBy("\n".__eq__) | |
>> Map("".join) >> Map(flip(str.strip)("\r")) | |
>> Filter("".__ne__))(iterate(lambda: stream.read(1))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment