Function returning a lambda expression
You don't need a handcrafted function object, just use std::function
, to which lambda functions are convertible:
This example returns the integer identity function:
std::function<int (int)> retFun() {
return [](int x) { return x; };
}
How to return a lambda function and use by passing as an argument to a method in Java 8? Why I can't use :: operator?
The method validateUser
expectes a Predicate<String>
, so method handles (the ::
syntax) and lambdas must conform to that functional interface.
For a method handle to conform to Predicate<String>
there can be three possible method signatures (and return type) to match:
- (non-static)
boolean methodName()
in theString
class, referred to asString::methodName
- (static)
boolean methodName(String value)
in any class referred to asClassName::methodName
- (non-static)
boolean methodName(String value)
in any class referred to assomeInstance::methodName
Role.isInRealm()
returns a predicate, so it cannot function as a predicate itself as it has Predicate<String> methodName()
as its signature and return type. So Role::isInRealm
cannot work.
Similarly r -> Role.isInRealm()
will not work, because this is a lambda of the form Function<String, Predicate<String>>
(or probably more correct: Function<?, Predicate<String>>
as there is nothing to infer the type of r
), not Predicate<String>
If you want to use isInRealm
as a predicate itself, then you need to write it as:
public static boolean isInRealm(String role) {
return Arrays.stream(values()).anyMatch(value -> value.value.equals(role));
}
Notice that instead of returning a lambda, it now returns a boolean result.
Then you can call it using:
validateUser(Role::isInRealm);
// notice how it passes r to isInRealm
validateUser(r -> Role.isInRealm(r));
Why does returning this lambda expression result in a string?
Well, you're not calling the lambda
function and as such the return value is a tuple of the defined lambda
function and the values of a
and b
.
Change it to call the lambda before returning while supplying the arguments to it:
return (lambda a, b: a+b if a != b else (a+b)*2)(a, b)
And it works just fine:
print(sum_double(1, 2))
3
print(sum_double(2, 2))
8
Lambda in a function
In the first example, you are returning a callable (ie. the lambda function).
In the second example, you are calling the nolambda
function, which means that the return value of make_incrementor
will be the same value returned by nolambda
.
To better understand, try looking at it like this:
def make_incrementor(n):
def some_function(x):
return x + n
return some_function
def make_incrementor(n):
some_return_value = nolambda(n)
return some_return_value
Returning a value from a method within a lambda expression
Is there some type of way to break or force a return for the entire method?
No. At least, not unless you throw an exception.
Basically, that's not what forEach
is meant for. You could write a method which accepted a function which would return null
for "keep going" and non-null for "stop, and make this the result"... but that method isn't forEach
.
The fact that you're using a lambda expression is really incidental here. Imagine you were just calling forEach
and passing in some argument - wouldn't it be really weird if that call made your findMissingNumber
method return (without an exception), without the findMissingNumber
method itself having the return statement?
Returning a lambda function in C++
The typedef makes it easier to write the function declaration, but you don't need the typedef if you know the right syntax:
int (*retFun())(int) {
return [](int x) { return x; };
}
As you can see, the typedef not only makes it easier to write; it makes it easier to read as well.
How to return a lambda function?
With C++14 function return type deduction, that should work.
In C++11, you could define another lambda (which can deduce the return type), rather than a function (which can't):
auto makeLambda = [](double ratio) {
return [=](double value) {return value * ratio;};
};
As noted in the comments, this could be further wrapped, if you particularly want a function:
auto makeLambdaFn(double ratio) -> decltype(makeLambda(ratio)) {
return makeLambda(ratio);
}
How should I return a lambda function from a function in Android (Kotlin)
Suppose, you’re trying to add two integers and will return an integer result.
In Kotlin, we can simply create a normal function like this:
fun addTwoNumbers(first: Int, second: Int): Int = first + second
Now let’s create another method which will return a lambda, like the following:
fun sum(): (Int, Int) -> Int = { x, y -> addTwoNumbers(x, y) }
As you can see, the return type of sum() is (Int, Int) -> Int, which means this is returning a lambda.
And for creating lambdas, we will simply use { } and will write the function body inside these parenthesis, like this: { x, y -> addTwoNumbers(x, y) }
This type of functions are also known as Higher Order Functions.
Now, we can simply use it like the following:-
fun main() {
val summation = sum()
println(summation(100, 300))
}
This will print 400 in the console.
Related Topics
What Is a Reference-To-Pointer
How to Building Static Qt with Static Openssl
C++ N Nested Vectors at Runtime
Unique Hardware Id in MAC Os X
Why Is Statically Linking Glibc Discouraged
Difference Between Creating Object with () or Without
C++11 - Declaring Non-Static Data Members as 'Auto'
Why Is Copy Constructor Called Instead of Conversion Constructor
C++ Global Variable Declaration
Function Composition in C++/C++11
Why Is #Define Bad and What Is the Proper Substitute
Variadic Deduction Guide Not Taken by G++, Taken by Clang++ - Who Is Correct
C++11: Number of Variadic Template Function Parameters
When Can You Omit the File Extension in an #Include Directive
Compiling Cuda Code in Qt Creator on Windows
Why Does C++11 Have 'Make_Shared' But Not 'Make_Unique'
Will a "Variablename;" C++ Statement Be a No-Op at All Times