Consider pipe processing in a functional language in Python.
The ideal is
result = [3,1,2] |> sorted |> reversed ## [3,2,1]
--Wrap with values and functions in your own class. --"|>" is not in the operator. → Substitute with ">>".
PIPE.py
# >>Pipe processing with
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
#You can use both lambda and function.
#print too.
_ = 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
##When you want to use format with print.
_ = 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}
--Pipe processing was possible.
--Easy to read than print (list (reversed (sorted ([3,1,2]))))
.
--It's easy to forget the "\" at the end of the line.
――I feel that it is surprisingly versatile.
Recommended Posts