scala differences between 2 functions syntaxes - scala

I'm trying to understand the differences between these 2 syntaxes in scala and why they have not the same result.
testVal
and
testVal2
are not defined in the same way
object FunctionVsVal2 extends App {
val testVal: () => Int = {
val r = util.Random.nextInt
() => r
}
val testVal2: () => Int = () => {
val r = util.Random.nextInt
r
}
println(testVal())
println(testVal())
println(testVal2())
println(testVal2())
}
Thanks

testVal2 is a lambda expression. Each time you call testVal2(), it evaluates
{
val r = util.Random.nextInt
r
}
and so returns a new value.
testVal is a block expression. It calculates r first and then returns () => r (the last expression in the block), so each time you call testVal(), the same r is used.

Related

Why this code compiles and it gives runtime error when it executes

This Scala code compiles under Scala 2.13
val res = new scala.collection.mutable.StringBuilder
"hello".foreach { c =>
if (true) {
(0 until 10).foreach( res += c )
}
}
If you see the foreach method is missing argument for anonymous function. When it is executed it gives an exception StringIndexOutOfBoundsException for res += c which is puzzling since StringBuilder should always be appendable.
Following code runs fine and there are no exceptions. The only change is adding _ as placeholder for foreach parameter function:
val res = new scala.collection.mutable.StringBuilder()
"hello".foreach { c =>
if (true) {
(0 until 10).foreach( _ => res += c )
}
}
The answer to your question lies in String.apply() or StringBuilder.apply() to be more exact.
You see, foreach expects a function. In more exact words, an expression which evaluates to a function.
So, it will first evaluate the expression to get the function then it will apply that function for 0 until 10
so when you consider the first iteration of outer foreach, you have c = 'h' and following,
(0 until 10).foreach(res += c )
Here, res += c will return res after appending h to it.
So... the evaluated function is res or res.apply with res = "h". Hence, the above is actually,
(0 until 10).foreach("h".apply)
So, res.apply(0) goes well... but res.apply(1) fails with StringIndexOutOfBoundsException.
Please see the signature for
def foreach[U](f: A => U): Unit = {
}
(f: A => U) this is a function, not an expression.

Scala count number of times function returns each value, functionally

I want to count up the number of times that a function f returns each value in it's range (0 to f_max, inclusive) when applied to a given list l, and return the result as an array, in Scala.
Currently, I accomplish as follows:
def count (l: List): Array[Int] = {
val arr = new Array[Int](f_max + 1)
l.foreach {
el => arr(f(el)) += 1
}
return arr
}
So arr(n) is the number of times that f returns n when applied to each element of l. This works however, it is imperative style, and I am wondering if there is a clean way to do this purely functionally.
Thank you
how about a more general approach:
def count[InType, ResultType](l: Seq[InType], f: InType => ResultType): Map[ResultType, Int] = {
l.view // create a view so we don't create new collections after each step
.map(f) // apply your function to every item in the original sequence
.groupBy(x => x) // group the returned values
.map(x => x._1 -> x._2.size) // count returned values
}
val f = (i:Int) => i
count(Seq(1,2,3,4,5,6,6,6,4,2), f)
l.foldLeft(Vector.fill(f_max + 1)(0)) { (acc, el) =>
val result = f(el)
acc.updated(result, acc(result) + 1)
}
Alternatively, a good balance of performance and external purity would be:
def count(l: List[???]): Vector[Int] = {
val arr = l.foldLeft(Array.fill(f_max + 1)(0)) { (acc, el) =>
val result = f(el)
acc(result) += 1
}
arr.toVector
}

What do these lines mean (Scala / JavaTokenParsers)?

I am trying to better understand how to do mass parsing/interpreting.
I am having difficulty understanding lines like these:
type L = () => Long
And then later there are other lines like
val term = chainl1(myNum, "[*/]".r ^^ {
case "*" => (u1:L, u2:L) => () => u1() * u2()
case "/" => (u1:L, u2:L) => () => u1() / u2()
})
I am just trying to understand the underlying structure here. What exactly is () here? What is the logical flow of these val statements?
I assume this means "if we find * or / in myNum, match on these two cases depending on which one it is, and then... long flow of logic I don't understand"
type L = () => Long
describes a function with zero arguments and return type Long. For example
def someConstant() = 5L
Here someConstant is of type L.
This line
case "*" => (u1:L, u2:L) => () => u1() * u2()
will return you a function of type Function2 (arity 2) with return type Function0(arity 0) which when is called will return the result of u1() * u2().
val f = () => (x:Int) => x
can be written as
() => ((x: Int) => x)
Here f is a function with arity 0 which when is called returns another function with arity 1 which accepts Int argument and returns it when called.
f()(6) == 6
is true statement.
The answer of ka4ell is correct, but does not mention why you would use () => Long instead of just using Long: with () => Long or L the execution of the calculation which returns the Long is delayed. We only execute the functions at the moment we want the actual result, this is called lazy evaluation.
In your case:
case "*" =>
// Return a function which takes two Ls : u1 and u2
// and which returns an L : () => u1() * u2()
(u1:L, u2:L) => () => u1() * u2()
Let's define a simple function which returns an L :
// return a function which will return a Long
// this could potentially be a very expensive calculation
def giveMeAnL(n: Long) = () => {
println("giveMeAnL is called")
n
}
If we would use an analogous function than the one in the case:
// analogous case "*" => ...
def multiply(u1:L, u2:L) = () => {
println("multiply is called")
u1() * u2()
}
// create two Ls
val (l1, l2) = (giveMeAnL(5L), giveMeAnL(2L))
val productL = multiply(l1, l2) // productL is of type L
The value productL now contains an L which can calculate the product of the two values. At this point, neither the product nor the two values are calculated. If we call the productL value, the two values are calculated and the product of these values is calculated.
val product = productL()
// multiply is called
// giveMeAnL is called
// giveMeAnL is called
// product: Long = 10
If somewhere in your parsing steps, you want to ignore some L values, the results of these Ls are never calculated, which improves the performance.
case "multiply first with 5" =>
(u1:L, u2:L) => () => u1() * 5L // u2 is never executed
If we split the line case "*" => (u1:L, u2:L) => () => u1() * u2():
case "*" => means match * to the code that is written next
(u1:L, u2:L) => {} is a definition of function that has two arguments of type L
u1 and u2 are functions, because their type is L, and it is actually () => Long which means this is a function that takes nothing and returns Long
() => u1() * u2() is a function with no arguments, that calls u1 and u2 and multiplies their results
Going back:
(u1:L, u2:L) => () => u1() * u2() is a function of two arguments which returns a function of no arguments, that executes both arguments of a first function, multiplies them and return the result
So, () => means a function with no arguments. The only exception here is case * => where => doesn't belong to a function, but rather to match statement

delay implementation in scala

I have implemented the following cons_stream function in scala that does not work and I am not sure why.
def cons_stream[T, U](x : T, y : U) =
{
def delay = () => y
/// Delay takes no parameters but returns y
(f : String ) =>
{
if ( f == "x") x
else if( f == "y") delay
else throw new Error("Invalid string use x or y")
}
}
The corresponding car and cdr functions are:
def stream_car[T](f : String => T) : T = f("x")
def stream_cdr[T](f : String => Any) : T = force(f("y").asInstanceOf[() => T])
Now I have the definition of a stream integers starting with 1
def integers_starting_from_n[T, U](n : Int) : String => Any =
{
cons_stream(n, integers_starting_from_n(n+1))
}
Unfortunately when I try to access the stream using either stream_car or stream_cdr I get a stack overflow:
def integers = integers_starting_from_n(1)
stream_car(integers)
I have no idea why. Any help is appreciated.
I assume that the stack is full of integers_starting_from_n. Correct? That function is recursive and is called before cons_stream can be executed, because it takes value of integers_starting_from_n(n+1) as a paremeter.
In order to define a stream, you can use a call-by-name parameter by prepending => to the type. For your example, use call-by-name with y.
def cons_stream[T, U](x:T, y: => U)

Returning code block in Scala

I was trying to implement the closure example in Scala, from Neal Ford's Functional Thinking presentation which is in Groovy. Refer slide # 43 & 44 https://sea.ucar.edu/sites/default/files/Functional_Thinking.pdf
def makeCounter : Unit = {
var localVar = 0
return { localVar += 1 }
}
This code returns an anonymous function. Now I want to increment the localVar by invoking this anonymous function.
I have two questions:
1. How do I invoke the anonymous function?
2. After invoking it how do I check if the value of localVar is incremented or not?
First I tried this -
val c1 = makeCounter(). It threw below error:
error: makeCounter of type Unit does not take parameters
Then I tried this.
val c1 = makeCounter
This didn't give any error. Only printed c1: Unit = ().
Then,
print(c1) printed (), whereas c1() gave the same error.
First of all. Don't use return, its semantics is completely different in Scala than in Java or Groovy.
The Unit type isn't a synonym for anonymous function. It's more like a indication of side-effects.
The type for an anonymous function is () => A. In your case you want a function that doesn't return any thing, but causes a side-effect. So its type should be () => Unit.
Let's see some code:
def makeCounter : () => Unit = {
var x = 0
{ () => x = x + 1 }
}
val counter = makeCounter
counter(); counter(); counter()
Great! We made makeCounter give us a fresh counter!
There is only one problem. x is a local variable in the method makeCounter and since it's never returned we can't see its value! Ever! We could, for example, remove x from the method, making it public in the outer scope. But it's not very functional. Instead let's make the function return it:
def makeCounter : () => Int = { // Notice now, instead of Unit we use Int
var x = 0
{ () => x = x + 1; x }
}
val counter = makeCounter
println(counter(), counter(), counter())
val counter2 = makeCounter
println(counter2(), counter2(), counter2())
You will see "1,2,3" twice. Once for each counter.
I didn't look at the presentation, so I don't know if this is functional thinking or just one of the slides on the road to functional thinking, but:
scala> def f: () => Int = {
| var v = 0
| () => v += 1 ; v }
f: () => Int
scala> val g = f
g: () => Int = <function0>
scala> g()
res0: Int = 1
scala> g()
res1: Int = 2
scala> g()
res2: Int = 3
The function literal returned by f is, of course, everything after the parens.