what is wrong with this partially applied function attempt? - scala

I am trying to write a partially applied function. I thought the below would work but it doesn't. Grateful for any help.
scala> def doSth(f: => Unit) { f }
doSth: (f: => Unit)Unit
scala> def sth() = { println ("Hi there") }
sth: ()Unit
scala> doSth(sth)
Hi there
scala> val b = sth _
b: () => Unit = <function0>
scala> doSth(b)
<console>:11: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
doSth(b)
^
Thanks!

The difference is subtle. sth is a method, so you can call it without the parentheses, which is what is happening here:
doSth(sth)
But b is just a function () => Unit, which you must use the parentheses to invoke.
doSth(b())
Otherwise you would not be able to assign b to another identifier.
val c: () => Unit = b
If we automatically invoked b here, c would be Unit instead of () => Unit. The ambiguity must be removed.
Let me also clarify that doSth is not a method that accepts only functions. f: => Unit means it accepts anything that evaluates to Unit, which includes methods that return Unit when they are invoked. doSth(sth) is not passing the message sth to doSth, it's invoking sth without parentheses and passing the result.

I think the difference is that b has type () => Unit, and doSth expects an expression that returns Unit (minor difference). If you want to store sth as a variable without the side effects, you could do:
lazy val b = sth
doSth(b)
The other option would be to make it so that doSth takes in () => Unit:
def doSth(f: () => Unit) { f() }
def sth() = { println ("Hi there") }
doSth(sth)
val b = sth _
doSth(b)

Related

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.

scala -- syntax to indicate any kind of anonymous function, whatsoever

I'd like to be able to pass in callback functions as parameters to a method. Right now, I can pass in a function of signature () => Unit, as in
def doSomething(fn:() => Unit) {
//... do something
fn()
}
which is fine, I suppose, but I'd like to be able to pass in any function with any parameters and any return type.
Is there a syntax to do that?
Thanks
To be able to execute a function passed as a callback you have to be able to call it with the arguments it requires. f: A => R must be called as f(someA), and g: (A,B) => R must be called as f(someA, someB).
Implementing a callback you want a function that accepts a context and returns something (you don't care what the something is). For example foreach in scala.Option is defined as:
def foreach[U](f: (A) => U): Unit
The function is called with a value of type A but the result is discarded so we don't care what type it has. Alternatively if you don't care what was completed the callback function could be implemented as:
def onComplete[U](f: () => U): Unit
It would then allow being called with any function that takes no arguments:
val f: () => Int = ...
val g: () => String = ...
onComplete(f) // In result is discarded
onComplete(g) // String result is discarded
If you really wanted a function that accepted any possible function there are some tricks you could use (but you really shouldn't). For example you could define a view bound with implicit conversions:
// Type F is any type that can be converted to () => U
def onComplete[F <% () => U, U](f: F): Unit
// Define conversions for each Function type to Function0
implicit def f1tof0[A,U](f: A => U): () => U = ...
implicit def f2tof0[A,B,U](f: (A,B) => U): () => U = ...
implicit def f3tof0[A,B,C,U](f: (A,B,C) => U): () => U = ...
.
.
etc.
Now onComplete accepts any function:
val f: Int => String = ...
val g: (List[Int], String) => String = ...
onComplete(f)
onComplete(g)
Defining the types for the above conversions is relatively simple, but there is no rational way to implement them so is pretty much entirely useless.

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

Repeated parameters of by-name/lazy functions

I want to have a function that takes a variable number of functions, but I want them to not be evaluated until I actually used them. I could use the () => type syntax, but I would prefer to use the => type syntax, because it seems to be custom made for delaying evaluation.
When I try something like this:
def functions(fns: => String*) = "OK"
I get the error:
error: ')' expected but identifier found.
def functions(fns: => String*) = "OK"
Interestingly, it works fine when I change it to
def functions(fns: () => String*) = "OK"
What do I have to do to get my first function to work?
Since I submitted the issue:
https://issues.scala-lang.org/browse/SI-5787
It may yet happen.
Depending on your semantics, consider using Stream[String], which evaluates lazily.
def foo(i: Int): String = { println(s"Numbering $i"); s"Number $i" }
val invocations = foo(2) #:: foo(4) #:: foo(5) #:: foo(8) #:: Stream.empty
Edit: Then I thought, didn't someone just ask that? A couple of more answers here using implicits. I think my answer there should be up-voted just for "This used to happens first".
For now, you have to use () => X* for repeated parameters. This makes entering them a pain, so you may wish to
implicit def anything_to_function0[A](a: => A): () => A = () => a
scala> def functions(fns: () => String*) = fns.length
functions: (fns: () => String*)Int
scala> functions("salmon","cod")
res2: Int = 2

Help me understand this Scala code: scalaz IO Monad and implicits

This is a followup to this question.
Here's the code I'm trying to understand (it's from http://apocalisp.wordpress.com/2010/10/17/scalaz-tutorial-enumeration-based-io-with-iteratees/):
object io {
sealed trait IO[A] {
def unsafePerformIO: A
}
object IO {
def apply[A](a: => A): IO[A] = new IO[A] {
def unsafePerformIO = a
}
}
implicit val IOMonad = new Monad[IO] {
def pure[A](a: => A): IO[A] = IO(a)
def bind[A,B](a: IO[A], f: A => IO[B]): IO[B] = IO {
implicitly[Monad[Function0]].bind(() => a.unsafePerformIO,
(x:A) => () => f(x).unsafePerformIO)()
}
}
}
This code is used like this (I'm assuming an import io._ is implied)
def bufferFile(f: File) = IO { new BufferedReader(new FileReader(f)) }
def closeReader(r: Reader) = IO { r.close }
def bracket[A,B,C](init: IO[A], fin: A => IO[B], body: A => IO[C]): IO[C] = for { a <- init
c <- body(a)
_ <- fin(a) } yield c
def enumFile[A](f: File, i: IterV[String, A]): IO[IterV[String, A]] = bracket(bufferFile(f),
closeReader(_:BufferedReader),
enumReader(_:BufferedReader, i))
I'm now trying to understand the implicit val IOMonad definition. Here's how I understand it. This is a scalaz.Monad, so it needs to define pure and bind abstract values of the scalaz.Monad trait.
pure takes a value and turns it into a value contained in the "container" type. For example it could take an Int and return a List[Int]. This seems pretty simple.
bind takes a "container" type and a function that maps the type that the container holds to another type. The value that is returned is the same container type, but it's now holding a new type. An example would be taking a List[Int] and mapping it to a List[String] using a function that maps Ints to Strings. Is bind pretty much the same as map?
The implementation of bind is where I'm stuck. Here's the code:
def bind[A,B](a: IO[A], f: A => IO[B]): IO[B] = IO {
implicitly[Monad[Function0]].bind(() => a.unsafePerformIO,
(x:A) => () => f(x).unsafePerformIO)()
}
This definition takes IO[A] and maps it to IO[B] using a function that takes an A and returns an IO[B]. I guess to do this, it has to use flatMap to "flatten" the result (correct?).
The = IO { ... } is the same as
= new IO[A] {
def unsafePerformIO = implicitly[Monad[Function0]].bind(() => a.unsafePerformIO,
(x:A) => () => f(x).unsafePerformIO)()
}
}
I think?
the implicitly method looks for an implicit value (value, right?) that implements Monad[Function0]. Where does this implicit definition come from? I'm guessing this is from the implicit val IOMonad = new Monad[IO] {...} definition, but we're inside that definition right now and things get a little circular and my brain starts to get stuck in an infinite loop :)
Also, the first argument to bind (() => a.unsafePerformIO) seems to be a function that takes no parameters and returns a.unsafePerformIO. How should I read this? bind takes a container type as its first argument, so maybe () => a.unsafePerformIO resolves to a container type?
IO[A] is intended to represent an Action returning an A, where the result of the Action may depend on the environment (meaning anything, values of variables, file system, system time...) and the execution of the action may also modify the environment. Actually, scala type for an Action would be Function0. Function0[A] returns an A when called and it is certainly allowed to depend on and modify the environment. IO is Function0 under another name, but it is intended to distinguish (tag?) those Function0 which depends on the environment from the other ones, which are actually pure value (if you say f is a function[A] which always returns the same value, without any side effect, there is no much difference between f and its result). To be precise, it is not so much that function tagged as IO must have side effect. It is that those not so tagged must have none. Note however than wrapping impure functions in IO is entirely voluntary, there is no way you will have a guarantee when you get a Function0 that it is pure. Using IO is certainly not the dominant style in scala.
pure takes a value and turns it into a value contained in the
"container" type.
Quite right, but "container" may mean quite a lot of things. And the one returned by pure must be as light as possible, it must be the one that makes no difference. The point of list is that they may have any number of values. The one returned by pure must have one. The point of IO is that it depends on and affect the environment. The one returned by pure must do no such thing. So it is actually the pure Function0 () => a, wrapped in IO.
bind pretty much the same as map
Not so, bind is the same as flatMap. As you write, map would receive a function from Int to String, but here you have the function from Int to List[String]
Now, forget IO for a moment and consider what bind/flatMap would mean for an Action, that is for Function0.
Let's have
val askUserForLineNumber: () => Int = {...}
val readingLineAt: Int => Function0[String] = {i: Int => () => ...}
Now if we must combine, as bind/flatMap does, those items to get an action that returns a String, what it must be is pretty clear: ask the reader for the line number, read that line and returns it. That would be
val askForLineNumberAndReadIt= () => {
val lineNumber : Int = askUserForLineNumber()
val readingRequiredLine: Function0[String] = readingLineAt(line)
val lineContent= readingRequiredLine()
lineContent
}
More generically
def bind[A,B](a: Function0[A], f: A => Function0[B]) = () => {
val value = a()
val nextAction = f(value)
val result = nextAction()
result
}
And shorter:
def bind[A,B](a: Function0[A], f: A => Function0[B])
= () => {f(a())()}
So we know what bind must be for Function0, pure is clear too. We can do
object ActionMonad extends Monad[Function0] {
def pure[A](a: => A) = () => a
def bind[A,B](a: () => A, f: A => Function0[B]) = () => f(a())()
}
Now, IO is Function0 in disguise. Instead of just doing a(), we must do a.unsafePerformIO. And to define one, instead of () => body, we write IO {body}
So there could be
object IOMonad extends Monad[IO] {
def pure[A](a: => A) = IO {a}
def bind[A,B](a: IO[A], f: A => IO[B]) = IO {f(a.unsafePerformIO).unsafePerformIO}
}
In my view, that would be good enough. But in fact it repeats the ActionMonad. The point in the code you refer to is to avoid that and reuse what is done for Function0 instead. One goes easily from IO to Function0 (with () => io.unsafePerformIo) as well as from Function0 to IO (with IO { action() }). If you have f: A => IO[B], you can also change that to f: A => Function0[B], just by composing with the IO to Function0 transform, so (x: A) => f(x).unsafePerformIO.
What happens here in the bind of IO is:
() => a.unsafePerformIO: turn a into a Function0
(x:A) => () => f(x).unsafePerformIO): turn f into an A => Function0[B]
implicitly[Monad[Function0]]: get the default monad for Function0, the very same as the ActionMonad above
bind(...): apply the bind of the Function0 monad to the arguments a and f that have just been converted to Function0
The enclosing IO{...}: convert the result back to IO.
(Not sure I like it much)