How are functions curried?

前端 未结 2 1407
生来不讨喜
生来不讨喜 2021-02-19 04:23

I understand what the concept of currying is, and know how to use it. These are not my questions, rather I am curious as to how this is actually implemented at some lower level

2条回答
  •  我在风中等你
    2021-02-19 05:06

    Try it out with GHC:

    ghc -C Test.hs
    

    This will generate C code in Test.hc

    I wrote the following function:

    f = (+) 16777217
    

    And GHC generated this:

    R1.p[1] = (W_)Hp-4;
    *R1.p = (W_)&stg_IND_STATIC_info;
    Sp[-2] = (W_)&stg_upd_frame_info;
    Sp[-1] = (W_)Hp-4;
    R1.w = (W_)&integerzmgmp_GHCziInteger_smallInteger_closure;
    Sp[-3] = 0x1000001U;
    Sp=Sp-3;
    JMP_((W_)&stg_ap_n_fast);
    

    The thing to remember is that in Haskell, partially applying is not an unusual case. There's technically no "last argument" to any function. As you can see here, Haskell is jumping to stg_ap_n_fast which will expect an argument to be available in Sp.

    The stg here stands for "Spineless Tagless G-Machine". There is a really good paper on it, by Simon Peyton-Jones. If you're curious about how the Haskell runtime is implemented, go read that first.

提交回复
热议问题