This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What does () => mean in C#?
Hi Everybody,
This is my first question in stackoverflow.
I have encounter something as
() => SomeClass.SomeMethod(param1, param2)
This is entirely new to me and I cannot fathom what it is, what we call it, what it does,
how it works etc.
What I am looking for is an explanation for the same with a simple example which can be
understandable easily and I can implement it in my program. It will be nice if I can get
the real time scenario for this implementation.
I am using C#3.0 with dotnet framework 3.5.
Many thanks in advance.
Lambdas page on MSDN is quite helpful with the syntax.
And yes, ()=>GetSomething() is an expression lambda that takes no parameters and returns something. The other lambda flavour is a statement lambda, which is an anonymous function that does not return anything - i.e. a void function.
Both can take any number of parameters, including none.
It's a lambda function I guess. It is the kind of function you define "inline".
For example, in LINQ you can do the following:
myTable.Where(eleme=>elem.qty>=10);
Here you pass the function leme=>elem.qty>=10 as a parameter to the Where method.
I guess in your example, () => SomeClass.SomeMethod(param1, param2) is referring to a function taking no input parameter an returning some value.
This is a lambda that creates an Action delegate.
More info (and example) http://msdn.microsoft.com/en-us/library/system.action.aspx
You can also create an action and pass in parameters with (s) => SomeMethod(s);
Or, you can pass an entire block:
(x) => {
DoSomething(x);
if(x.SomeValue == requiredValue){
x.SomeOtherValue = true;
}
}
For more examples of passing parameters to Action<T> see here
Related
The Scala Tour Of Scala docs explain pass-by-name parameters using a whileLoop function as an example.
def whileLoop(condition: => Boolean)(body: => Unit): Unit =
if (condition) {
body
whileLoop(condition)(body)
}
var i = 2
whileLoop (i > 0) {
println(i)
i -= 1
} // prints 2 1
The section explains that if the condition is not met then the body is not evaluated, thus improving performance by not evaluating a body of code that isn't being used.
Does Scala's implementation of while already use pass-by-name parameters?
If there's a reason or specific cases where it's not possible for the implementation to use pass-by-name parameters, please explain to me, I haven't been able to find any information on it so far.
EDIT: As per Valy Dia's (https://stackoverflow.com/users/5826349/valy-dia) answer, I would like to add another question...
Would a method implementation of the while statement perform better than the statement itself if it's possible not to evaluate the body at all for certain cases? If so, why use the while statement at all?
I will try to test this, but I'm new to Scala so it might take me some time. If someone would like to explain, that would be great.
Cheers!
The while statement is not a method, so the terminology by-name parameter is not really relevant... Having said so the while statement has the following structure:
while(condition){
body
}
where the condition is repeatedly evaluated and the body is evaluated only upon the condition being verified, as show this small examples:
scala> while(false){ throw new Exception("Boom") }
// Does nothing
scala> while(true){ throw new Exception("Boom") }
// java.lang.Exception: Boom
scala> while(throw new Exception("boom")){ println("hello") }
// java.lang.Exception: Boom
Would a method implementation of the while statement perform better than the statement itself if it's possible not to evaluate the body at all for certain cases?
No. The built-in while also does not evaluate the body at all unless it has to, and it is going to compile to much more efficient code (because it does not need to introduce the "thunks"/closures/lambdas/anonymous functions that are used to implement "pass-by-name" under the hood).
The example in the book was just showing how you could implement it with functions if there was no built-in while statement.
I assumed that they were also inferring that the while statement's body will be evaluated whether or not the condition was met
No, that would make the built-in while totally useless. That is not what they were driving at. They wanted to say that you can do this kind of thing with "call-by-name" (as opposed to "call-by-value", not as opposed to what the while loop does -- because the latter also works like that).
The main takeaway is that you can build something that looks like a control structure in Scala, because you have syntactic sugar like "call-by-name" and "last argument group taking a function can be called with a block".
In the book of "functional programming in Scala", it gives some examples about side-effects, like:
Modifying a variable
Modifying a data structure in place
Setting a field on an object
Throwing an exception or halting with an error Printing to the console or reading user input
Reading from or writing to a file
Drawing on the screen
My question is, is reading some data from outside rathen than the parameters makes the function impure?
E.g.
val name = "Scala"
def upcase() = name.toUpperCase
Is the upcase function pure or not?
Edit: as per this answer: https://stackoverflow.com/a/31377452/342235, my "function" is not actually function, it's a method, so I give a function version of it, and ask the same question:
val name = "Scala"
val upcase: () => String = () => name.toUpperCase
Reading from immutable data is not impure; the function will still return the same value every time. If name were a var then that function would be impure, since something external could change name, so multiple calls to upcase() might evaluate to different values.
(Of course it might be possible to e.g. alter name through reflection. Properly we can only talk about purity with respect to some notion of what kind of functions are allowed to call a given function, and what kind of side effects we consider to be equivalent)
It's worth noting that your function is not pure because toUpperCase is not pure; it depends on the system's default Locale, and may produce different results on different systems (e.g. on a Turkish system, "i".toUpperCase == "İ"). You should always pass an explicit Locale, e.g. def upcase() = name.toUpperCase(Locale.ENGLISH); then the function will be pure.
Interestingly, the answer is "No", but not for the reason you think it is. Your upcase is not a pure function. It is, however, pure, but it is a method, not a function.
My question is about the prompts that appear when you try to call a method (or a function): I'm referring to the little box that says (param1 double, param2 char, ...). I've been having trouble googling this question, mostly because I'm not sure what this box is called, so please do point me to it if this question is already answered.
If you write a function or a method and use validateattributes to specify which input types you're expecting, Matlab will pop up this box, telling you what parameters are called for when you go to call the method.
However, if you write a handle class method then you have to include the object as the first parameter. E.g.:
function [x] = doSomething(arg, param1, param2, ...)
fprintf('I did %d things!\n', param1);
end
But when you try to call this function, the popup box only asks for the arg class instance and doesn't mention the other parameters. Like this:
How can I arrange it so that my users get prompted for the correct inputs and not only the class-object itself?
Converting my comment into an answer:
The box is called function hint. The same question here did not receive an answer. I guess it is not possible currently, submit a feature request.
This question already has answers here:
What is the formal difference in Scala between braces and parentheses, and when should they be used?
(9 answers)
Closed 7 years ago.
I have done C/Java/C3/Python/JS all my life. Since yesterday I am looking at some scala code, now i m super confused about everything..
The snippet goes:
// Parse the input file
val lines = fromTextFile(input)
// Iterate on every element to generate the keys, and then aggregate it
val counts = lines.mapFlatten{
line =>
val rowSplit = line.split(",",-1)
....
}
the signature of the method mapFlatten in scoobi api is :
def mapFlatten[B](f: (A) ⇒ Iterable[B])(implicit arg0: WireFormat[B]): DList[B]
Why do we call mapFlatten with
mapFlatten{
instead of
mapFlatten({
Is it because the function is taking a predicate as a paramater?
in this sense, are while, else, if functions too?
According to this answer
Why use curly braces over parentheses?
there are cases when you do need to use curl braces(multiline expressions) and cases when you don't.
Indeed, they are all functions that receive functions inside.
In this situation:
def mapFlatten[B](f: (A) ⇒ Iterable[B])(implicit arg0: WireFormat[B]): DList[B]
You pass a function f:(A) that should result in Iterable[B]
From Programing in Scala, Fist Edition, Version 7 (yeah, a little dated):
In any method invocation in Scala in which you're passing in exactly one argument, you can opt to use curly braces to surround the argument instead of parentheses.
And then later:
The purpose of this ability ... is to enable client programmers to write function literals between curly braces. This can make the method call feel more like a control abstraction.
Suppose I have defined a function:
def hello(name:String, words:String) = println("Hello!" + name + words)
Then I defined a partial function:
def p = hello _
Print p, displayed:
(String, String) => Unit = <function2>
There's no function name displayed. Is it possible to get the original method name hello from the partial function p?
There has been some discussion on the mailing lists recently about a language construct that allows you to identify the current method that you're in. It would be called something like thisMethod and would essentially do for methods what this does for class instances.
I'd be interested to see how this interacts with functions (which are a different concept from methods). Your p is an anonymous function created from partially applying the hello method (again, you need to be careful here, a "partially applied function is a very different thing from a PartialFunction). The actual method then invoked would be apply on this function object, and there are several possibilities as to how thisMethod could behave in such a case.
Whatever happens, p is just an object reference, don't expect to ever be able to access it as a name.
No.
Its a feature I'd love to have, but it has serious conceptual problems like, what should happen, when the same function is given two names ... it should still be the same function, shouldn't it?
update in response to comment:
def p = hello _
def q = p
What is the name of q? p? or hello? or println? I have a hard time imagining a solution that is simple, consistent and usefull.
... that is actually a "partially applied function" that is created anonymously by calling your hello function without the parameters being applied. It does not have an explicit name to show.