Practical use of curried functions?

后端 未结 10 863
粉色の甜心
粉色の甜心 2020-12-14 07:01

There are tons of tutorials on how to curry functions, and as many questions here at stackoverflow. However, after reading The Little Schemer, several books, tutorials, blog

10条回答
  •  既然无缘
    2020-12-14 07:35

    One effective use of curried functions is decreasing of amount of code.

    Consider three functions, two of which are almost identical:

    (define (add a b)
      (action + a b))
    
    (define (mul a b)
      (action * a b))
    
    (define (action kind a b)
      (kind a b))
    

    If your code invokes add, it in turn calls action with kind +. The same with mul.

    You defined these functions like you would do in many imperative popular languages available (some of them have been including lambdas, currying and other features usually found in functional world, because all of it is terribly handy).

    All add and sum do, is wrapping the call to action with the appropriate kind. Now, consider curried definitions of these functions:

    (define add-curried
      ((curry action) +))
    
    (define mul-curried
      ((curry action) *))
    

    They've become considerable shorter. We just curried the function action by passing it only one argument, the kind, and got the curried function which accepts the rest two arguments.

    This approach allows you to write less code, with high level of maintainability.

    Just imagine that function action would immediately be rewritten to accept 3 more arguments. Without currying you would have to rewrite your implementations of add and mul:

    (define (action kind a b c d e)
      (kind a b c d e))
    
    (define (add a b c d e)
      (action + a b c d e))
    
    (define (mul a b c d e)
      (action * a b c d e))
    

    But currying saved you from that nasty and error-prone work; you don't have to rewrite even a symbol in the functions add-curried and mul-curried at all, because the calling function would provide the necessary amount of arguments passed to action.

提交回复
热议问题