I found some good posts about what is curry and what it can do. It can transform a function with list of parameter to a list of function. I am not clear in what scenario this is useful. Can anyone give me one concrete example ?
Asked
Active
Viewed 223 times
0
-
1As far as Scala in particular is concerned, [it helps with type inference (and more)](http://stackoverflow.com/a/7287481/1180426) (see: implementation of all `fold`s) – Patryk Ćwiek Aug 26 '15 at 08:54
-
possible duplicate of http://stackoverflow.com/questions/8063325/usefulness-as-in-practical-applications-of-currying-v-s-partial-application-i – shanmuga Aug 26 '15 at 09:08
1 Answers
5
Currying does not transform a function with a list of parameters to a list of functions. It transforms a function with more than one argument to a function that takes one argument and returns a function that takes the rest of the arguments, recursively. For example:
scala> def f(x: Int, y: Int, z:Int) = x + y + z
ff: (x: Int, y: Int, z: Int)Int
scala> (f _).curried
res4: Int => (Int => (Int => Int)) = <function1>
The first function takes 3 parameters. The second function takes one parameter, and returns a function that takes another parameter, that takes an int and returns the sum of all three.
Why is this useful in practice? It helps in creating function objects without having to write closures. Consider a function f(pat, dir)
that looks for files matching a pattern in a directory. Now you want to look for the same pattern in multiple directories stored in a list dirs
. You can use
val ff = (f _).curried
dirs.map(ff(pat))

Little Bobby Tables
- 5,261
- 2
- 39
- 49