Practical use of curried functions?

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

    They can make code easier to read. Consider the following two Haskell snippets:

    lengths :: [[a]] -> [Int]
    lengths xs = map length xs
    
    lengths' :: [[a]] -> [Int]
    lengths' = map length
    

    Why give a name to a variable you're not going to use?

    Curried functions also help in situations like this:

    doubleAndSum ys = map (\xs -> sum (map (*2) xs) ys
    
    doubleAndSum' = map (sum . map (*2))
    

    Removing those extra variables makes the code easier to read and there's no need for you to mentally keep clear what xs is and what ys is.

    HTH.

    0 讨论(0)
  • 2020-12-14 07:19

    You can see currying as a specialization. Pick some defaults and leave the user (maybe yourself) with a specialized, more expressive, function.

    0 讨论(0)
  • 2020-12-14 07:19

    It is very easy to create closures. From time to time i use SRFI-26. It is really cute.

    0 讨论(0)
  • 2020-12-14 07:21

    Using all :: (a -> Bool) -> [a] -> Bool with a curried predicate.

    all (`elem` [1,2,3]) [0,3,4,5]
    

    Haskell infix operators can be curried on either side, so you can easily curry the needle or the container side of the elem function (is-element-of).

    0 讨论(0)
  • 2020-12-14 07:25

    I would like to add example to @Francesco answer.

    enter image description here

    0 讨论(0)
  • 2020-12-14 07:26

    I think that currying is a traditional way to handle general n-ary functions provided that the only ones you can define are unary.

    For example, in lambda calculus (from which functional programming languages stem), there are only one-variable abstractions (which translates to unary functions in FPLs). Regarding lambda calculus, I think it's easier to prove things about such a formalism since you don't actually need to handle the case of n-ary functions (since you can represent any n-ary function with a number of unary ones through currying).

    (Others have already covered some of the practical implications of this decision so I'll stop here.)

    0 讨论(0)
提交回复
热议问题