What is 'Currying'?

前端 未结 18 1252
遥遥无期
遥遥无期 2020-11-21 05:26

I\'ve seen references to curried functions in several articles and blogs but I can\'t find a good explanation (or at least one that makes sense!)

18条回答
  •  悲&欢浪女
    2020-11-21 06:14

    If you understand partial you're halfway there. The idea of partial is to preapply arguments to a function and give back a new function that wants only the remaining arguments. When this new function is called it includes the preloaded arguments along with whatever arguments were supplied to it.

    In Clojure + is a function but to make things starkly clear:

    (defn add [a b] (+ a b))
    

    You may be aware that the inc function simply adds 1 to whatever number it's passed.

    (inc 7) # => 8
    

    Let's build it ourselves using partial:

    (def inc (partial add 1))
    

    Here we return another function that has 1 loaded into the first argument of add. As add takes two arguments the new inc function wants only the b argument -- not 2 arguments as before since 1 has already been partially applied. Thus partial is a tool from which to create new functions with default values presupplied. That is why in a functional language functions often order arguments from general to specific. This makes it easier to reuse such functions from which to construct other functions.

    Now imagine if the language were smart enough to understand introspectively that add wanted two arguments. When we passed it one argument, rather than balking, what if the function partially applied the argument we passed it on our behalf understanding that we probably meant to provide the other argument later? We could then define inc without explicitly using partial.

    (def inc (add 1)) #partial is implied
    

    This is the way some languages behave. It is exceptionally useful when one wishes to compose functions into larger transformations. This would lead one to transducers.

提交回复
热议问题