パイプ処理
関数型言語のパイプ処理をPythonで考えてみる。
理想は、
result = [3,1,2] |> sorted |> reversed ## [3,2,1]
実装
- 独自クラスで値と関数とラップする。
- 「|>」は、演算子にない。
→ 「>>」で代用。
独自クラスPIPE
PIPE.py
# >> でパイプ処理
class PIPE:
def __init__(self, val):
self.val = val
def __rshift__(self, other):
if callable(other.val):
return PIPE(other.val(self.val))
return other.val
def __str__(self):
return str(self.val)
Usage
result = PIPE([3,1,2]) >> PIPE(sorted)
print(result) # [1, 2, 3]
sample1
# lambdaもfunctionも使える。
# printも。
_ = PIPE([3,1,2]) \
>> PIPE(sorted) \
>> PIPE(reversed) \
>> PIPE(lambda lst: [l+1 for l in lst]) \
>> PIPE(list) \
>> PIPE(print) # [4, 3, 2]
sample2
## printでformat使いたい時。
_ = PIPE({"K0":1, "K1":2}) \
>> PIPE(lambda d: sum([v for k,v in d.items()])) \
>> PIPE(lambda s: "sum is {}".format(s)) \
>> PIPE(print) # sum is 3
sample3
_ = PIPE({"K0":1, "K1":2}) \
>> PIPE(lambda d: {k:v+1 for k,v in d.items()}) \
>> PIPE(lambda d: {k.replace("K", "KEY"): v for k,v in d.items()}) \
>> PIPE(print) # {'KEY0': 2, 'KEY1': 3}
まとめ
- パイプ処理できた。
-
print(list(reversed(sorted([3,1,2]))))より見やすい。 - 行末の「\」を忘れがち。
- 意外に汎用性が高い気がする。