Practical use of curried functions?

后端 未结 10 862
粉色の甜心
粉色の甜心 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:43

    In and of itself currying is syntactic sugar. Syntactic sugar is all about what you want to make easy. C for example wants to make instructions that are "cheap" in assembly language like incrementing, easy and so they have syntactic sugar for incrementation, the ++ notation.

     t = x + y
     x = x + 1
    

    is replaced by t = x++ + y

    Functional languages could just as easily have stuff like.

    f(x,y,z) = abc 
    g(r,s)(z) = f(r,s,z). 
    h(r)(s)(z) = f(r,s,z)
    

    but instead its all automatic. And that allows for a g bound by a particular r0, s0 (i.e. specific values) to be passed as a one variable function.

    Take for example perl's sort function which takes sort sub list where sub is a function of two variables that evaluates to a boolean and list is an arbitrary list.

    You would naturally want to use comparison operators (<=>) in Perl and have sortordinal = sort (<=>) where sortordinal works on lists. To do this you would sort to be a curried function.
    And in fact sort of a list is defined in precisely this way in Perl.

    In short: currying is sugar to make first class functions more natural.

提交回复
热议问题