How to read a chain of Scala function parameters - scala

I am trying to read the parameter-list of the following 2 functions:
1. def foo(action: => String => String) = "bar"
2. def foo(action: => () => String => String) = "bar"
A function named "foo" which receives a function named "action" which receives/returns ???
A function named "foo" which receives a function named "action" which returns a function which returns ???

action is a passed-by-name function that takes a String and returns a String.
action is a passed-by-name function that takes nothing to return a function that takes a String and returns a String
Now you might ask, "Well, what does it mean for a parameter to be passed-by-name?" Alright... that's a whole different can of worms. Basically, a passed by name parameter is only evaluated when it's used in the function, and every time that it's used in the function. What this allows for is something like short-circuiting, as follows
def orOperator(left: Boolean, right: => Boolean) : Boolean = if (left) true else right
In this case, the operator will short-circuit (and terminate without computing/evaluating right) if it finds left to be true.
So... what you have with these parameters is something similar. They are functions that do not evaluate—for some reason—unless/until they are named in the function body. I don't understand the motivation for that, but... that's how it is. I hope that helps.

Related

Passing a function as a parameter, why the => symbol is required in my scenerio?

case class User(id: Int)
def Transform(u: User): String = u.id.toString()
def Process[A](f: A => String): String = "hello"
val u = User(123)
println(Process(u => Transform(u))) // Scenerio#1 works fine
println(Process(Transform(u))) // error
println(Process[User](Transform(u))) // error
I'm a little confused as to why I need the => in Scenerio#1
I have a function Process that takes a function. The function requires:
a parameter of type A
return value of String.
Now I have a function named Transform that takes a parameter of type A (a User) and returns a string.
Why can't I pass in:
Process(Transform(u))
I am passing it a function that meets the requirements am I not? (I guess not but I don't understand!)
I guess I still don't understand what the following notation really means:
Process(u => Transform(u))
As you already noticed, Transform is of type User => String, therefore, you can just pass it as a parameter to Process:
val process1: String = Process(u => Transform(u))
val process2: String = Process(Transform)
val process3: String = Process[User](Transform)
All of the above are exactly the same, and outputs hello.
def Process[A](f: A => String) method in your code is expecting a function definition as argument whose input parameter type should A and return type should be String.
Case 1:
println(Process(u => Transform(u)))
You are passing function definition so it is working fine as per expectation.
Case 2:
println(Process(Transform(u))) // error
println(ProcessUser) // error
You are not passing function definition here as expected by Process function instead you are passing the function call Transform(u) which will return the value and pass as argument to Process function.
You can refer high order function in scala using this link (https://docs.scala-lang.org/tour/higher-order-functions.html).

Using Type parameter in Scala Functions

I'm trying to implement the Boolean Type in Scala, and i found an example using this signature :
abstract class Boolean {
def ifThenElse[T](t : => T , e : => T) : T
... }
My questions is :
When we should use the type Parameter after the function name like this funcName[T].
What does t : => T mean ?
Thank you
As for the first question:
1.When we should use the type Parameter after the function name like this funcName[T]
if you want this function can be used by different type, it's appreciate that put the generic type after function name as funcName[T]. For example, you have a function like this
def myFunction[T](param1: T){/*process*/}
you want to pass the parameter param1 and param2 to myFunction. These two parameters are defined as following
val param1: Int = 10
val param2: String = "test"
Though param1 and param2 have different types, you can call the function myFunction(param1) and also myFunction(param2)
Then, let's talk about the second question
2.What does t : => T mean ?
It's a by-name parameter. what's it? The following gives you more details:
t: => T has the same meaning as t: () => T, instead of inputing the words () => T, you can choose => T as for t
Another example: if you want to has an assertion, you may define the function like this:
def myAssert(predicate: () => Boolean) =
if(!predicate()) throw new AssertionError
then you can use it as following
myAssert(() => 5 > 3)
The usage is so ugly, is it? You may want to use it like this
myAssert(5 > 3)
at this time, the by-name parameter will be on the stage. Just define your function by the help of by-name parameter
def myAssert(predicate: => Boolean) = //leave out '()'
if(!predicate) throw new AssertionError //leave out '()'
then, you can use myAssert as above
myAssert(5 > 3)
Notes: A by-name type, in which the empty parameter list, (), is left out, is only allowed for parameters. There is no such thing as a by-name variable or a by-name field.
Good luck with you.

Scala: understanding anonymous function syntax

I am trying to make sense of a custom Iterator in Scala written by another programmer.
I am having trouble understanding the function declarations.
They look like anonymous functions to me, but I simply can't wrap my head around them fully.
I did some reading about Anonymous Functions in Scala , and I found this resource [http://www.scala-lang.org/old/node/133] helpful, but I still cannot read the above functions and make sense of them completely.
Here is the code:
class MyCustomIterator(somePath: Path, someInt: Int, aMaxNumber: Int) {
def customFilter:(Path) => Boolean = (p) => true
// Path is from java.nio.files.Path
def doSomethingWithPath:(Path) => Path = (p) => p
}
I would like to understand these understand these functions. What is the return type really? What is the body of the function?
.
(For the first def) The parts after the colon and before the equals sign are the return type. So, the return type is:
Path => Boolean
Which denotes a function signature.
Now, breaking that down, the item on the left of the arrow is the parameters of a function. The right hand side is the return type of the function.
So, it is returning a function that accepts a Path and returns a Boolean. In this case, it is returning a function that will accept a Path and return true no matter what.
The second def returns a function that accepts a Path and returns another Path (the same Path in this case)
An example usage would be to use them as follows:
First method:
iter.customFilter(myPath) //returns true
or
val pathFunction = iter.customFilter;
pathFunction(myPath) //returns true
Second method:
iter.doSomethingWithPath(myPath) //returns myPath
or
val pathFunction = iter.doSomethingWithPath
pathFunction(myPath) //returns myPath

Scala no argument string function vs typed String parameter

I ran across a function that looks like this:
def doSomethingQuestionable(config: someConfig, value: String)(default: => String) : String
What is interesting is the parameterless function that gets passed in as second argument group. In the code base, the method is only ever called with a config and two strings, the latter being some default value, but as a String, not a function. Within the code body of the method, default is passed on to a method that takes 3 string arguments. So the function "default" only resolves down to a string within the body of this method.
Is there any benefit, apart from a currying usage which does not happen with this method in the code base I am going through, of defining the method this way? Why not just define it with 3 string arguments in a single argument group?
What am I missing? Some compiler advantage here? Keep in mind, I am assuming that no currying will ever be done with this, since it is a large code base, and it is not currently done with this method.
The point is to have a potentially expensive default string that is only created when you need it. You write the code as if you're creating the string to pass in, but because it's a by-name parameter ('=> String') it will actually be turned into a function that will be transparently called whenever default is referenced in the doSomethingQuestionable method.
The reason to keep it separate is in case you do want a big block of code to create that string. If you never do and never will, it may as well be
def doSomethingQuestionable(config: someConfig, value: String, default: => String): String
If you do, however,
def doSomethingQuestionable(cfg, v){
// Oh boy, something went wrong
// First we need to check if we have a database accessible
...
// (Much pain ensues)
result
}
is way better than embedding the code block as one argument in a multi-argument parameter list.
This is a parameterless function returning a String:
() => String
Which is not what you have. This,
=> <WHATEVER>
is a parameter being passed by-name instead of by-value. For example:
=> String // A string being passed by-name
=> () => String // A parameterless function returning string being passed by-name
The difference between these modes is that, on by-value, the parameter is evaluated and the resulting value is passed, whereas on by-name, the parameter is passed "as is", and evaluated each time it is used.
For example:
var x = 0
def printValue(y: Int) = println(s"I got $y. Repeating: $y.")
def printName(y: => Int) = println(s"I got $y. Repeating: $y.")
printValue { x += 1; x } // I got 1. Repeating: 1.
printName { x += 1; x } // I got 2. Repeating: 3.
Now, as to why the method splits that into a second parameter, it's just a matter of syntactic pleasantness. Take the method foldLeft, for example, which is similarly defined. You can write something like this:
(1 to 10).foldLeft(0) { (acc, x) =>
println(s"Accumulator: $acc\tx: $x\tacc+x: ${acc+x}")
acc+x
}
If foldLeft was defined as a single parameter list, it would look like this:
(1 to 10).foldLeft(0, { (acc, x) =>
println(s"Accumulator: $acc\tx: $x\tacc+x: ${acc+x}")
acc+x
})
Not much different, granted, but worse looking. I mean, you don't write this thing below, do you?
if (x == y, {
println("Same thing")
}, {
println("Different thing"
})

Can anyone explain how the symbol "=>" is used in Scala

I've read a lot of code snippets in scala that make use of the symbol =>, but I've never really been able to comprehend it. I've tried to search in the internet, but couldn't find anything comprehensive. Any pointers/explanation about how the symbol is/can be used will be really helpful.
(More specifially, I also want to know how the operator comes into picture in function literals)
More than passing values/names, => is used to define a function literal, which is an alternate syntax used to define a function.
Example time. Let's say you have a function that takes in another function. The collections are full of them, but we'll pick filter. filter, when used on a collection (like a List), will take out any element that causes the function you provide to return false.
val people = List("Bill Nye", "Mister Rogers", "Mohandas Karamchand Gandhi", "Jesus", "Superman", "The newspaper guy")
// Let's only grab people who have short names (less than 10 characters)
val shortNamedPeople = people.filter(<a function>)
We could pass in an actual function from somewhere else (def isShortName(name: String): Boolean, perhaps), but it would be nicer to just place it right there. Alas, we can, with function literals.
val shortNamedPeople = people.filter( name => name.length < 10 )
What we did here is create a function that takes in a String (since people is of type List[String]), and returns a Boolean. Pretty cool, right?
This syntax is used in many contexts. Let's say you want to write a function that takes in another function. This other function should take in a String, and return an Int.
def myFunction(f: String => Int): Int = {
val myString = "Hello!"
f(myString)
}
// And let's use it. First way:
def anotherFunction(a: String): Int = {
a.length
}
myFunction(anotherFunction)
// Second way:
myFunction((a: String) => a.length)
That's what function literals are. Going back to by-name and by-value, there's a trick where you can force a parameter to not be evaluated until you want to. The classic example:
def logger(message: String) = {
if(loggingActivated) println(message)
}
This looks alright, but message is actually evaluated when logger is called. What if message takes a while to evaluate? For example, logger(veryLongProcess()), where veryLongProcess() returns a String. Whoops? Not really. We can use our knowledge about function literals to force veryLongProcess() not to be called until it is actually needed.
def logger(message: => String) = {
if(loggingActivated) println(message)
}
logger(veryLongProcess()) // Fixed!
logger is now taking in a function that takes no parameters (hence the naked => on the left side). You can still use it as before, but now, message is only evaluated when it's used (in the println).