Writing a function to curry any function - scala

For the record I find it very annoying that functions are not automatically curried in Scala. I'm trying to write a factory that takes in any function and returns a curried version:
def curry(fn:(_ => _)) = (fn _).curried
Basically what I have defined here is a function curry that takes as an argument a function fn that is of type _ => _ and returns a curried version of function fn. Obviously this didnt work because Java.
This was the error I got:
error: _ must follow method; cannot follow fn.type
def curry(fn:(_ => _)) = (fn _).curried
Can any gurus out there help me figure out why this doesnt work? I don't mean to sound snarky, I am used to functional languages treating all types as functions. Please help this Scala newbie.
(I tagged this question with haskell because I'm trying to get Scala functions to behave like Haskell functions :'(
UPDATE
Just to clarify, I need a curryN function, so a function that curries any other function regardless of its arity.
Side note, some people have pointed out that increasing the number of fn's arguments would solve the problem. Nope:
def curry2(fn:((_, _) => _)) = (fn _).curried
error: _ must follow method; cannot follow fn.type
def curry2(fn:((_, _) => _)) = (fn _).curried

Scala doesn't allow you to abstract over the arity of a function. Thus, you need to use a typeclass-style approach (which allows you to abstract over just about anything, after you do all the manual work for it).
So, in particular, you do something like
sealed trait FunctionCurrier[Unc, Cur] { def apply(fn: Unc): Cur }
final class Function2Currier[A, B, Z]
extends FunctionCurrier[(A, B) => Z, A => B => Z] {
def apply(fn: (A, B) => Z): (A => B => Z) = fn.curried
}
// Repeat for Function3 through Function21
implicit def makeCurrierForFunction2[A, B, Z]: Function2Currier[A, B, Z] =
new Function2Currier[A, B, Z]
// Again, repeat for Function3 through Function21
def curryAll[Unc, Cur](fn: Unc)(implicit cf: FunctionCurrier[Unc, Cur]): Cur =
cf(fn)
Now you can use it like so:
scala> def foo(a: Int, b: String) = a < b.length
foo: (a: Int, b: String)Boolean
scala> curryAll(foo _)
res0: Int => (String => Boolean) = <function1>
There is probably already something like this in Shapeless, but in this case you can roll your own, albeit with some tedium (and/or a code generator).
(Note: if you want to "curry" A => Z, you can write a Function1Currier that just returns the function untouched.)

This can be done using the curried method of functions. You need to access the function itself as a partially applied function and get its curried form, like so:
def fn(i: Int, j: Int) = i + j
val fnCurryable = (fn _).curried
val fnCurried = fnCurryable(1)
println(fnCurried(2))
//prints 3
The same second line would work to curry any function with 2-22 arguments due to scala's powerful type inference. Also, remember that you can declare your functions to be curryable in their declaration. This would do the same as above:
def fnCurryable(i: Int)(j: Int) = i + j
The use of multiple argument lists means this function is called as fnCurryable(1)(2) and can NEVER be called as fnCurryable(1, 2). This conversion is basically what .curried does.
This is based on the function traits described on:
http://www.scala-lang.org/api/2.11.8/index.html#scala.package

def toCurry[A](f: (A, A) => A): A => A => A = x => f(x, _)
val addTwoNum = (x: Int, y: Int) => x + y
val curriedAddTwoNum = toCurry(addTwoNum)
val part1Curry = curriedAddTwoNum(5)
println(part1Curry(2))
For additional arity, you would simply need to add additional params to the above function definition.
Otherwise, you may want to do something like Can you curry a function with varargs in scala?

Related

Why should calling a currying function with non-complete args with underscore

According to ScalaByExample:
A curried function definition def f (args1) ... (argsn) = E where n >
1 expands to
def f (args1) ... (argsn−1) = { def g (argsn) = E ; g }
Or, shorter, using an anonymous function:
def f (args1) ... (argsn−1) = ( argsn ) => E
Uncurried version:
def f(x: Int): Int => Int = {
y: Int => x * y
} //> f: (x: Int)Int => Int
def f1 = f(10) //> f1: => Int => Int
f1(5)
Curried version:
def g(x: Int)(y: Int) = {
x * y
} //> g: (x: Int)(y: Int)Int
def g1 = g(10) _ //> g1: => Int => Int
g1(5)
The question is, Why curried required the underscore in line #5 in the second code snippet.
You can find the explanation at Martin Odersky book: http://www.artima.com/pins1ed/functions-and-closures.html (search for "Why the trailing underscore").
In short this is because Scala is closer to Java in a lot of things, rather than functional languages where this is not required. This helps you to find out mistakes at compile time, if you forgot the missing argument.
If underscore was not required, the next code will compile:
println(g(10))
And this check helps you preventing such mistakes
There are some cases though, when such calls are obvious, and underscore is not required:
def g(x: Int)(y: Int) = {
x * y
}
def d(f: Int => Int) {
f(5)
}
d(g(10)) // No need to write d(g(2) _)
// Or any other way you can specify the correct type
val p: Int => Int = g(10)
Something to note: in Scala, def's are methods, not functions, at least, not directly. Methods are converted to functions by the compiler every time a method is used where a function would be required, but strictly speaking, a function would be created with val instead, like so:
val curry = (x: Int) => (y: Int) => x * y
This allows you to apply arguments one at a time without having to add a trailing underscore. It functions identically to the code in your first snippet, but because it uses val and not def, curry cannot be written like
val curry(x: Int) = (y: Int) => x * y //Won't compile
So, when you want to write a function that behaves the way you want a curried function to behave, write it like I did in my first snippet. You can keep chaining parameters with => as many times as you want (up to technical limits, but good luck hitting them).

Executing and getting return value of a function wrapped in a context?

I have a function in a context, (in a Maybe / Option) and I want to pass it a value and get back the return value, directly out of the context.
Let's take an example in Scala :
scala> Some((x:Int) => x * x)
res0: Some[Int => Int] = Some(<function1>)
Of course, I can do
res0.map(_(5))
to execute the function, but the result is wrapped in the context.
Ok, I could do :
res0.map(_(5)).getOrElse(...)
but I'm copy/pasting this everywhere in my code (I have a lot of functions wrapped in Option, or worst, in Either...).
I need a better form, something like :
res0.applyOrElse(5, ...)
Does this concept of 'applying a function in a concept to a value and immediatly returning the result out of the context' exists in FP with a specific name (I'm lost in all those Functor, Monad and Applicatives...) ?
You can use andThen to move the default from the place where you call the function to the place where you define it:
val foo: String => Option[Int] = s => Some(s.size)
val bar: String => Int = foo.andThen(_.getOrElse(100))
This only works for Function1, but if you want a more generic version, Scalaz provides functor instances for FunctionN:
import scalaz._, Scalaz._
val foo: (String, Int) => Option[Int] = (s, i) => Some(s.size + i)
val bar: (String, Int) => Int = foo.map(_.getOrElse(100))
This also works for Function1—just replace andThen above with map.
More generally, as I mention above, this looks a little like unliftId on Kleisli, which takes a wrapped function A => F[B] and collapses the F using a comonad instance for F. If you wanted something that worked generically for Option, Either[E, ?], etc., you could write something similar that would take a Optional instance for F and a default value.
You could write something like applyOrElse using Option.fold.
fold[B](ifEmpty: ⇒ B)(f: (A) ⇒ B): B
val squared = Some((x:Int) => x * x)
squared.fold {
// or else = ifEmpty
math.pow(5, 2).toInt
}{
// execute function
_(5)
}
Using Travis Browns recent answer on another question, I was able to puzzle together the following applyOrElse function. It depends on Shapeless and you need to pass the arguments as an HList so it might not be exactly what you want.
def applyOrElse[F, I <: HList, O](
optionFun: Option[F],
input: I,
orElse: => O
)(implicit
ftp: FnToProduct.Aux[F, I => O]
): O = optionFun.fold(orElse)(f => ftp(f)(input))
Which can be used as :
val squared = Some((x:Int) => x * x)
applyOrElse(squared, 2 :: HNil, 10)
// res0: Int = 4
applyOrElse(None, 2 :: HNil, 10)
// res1: Int = 10
val concat = Some((a: String, b: String) => s"$a $b")
applyOrElse(concat, "hello" :: "world" :: HNil, "not" + "executed")
// res2: String = hello world
The getOrElse is most logical way to do it. In regards to copy/pasting it all over the place - you might not be dividing your logic up on the best way. Generally, you want to defer resolving your Options (or Futures/etc) in your code until the point you need to have it unwrapped. In this case, it seems more sensible that your function takes in an an Int and returns an Int, and you map your option where you need the result of that function.

Understanding Scala: passing functions as arguments

I'm starting to learn Scala and I've come across a snippet from the Programming in Scala textbook which I don't quite understand. Was hoping some one could help me?
This is from Listing 9.1 from Programming in Scala, 2nd Edition.
object FileMatcher {
private def filesHere = (new java.io.File(".")).listFiles
}
private def filesMatching(matcher: String => Boolean) =
for (file <- filesHere; if matcher(file.getName)) yield file
def filesEnding(query: String) =
filesMatching(_.endsWith(query)) // ???
def filesContaining(query: String) =
filesMatching(_.contains(query)) // ???
def filesRegex(query: String) =
filesMatching(_.matches(query)) // ???
I'm a little confused with the lines that have // ???. Does the use of the _ somehow create an anonymous function that is passed to filesMatching? Or does the _ have nothing to do with this, and instead the compiler sees that filesMatching requires a function and therefore doesn't execute _.endsWith(query) as an expression but instead makes the expression a function?
extended definition
Anonymous function are defined, in their more verbose and complete form, as
(a: A, b: B, ...) => function body //using a, b, ...
E.g.
(a: String, b: String) => a ++ b // concatenates 2 Strings
inferred types
if the context provides the needed information (as when a higher order function expects a specific signature for its function arguments), you can omit the parameters' types, as
(a, b, ...) => function body //using a, b, ...
E.g.
val l = List(1, 2, 3)
//you can omit the type because filter on List[Int] expects a (Int => Boolean)
l.filter(i => i < 3)
placeholder syntax
Finally you can use a shorter form still, if your parameters are used once each and in the same order that you declare them, by the function body, as
_ ++ _ // which is equivalent to (a, b) => a ++ b
Each _ is a placeholder for the function's arguments
E.g.
filesMatching's argument is a function of type String => Boolean so you can use
_.endsWith(query) // equivalent to (s: String) => s.endsWith(query)
_.contains(query) // equivalent to (s: String) => s.contains(query)
_.matches(query) // equivalent to (s: String) => s.matches(query)
The _ as used here is shorthand for a function argument. Thus filesMatching(_.endsWith(query)) is equivalent to filesMatching(f => f.endsWith(query)). As filesMatching has as argument a function of String => Boolean, the compiler can infer that f is expected to be a String here. So you are right that this expression is an anonymous function.
This kind of operation is best done by defining function types. I found an excellent demonstration here. Combined with this post, the demonstration should clarify best practices for passing functions as arguments

How do I simplify this transitive application in Scala

For a given function call f, with arguments a, b, and c, that calls function g using functions h and i to build the arguments, I can say:
f(a)(b)(c) = g( h(a)(b)(c), i(a)(b)(c) )
I know that I can create a function such that:
g'(h,i)(a)(b)(c) = g(h(a)(b)(c), i(a)(b)(c))
so that f can be
f = g'(h,i)
and thusly applying f(a)(b)(c) will yield the desired result.
I can brute force this from (where f becomes build):
def build(a: String)(b: String)(c: String) =
Message(convA(a)(b)(c), convB(a)(b)(c))
to (given that h and i aren't important to be arguments, maybe this is where the disconnect is):
def gDash = {
a:String => b: String => c: String => Message(convA(a)(b)(c), convB(a)(b)(c))
}
def build = a:String => b:String => c:String => gDash(a,b,c)
but I still have to specify the entire typing for (a,b,c). But I've gone from something that should be more complex and fragile to something simpler, but the implementation is actually a bigger mess! Is there a way to simplify this that doesn't require all this?
If I tupleize the arguments so that:
def gDash = implicit composite:(String,String,String) => Message(convA, convB)
def convA(composite: s) => ...
def convB(composite: s) => ...
def f(a: String)(b: String)(c: String) = gDash((a,b,c))
I'm not sure that's actually better, I feel like I'm missing something.
Methods require you to be explicit with parameters. Tuples can have type aliases assigned to them, which can help with the excess typing:
type S3 = (String, String, String)
And you can go back and forth between functions (A, B) => C and A => B => C with curried and Function.uncurried.
These give you the tools that you need to make more compact representations of your functions. For example, if you want something called build that has form String => String => String => Whatever, you could
val build = ((abc: S3) => Message(convA(abc), convB(abc)).curried
and then if you want to write gDash in place of Message you could do something like
def dash[A,B,C,D,E](g: (A,B) => C)(h: E=>A, i: E=>B): E => C =
(e: E) => g(h(e),i(e))
and then uncurry on the way in if you want E to actually be three separate string parameters.

Usefulness (as in practical applications) of Currying v.s. Partial Application in Scala

I'm trying to understand the advantages of currying over partial applications in Scala. Please consider the following code:
def sum(f: Int => Int) = (a: Int, b: Int) => f(a) + f(b)
def sum2(f: Int => Int, a: Int, b: Int): Int = f(a) + f(b)
def sum3(f: Int => Int)(a: Int, b: Int): Int = f(a) + f(b)
val ho = sum({identity})
val partial = sum2({ identity }, _, _)
val currying = sum3({ identity })
val a = currying(2, 2)
val b = partial(2, 2)
val c = ho(2, 2)
So, if I can calculate partially applied function that easy, what are the advantages of currying?
Currying is mostly used if the second parameter section is a function or a by name parameter. This has two advantages. First, the function argument can then look like a code block enclosed in braces. E.g.
using(new File(name)) { f =>
...
}
This reads better than the uncurried alternative:
using(new File(name), f => {
...
})
Second, and more importantly, type inference can usually figure out the function's parameter type, so it does not have to be given at the call site.
For instance, if I define a max function over lists like this:
def max[T](xs: List[T])(compare: (T, T) => Boolean)
I can call it like this:
max(List(1, -3, 43, 0)) ((x, y) => x < y)
or even shorter:
max(List(1, -3, 43, 0)) (_ < _)
If I defined max as an uncurried function, this would not work, I'd have to call it like this:
max(List(1, -3, 43, 0), (x: Int, y: Int) => x < y)
If the last parameter is not a function or by-name parameter, I would not advise currying. Scala's _ notatation is amost as lightweight, more flexible, and IMO clearer.
I think it becomes clearer if you invert your curried example:
def sum4(a: Int, b: Int)(f: Int => Int): Int = f(a) + f(b)
val d = sum4(2, 2) { x =>
x * x
}
It is more of an optical effect but you don’t need to use any parentheses around the whole expression. Of course you can achieve the same result using partial application or by creating a helper method to invert the arguments, sure. The point is, that you don’t have to do all of this if you start with a curried method in the first place. In that sense currying is more of an API and syntax sugar thing. It is not expected that you use
val partial_sum4 = sum4(2, 2)
anywhere in your code or that this is in any way especially meaningful to do. It is just that you get a nicely looking expression easily.
(Well, and there are some advantages with respect to type inference…)