How do I simplify this transitive application in Scala - 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.

Related

Use of underscore in function call with Try parameters

I'm trying to understand particular use of underscore in Scala. And following piece of code I cannot understand
class Test[T, S] {
def f1(f: T => S): Unit = f2(_ map f)
def f2(f: Try[T] => Try[S]): Unit = {}
}
How is the _ treated in this case? How is the T=>S becomes Try[T]=>Try[S]?
It seems you are reading it wrongly. Look at the type of f2(Try[T] => Try[S]):Unit.
Then looking into f1 we have f: T => S.
The _ in value position desugars to f2(g => g map f).
Let's see what we know so far:
f2(Try[T] => Try[S]):Unit
f: T => S
f2(g => g map f)
Give 1. and 3. we can infer that the type of g has to be Try[T]. map over Try[T] takes T => Something, in case f which is T => S, in which case Something is S.
It may seem a bit hard to read now, but once you learn to distinguish between type and value position readin this type of code becomes trivial.
Another thing to notice def f2(f: Try[T] => Try[S]): Unit = {} is quite uninteresting and may be a bit detrimental in solving your particular question.
I'd try to solve this like that: first forget the class you created. Now implement this (replace the ??? with a useful implementation):
object P1 {
def fmap[A, B](A => B): Try[A] => Try[B] = ???
}
For bonus points use the _ as the first char in your implementation.

Writing a function to curry any function

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?

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

Implementing a higher order function that performs currying in scala

A coworker of mine sent me a question as follows:
Implement a HOF(higher order function) that performs currying, the
signature of your function is as follows:
def curry[A,B,C](f:(A,B) => C) : A => B => C
Similarly, implement a function that performs uncurrying as follows:
def uncurry[A,B,C](f:A => B => C): (A,B) => C
The way I understand currying is that if you have a function that takes multiple parameters, you can repeatedly apply the function to each one of the paramaters until you get the result.
So something along the lines of f:(A,B) => C turns into A => f(A,_) => f(B)????
And uncurrying would be to consolidate this application into one function as follows:
f:A=>B=>C would be f(A,B)?
Maybe I am just being confused by the syntax here but it would be great if somebody could point out what I am missing here.
Thanks
Hopefully this fully worked example with a bunch of comments is easy to understand. Please reply if you have questions.
You can execute this code by dropping it in a Scala interpreter.
// Here's a trait encapsulating the definition your coworker sent.
trait Given {
def curry[A,B,C](f:(A,B) => C) : A => B => C
def uncurry[A,B,C](f:A => B => C): (A,B) => C
}
object Impl extends Given {
// I'm going to implement uncurry first because it's the easier of the
// two to understand. The bit in curly braces after the equal sign is a
// function literal which takes two arguments and applies the to (i.e.
// uses it as the arguments for) a function which returns a function.
// It then passes the second argument to the returned function.
// Finally it returns the value of the second function.
def uncurry[A,B,C](f:A => B => C): (A,B) => C = { (a: A, b: B) => f(a)(b) }
// The bit in curly braces after the equal sign is a function literal
// which takes one argument and returns a new function. I.e., curry()
// returns a function which when called returns another function
def curry[A,B,C](f:(A,B) => C) : A => B => C = { (a: A) => { (b: B) => f(a,b) } }
}
def add(a: Int, b: Long): Double = a.toDouble + b
val spicyAdd = Impl.curry(add)
println(spicyAdd(1)(2L)) // prints "3.0"
val increment = spicyAdd(1) // increment holds a function which takes a long and adds 1 to it.
println(increment(1L)) // prints "2.0"
val unspicedAdd = Impl.uncurry(spicyAdd)
println(unspicedAdd(4, 5L)) // prints "9.0"
How about a less numerical example?
def log(level: String, message: String) {
println("%s: %s".format(level, message))
}
val spicyLog = Impl.curry(log) // spicyLog's type is String => Unit
val logDebug = spicyLog("debug") // This new function will always prefix the log
// message with "debug".
val logWarn = spicyLog("warn") // This new function will always prefix the log
// message with "warn".
logDebug("Hi, sc_ray!") // prints "debug: Hi, sc_ray!"
logWarn("Something is wrong.") // prints "warn: Something is wrong."
Update
You replied asking "How does the compiler evaluate expressions such as a => b => f(a,b)." Well it doesn't. At least the way things are defined in your coworker's snippet, that wouldn't compile. In general, though, if you see something of the form A => B => C that means "a function which takes an A as an argument; it returns a function which takes a B as an argument and returns a C."
I'm not sure I really understand your question - what would you like to know, besides the actual implementation? As described, it should be quite trivial:
def curry[A,B,C](f:(A,B) => C): A => B => C =
a => b => f(a,b)
What a => b => f(a,b) means is, "a function of one argument, a, whose return value is b => f(a,b) which is again, a function of one argument, b, whose return value is what you get of you execute f(a,b) (whose type is C)"
a => b => f(a, b) can be written slightly more verbosely if it helps?
{ (a: A) => { // a function of *one* argument, `a`
(b: B) => { // a function of *one* argument, `b`
f(a, b) // whose return value is what you get of you execute `f(a,b)` (whose type is `C`)
}
}
}
and
def uncurry[A,B,C](f:A => B => C): (A,B) => C =
(a, b) => f(a)(b)
Where (a, b) => f(a)(b) means, "A function of two arguments (a, b), whose return value is what you get when you first apply a to the HoF f, which returns a function that in turn consumes the b to return a C".
Does that help?