When using these in a function parameters description, they have different effects.
Only the latter form can accept multi-line operations like
{
println(“hello”)
println(“world”)
1
}
However, the former can’t.
I know ‘()’ means “no parameters”, right? But what ‘’ means in ‘=>Int’?
Here's the whole story.
Define a function
def func(x: =>Int)= {
println(x)
}
Invoke it
func {
println("hello")
println("world")
1
}
We will get
hello
world
1
However, if we define the function as
def func(x: ()=>Int)= {
println(x)
}
Invoke it using the former code, we will get
error: type mismatch;
found : Int(1)
required: () => Int
1
^
So, what's the difference between ‘x: () => Int’ and ‘x: => Int’?
Behaviors Of Call By Name Evaluation VS Higher-Order Functions
Call By Name Evaluation:
In case of call by name, the expression is evaluated before the function is invoked.
Example:
def func(x: =>Int): Int= {
x
}
func(10 + 2)
Higher-Order Functions:
In case of HOF, the function is passed and its result are computed when the function is invoked.
Example:
def func(x: () =>Int): () => Int = {
x
}
func(() => 10 + 2)
Note: Check the return types for more clarity.
Essentially, there is no difference. Both represent 0-arity functions which result in an Int value.
However, there is a big difference in how they are used. One, x: => Int, is used for a call-by-name parameter in a method and is invoked simply by referencing an Int. The compiler does the rest.
The other form, x: () => Int, is used for a method parameter where you really want to pass in a 0-arity function. But when you use x within your method, you must actually give it parentheses. And, of course, when you invoke the method, you need to pass in a function (or partially-applied method), not an Int.
Here's an example:
def and(a: Boolean, b: () => Boolean): Boolean = if (a) b() else false
def not(): Boolean = false
println(and(true, not))
Related
Background
I tried to answer a question "what is function?" and wonder if I actually know what it is. Please help to understand what a "function" is in Scala. It may sound non-sense debate but please be patient to help.
Questions
1. What is function
A "function" is a "computation/operation" to be "applied" to a single "argument" to generate an "value". If there are multiple argument, then it can be converted into ()()()... which is called currying.
w is a name
b is a binding of a function object to a name
c is computation
a is application
g is argument on which apply an compuation
val w = ( ) => { }
^ ^ ^ ^ ^
| | | | |
(n) (b) (g) (a) (c)
Is it OK to say these?
Also if this is to apply a computation to an argument:
() => { }
Then it actually should be in the opposite direction?
() <= { }
or
{ } => ()
2. Decomposition of definition
Is this correct understanding of what "def f (x:Unit):Unit = {}" is?
//--------------------------------------------------------------------------------
// The function literal says:
// 1. Define a "function" (ignore "method" here).
// 2. Bind the function to a name f.
// 3. It is to be applied to an "argument" of type Unit.
// 4. Bind the argument to a name x.
// 5. E-valuation, or appliation of the function to an argument generates an "value" of type Unit.
// 6. After evaluation, substitute it with the "value".
//--------------------------------------------------------------------------------
def f (x:Unit):Unit = {}
3. Evaluation / Application
Is "evaluation" the same with "application of a function to an argument and yield an value"? When I read lambda calculas, word "application" is used, but I think "evaluation" is also used.
Unit
//--------------------------------------------------------------------------------
// The literal says:
// 1. Apply the function f
// 2. on the "argument" enclosed between '(' and ')', which is Unit.
// 3. and yield Unit as the "value" evaluated.
//--------------------------------------------------------------------------------
def f (x:Unit):Unit = {}
f()
Is it the same with this? If so is "Unit" an object?
f(Unit) // No error in Scala worksheet
What is causing the error "Too many arguments" for Unit as argument below?
// Define a function that applies on an argument x of type Unit to generate Unit
() => {} // res0: () => Unit = <function0>
(() => {}) // res1: () => Unit = <function0>
// Application
(() => {})()
/* Error: Too many arguments */
(() => {})(Unit)
4. Referential transparency
Please advise if this is correct.
Using "def g (x:String): Unit = println(x)" as an example, "referential transparency" means that g(x) can be always substituted with its result and it will not break any.
If
g("foo")
can be always replaced with
Unit
then it is referentially transparent. However, it is not the case here for g. Hence g is not a referentially transparent function, hence it is not "pure" function. Random is also not pure.
{ scala.util.Random.nextInt } // res0: Int = -487407277
In Scala, function can be pure or side-effective. There is no way to tell by just having look at a function. Or is there a way to mark as such, or validate if it is pure or not?
5. Method is not a function
A method cannot be a first class object to be passed around but it can be by converting it to a function.
def g (x:String): Unit = println(x)
g("foo")
val _g = g _
_g("foo")
Why method cannot be a first class object? If a method is an object, what will happen or what will break?
Scala compiler does clever inferences or complehentions, then if it can be converted into an object with _, why Scala does not make it a firt class object?
6. What is { ... }?
Update:
"=> T" is call by name passing expression to be evaluated inside the function, hence has nothing to do with "{...}" specifically. {...} is a block expression. Hence all below is invalid.
It looks "{...}" is the same with "=> T".
def fill[T](n: Int)(elem: => T)
Array.fill[Int](3)({ scala.util.Random.nextInt })
{...} in itself yield an value without taking any argument.
{ scala.util.Random.nextInt } // res0: Int = 951666328
{ 1 } // res1: Int = 1
Does it mean "application" is an independent first class object, or the Scala compiler is clever enough to understand it is an abbreviation of:
() => { scala.util.Random.nextInt }
or
val next = (x:Int) => { scala.util.Random.nextInt(x) }
If so, "=> T" is actually "() => T"?
In Scala function is an implementation of one of traits from Function1 to Function22 depending on input parameters amount. For your particular example w is a shorthand for anonfunW:
val w = () => {}
val anonfunW = new Function1[Unit, Unit] {
def apply(x: Unit): Unit = ()
}
specifically, what is the difference for following two definitions:
def func(f: () => String) = f()
def func1(s: String) = s
I wrote some codes to test them, it seems they produce the same result; are those two definitions just the same in this scenario; or they do have some difference?
var x = 1
def f() = {
x = x + 1
s"$x"
}
println(func1(f))
println(func1(f))
println(func1(f))
println(func(f))
println(func(f))
println(func(f))
They are perhaps the same in THIS scenario, but there are lots of other scenarios when a () => A and a A are much different. () => A is referred to as a thunk and is used to pass a piece of delayed computation to a function. The body of the "thunk" doesn't get evaluated until the function called decides to evaluate it. Otherwitse, the value of the argument being passed in is evaluated by the caller.
Consider this example, where there IS a difference between the version that takes a thunk and the version that just takes a value:
object Thunk {
def withThunk(f: () ⇒ String): Unit = {
println("withThunk before")
println("the thunk's value is: " + f())
println("now the thunk's value is: " + f())
}
def withoutThunk(f: String): Unit = {
println("withoutThunk before")
println("now the value's value is: " + f)
}
def main(argv: Array[String]): Unit = {
withThunk { () ⇒ println("i'm inside a thunk"); "thunk value" }
println("------------")
withoutThunk { println("i'm not inside a thunk"); "just a value" }
}
}
This program will demonstrate some differences. In the thunk version, you see "withThunk before" get printed before the first time "i'm inside a thunk" gets printed, which gets printed twice, since f() is evaluated twice. In the non-thunk version, the "I'm not inside a thunk" gets printed before "withoutThunk before", since this is evaluated before being sent to the function as an argument.
def func(f: () => String) = f()
This one accepts as parameter a function that returns a string.
def func1(s: String) = s
While this one simple requires a String as parameter
Aside from the minor technical difference above, in this scenario they seem to function the same. However, the function parameter is potentially more powerful as it is a function that can derive its return value from several other operations. I think however, the main difference that the function parameter allows you to decide when the value is derived.
def func(f: () => String) = f()
def func1(s: String) = s
println(func1(f)) // in this case f is evaluated first, its value is used in func1.
println(func(f)) // in this case f is NOT evaluated, but passed as it is to func.
// It is upto func to call f whenever needed, or even not call it.
It is this "lazy" evaluation of f, that makes func more useful, for instance f can be passed to some other higher order functions, or it can be called asynchronously.
I want to add an example for the use of () => String.
def printFuncResult(f: () => String) = println(f() + " " + f())
def ran = () => Math.random.toString
printFuncResult(ran)
printFuncResult(Math.random.toString)
When you pass a function like ran then you will most likely have two different values printed (randomness is involved here). When you pass a fixed Random number then it will be printed twice.
As you can see: when you have a function as a parameter it might result in a different value each time it is used in printFuncResult. This is not possible when you just put a String parameter.
I have not understood the following code snippet why afterDelay(0) {...}, a locally defined function can be stored into agenda? Can someone help me understand the afterDelay(0) {...} in the run function?
abstract class Simulation {
type Action = () => Unit
case class WorkItem(time: Int, action: Action)
private var curtime = 0
def currentTime: Int = curtime
private var agenda: List[WorkItem] = List()
private def insert(ag: List[WorkItem], item: WorkItem): List[WorkItem] = {
if (ag.isEmpty || item.time < ag.head.time) item :: ag
else ag.head :: insert(ag.tail, item)
}
def afterDelay(delay: Int)(block: => Unit) {
val item = WorkItem(currentTime + delay, () => block)
agenda = insert(agenda, item)
}
private def next() {
(agenda: #unchecked) match {
case item :: rest =>
agenda = rest
curtime = item.time
item.action()
}
}
def run() {
afterDelay(0) {
println("*** simulation started, time = "+
currentTime +" ***")
}
while (!agenda.isEmpty) next()
}
}
afterDelay(0) {
println(...)
}
Is equivalent to the following:
afterDelay(0)({
println(...)
})
The function afterDelay is invoked a new WorkItem (item) is added to the list, not the function itself. The parameter block: => Unit is a "By-Name Parameter" (see the Scala Language Specification section 4.6.1): the expression used as the argument is implicitly converted into a "parameterless method" (without being evaluated first) that will be invoked whenever the variable inside the method is accessed (no () required).
In this case that is when the function resulting from () => block is invoked: it is invoked at item.action() which occurs at some point after the new WorkItem is added to the list (and afterDelay returns).
If it was written as (taking in a function paramater, not a by-name/thunk):
def afterDelay(delay: Int)(block: () => Unit) { // take a function
// new function will invoke function named by "block" when invoked ...
val item = WorkItem(..., () => block())
// or skip wrapping the function in a function ...
// val item = WorkItem(..., block)
...
}
Then it would need to be invoked passing in a function:
afterDelay(0)(() => { // need a function
println(...)
})
Or, alternative syntax, still a function of () => Unit, but the outside parenthesis can be avoided:
afterDelay(0) { () => // need a function
println(...)
}
Extract from the SLS, 4.6.1 By-Name Parameters:
The type of a value parameter may be prefixed by =>, e.g. x: => T. The type of such a parameter is then the parameterless method type => T. This indicates that the corresponding argument is not evaluated at the point of function application, but instead is evaluated at each use within the function. That is, the argument is evaluated using call-by-name.
You defined afterDelay as a curried function. This means it has two parameter lists. In scala you can replace the brackets surounding the parameterlist (...) with {...}. In the second parameterlist you are using a "call-by-name" parameter. Those parameters are evaluated everytime again you use them in your function. A good Example is here.
"Call-by-name" parameters are often used to define your own controlling structure.
def do(until: Int)(body: => Unit) {
body
if (until > 1) do(until - 1)(body)
}
do(0)(println("test"))
do(5)(println("test2"))
This is an example for a do until. It will print once test and five times test2.
I have the following code in Scala-IDE:
type myF = () => Boolean
def acceptFunction(f: myF) {
//...
}
and then:
var a = false
def isA = () => a
but when I try passing it, to the acceptFunction, it results in error:
acceptFunction(isA)
the error is:
type mismatch; found : () => Boolean required: Boolean
But why?
If I declare isA like this:
def isA() = () => a
then it is accepted, but I assume, it get's evaluated because of the parenthesis.
Is there any way to pass such a function for furhter evaluation?
UPDATE:
Looks like it is something with Scala-IDE. The REPL has no problems with these expressions. However, still I can't make it so that the passed function does not get turned into a closure. I mean, that it turns into closure, and changing the var a later and calling the example with println(f()) again - does not change the value. So, the second part of the question remains - is there any way to pass such a function for furhter evaluation?
Are you sure you didn't make a mistake when writing your code the first time? I copied and pasted what you had into the 2.9.1 REPL and it worked fine.
scala> type myF = () => Boolean
defined type alias myF
scala> var a = false
a: Boolean = false
scala> def isA = () => a
isA: () => Boolean
scala> def acceptFunction(f: myF) {println(f())}
acceptFunction: (f: () => Boolean)Unit
scala> acceptFunction(isA)
false
scala>
UPDATE: isA is a closure when you define it. Passing it to acceptFunction has no effect on whether it grabs a.
Is your purpose to write a function, acceptFunction, which takes a function, f, which captures an external value, a, at the time it's defined?
You could do that like so:
// Defines a function which returns a function with returns the
// value that was captured at the outer function's call time.
def isB = { (b: Boolean) => { () => b }: myF }
a = true
val f = isB(a)
acceptFunction(f) // >> true
a = false
acceptFunction(f) // >> true
Is that where you're trying to go?
I'm new to scala so sorry if this is easy but I've had a hard time finding the answer.
I'm having a hard time understanding what <- does, and what ()=> Unit does. My understanding of these is that -> is sometimes used in foreach, and that => is used in maps. Trying to google "scala "<-" doesn't prove very fruitful. I found http://jim-mcbeath.blogspot.com/2008/12/scala-operator-cheat-sheet.html but it wasn't as helpful as it looks at first glance.
val numbers = List("one", "two", "three","four","five")
def operateOnList() {
for(number <- numbers) {
println(number + ": came out of this crazy thing!")
}
}
def tweener(method: () => Unit) {
method()
}
tweener(operateOnList)
() => Unit means that method is a function that takes no parameter and returns nothing (Unit).
<- is used in the for comprehension as an kind of assignation operator. for comprehension are a little bit specific because they are internally transformed. In your case, that would be transforms as numbers.foreach(i => println(i + ": came out of this crazy thing!"))
<- in the for comprehension means that we will iterate over each element of the numbers list and passed to number.
'<-' could be threated as 'in' so
for(number <- numbers){
...
}
could be translated into english as for each number in numbers do
'<-' has a twin with a different semantics: '->'. Simply it is just a replacement of comma in tuples: (a,b) is an equivalent to (a->b) or just a->b. The meaning after this symbols is that 'a' maps to 'b'. So this is often used in definition of Maps:
Map("a" -> 1,"aba" -> 3)
Map("London" -> "Britain", "Paris" -> "France")
Here you can think about mapping as a projection (or not) via some function (e.g. 'length of string', 'capital of').
Better explanation is here.
Last, but not least is '=>' which is map too, but with a general semantics. '=>' is in use all over the place in anonymous expressions:
scala> List(1,2,3,4).map(current => current+1)
res5: List[Int] = List(2, 3, 4, 5)
Which is for each element map current element of list with function 'plus one'
List(1,2,3,4).map(c => c%2 match {
| case 0 => "even"
| case 1 => "odd"
| }
| )
res6: List[java.lang.String] = List(odd, even, odd, even)
Map current element with provided pattern mathing
In the method
def tweener(method: () => Unit) {
method()
}
the method is called tweener, the parameter is arbitrarily named method, and the type of method is () => Unit, which is a function type, as you can tell from the =>.
Unit is a return type similar to void in Java, and represents no interesting value being returned. For instance, the return type of print is Unit. () represents an empty parameter list.
Confusingly, () is also used to represent an instance of Unit, called the unit value, the only value a Unit can take. But this is not what it means in the function type () => Unit, just as you can't have a function type 42 => Unit.
Back to your example, tweener takes a function of type () => Unit. operateOnList is a method, but it gets partially applied by the compiler to turn it into a function value. You can turn methods into functions yourself like this:
scala> def m = println("hi")
m: Unit
scala> m _
res17: () => Unit = <function0>
operateOnList can be turned into the right type of function because its parameter list is empty (), and its return type is implicity Unit.
As a side-note, if operateOnList were defined without the empty parameter list (as is legal, but more common when the return type is not Unit), you would need to manually partially apply it, else its value will be passed instead:
def f1() {}
def f2 {}
def g(f: () => Unit) {}
g(f1) // OK
g(f2) // error, since we're passing f2's result (),
// rather than partial function () => Unit
g(f2 _) // OK