3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonで関数型プログラミングのパイプやってみる

3
Last updated at Posted at 2019-11-13

パイプ処理

関数型言語のパイプ処理を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]))))より見やすい。
  • 行末の「\」を忘れがち。
  • 意外に汎用性が高い気がする。
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?