Last active
March 26, 2023 23:34
-
-
Save FuruNov/0a3b34a3706ee311e7ad452f999a6828 to your computer and use it in GitHub Desktop.
中置演算子を擬似的に定義する Python プログラム
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
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Memo:
文字列 |>, <| に関数の部分適用(partial)を割り当てたい
文字列 . に関数の合成を割り当てたい