« 日記 |Main| log »

« Pythonで87文字でCollatz角谷問題の(以下略 | Python | 日記 »

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

トラックバック(Trackback)

Trackback URL: http://www.nishiohirokazu.org/mt/mt-tb.cgi/181

ご意見・ご感想をお送りください(フィードバック)

(フィードバックはメールで送信され、基本的に表示されませんが、内容によっては公開させていただくこともございます。ご了承ください。Your comment doesn't appear the page immediately. If the comment has value to other people, it will be put on the page or subsequent entries. Thank you.)

上の情報は、いずれも未記入でかまいません。 All of above questions are optional.