Skip to content

Instantly share code, notes, and snippets.

@FuruNov
Last active March 26, 2023 23:34
Show Gist options
  • Select an option

  • Save FuruNov/0a3b34a3706ee311e7ad452f999a6828 to your computer and use it in GitHub Desktop.

Select an option

Save FuruNov/0a3b34a3706ee311e7ad452f999a6828 to your computer and use it in GitHub Desktop.
中置演算子を擬似的に定義する Python プログラム
class Infix:
def __init__(self, func):
self.func = func
def __ror__(self, other):
return Infix(lambda x: self.func(other, x))
def __or__(self, other):
return self.func(other)
class Op:
def __init__(self, symbol):
self.symbol = symbol
def __ror__(self, other):
if self.symbol == "+":
return Infix(lambda x: other + x)
elif self.symbol == "-":
return Infix(lambda x: other - x)
elif self.symbol == "*":
return Infix(lambda x: other * x)
elif self.symbol == "/":
return Infix(lambda x: other / x)
else:
raise ValueError("Invalid symbol")
a = 5
b = 10
result = a |Op("*")| b
print(result) # 50
@FuruNov
Copy link
Author

FuruNov commented Mar 26, 2023

Memo:
文字列 |>, <| に関数の部分適用(partial)を割り当てたい
文字列 . に関数の合成を割り当てたい

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment