Pythonでカリー化
帰りの電車でHaskellの勉強をしていたはずが、なぜかPythonでカリー化を実装してしまいました。 型チェックも入っていますけど、これは実行時の型チェックですね。「型XはYまたはXとXのForkである」などの定義の仕方は僕の発想の斜め上を行っていたのでしばらく寝かせないと理解が進みません…。
def curry(argsType, resultType):
def _curry(f):
args = []
restArgsType = argsType
def foo(x):
argType = argsType.pop(0)
assert isinstance(x, argType)
args.append(x)
if argsType == []:
result = apply(f, args)
assert isinstance(result, resultType)
return result
def bar(y):
return foo(y)
return bar
return foo
return _curry
@curry([str], str)
def f(x):
return x
print f("hello") #-> hello
@curry([str, str], str)
def f(x, y):
return x + " " + y + "!"
print f("Hello")("Haskell") #-> Hello Haskell!
@curry([int, int, int], int)
def add(x, y, z):
return x + y + z
print add(1)(2)(3) #-> 6