Questions tagged [lambda]
DO NOT USE FOR THE AWS SERVICE (use [aws-lambda] for those questions!) Lambdas are anonymous functions or closures in programming languages such as Lisp, C#, C++, Lua, Python, Ruby, JavaScript, Java, Excel or Google sheets. (Also, lambda expression.)
lambda
30,144
questions
1865
votes
4
answers
121k
views
Is there a reason for C#'s reuse of the variable in a foreach?
When using lambda expressions or anonymous methods in C#, we have to be wary of the access to modified closure pitfall. For example:
foreach (var s in strings)
{
query = query.Where(i => i.Prop ...
1760
votes
10
answers
668k
views
What is a lambda expression, and when should I use one?
What is a lambda expression in C++11? When would I use one? What class of problem do they solve that wasn't possible prior to their introduction?
A few examples, and use cases would be useful.
1144
votes
12
answers
305k
views
Why would you use Expression<Func<T>> rather than Func<T>?
I understand lambdas and the Func and Action delegates. But expressions
stump me.
In what circumstances would you use an Expression<Func<T>> rather than a plain old Func<T>?
1109
votes
18
answers
839k
views
List comprehension vs. lambda + filter
I have a list that I want to filter by an attribute of the items.
Which of the following is preferred (readability, performance, other reasons)?
xs = [x for x in xs if x.attribute == value]
xs = ...
1058
votes
23
answers
761k
views
Java 8 List<V> into Map<K, V>
I want to translate a List of objects into a Map using Java 8's streams and lambdas.
This is how I would write it in Java 7 and below.
private Map<String, Choice> nameMap(List<Choice> ...
987
votes
17
answers
182k
views
What is the difference between a 'closure' and a 'lambda'?
Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused.
And now that we're here, how do they differ from a regular function?
985
votes
26
answers
589k
views
How are lambdas useful? [closed]
I'm trying to figure out Python lambdas. Is lambda one of those "interesting" language items that in real life should be forgotten?
I'm sure there are some edge cases where it might be ...
849
votes
24
answers
394k
views
What is a lambda (function)?
For a person without a comp-sci background, what is a lambda in the world of Computer Science?
834
votes
20
answers
476k
views
Distinct() with lambda?
Right, so I have an enumerable and wish to get distinct values from it.
Using System.Linq, there's, of course, an extension method called Distinct. In the simple case, it can be used with no ...
663
votes
19
answers
393k
views
Getting all types that implement an interface
Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?
This is what I want to re-write:
foreach (Type t in this....
640
votes
28
answers
514k
views
Java 8 Lambda function that throws exception?
I know how to create a reference to a method that has a String parameter and returns an int, it's:
Function<String, Integer>
However, this doesn't work if the function throws an exception, say ...
601
votes
23
answers
288k
views
Retrieving Property name from lambda expression
Is there a better way to get the Property name when passed in via a lambda expression?
Here is what i currently have.
eg.
GetSortingInfo<User>(u => u.UserId);
It worked by casting it as a ...
564
votes
10
answers
1.2m
views
Join/Where with LINQ and Lambda
I'm having trouble with a query written in LINQ and Lambda. So far, I'm getting a lot of errors here's my code:
int id = 1;
var query = database.Posts.Join(database.Post_Metas,
...
511
votes
16
answers
835k
views
Is there a way to perform "if" in python's lambda? [duplicate]
In Python 2.6, I want to do:
f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
This clearly isn't the syntax. Is it possible to ...
502
votes
24
answers
308k
views
No Multiline Lambda in Python: Why not?
I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and ...
502
votes
15
answers
447k
views
Retrieving a List from a java.util.stream.Stream in Java 8
I was playing around with Java 8 lambdas to easily filter collections. But I did not find a concise way to retrieve the result as a new list within the same statement. Here is my most concise approach ...
502
votes
9
answers
148k
views
When should I use arrow functions in ECMAScript 6?
With () => {} and function () {} we are getting two very similar ways to write functions in ES6. In other languages lambda functions often distinguish themselves by being anonymous, but in ...
491
votes
16
answers
402k
views
How do I define a method which takes a lambda as a parameter in Java 8?
In Java 8, methods can be created as Lambda expressions and can be passed by reference (with a little work under the hood). There are plenty of examples online with lambdas being created and used with ...
485
votes
10
answers
796k
views
List<T> OrderBy Alphabetical Order
I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List<T>. For the sake of this example, let's say I have a List of a Person type with a property of lastname. How would I ...
433
votes
21
answers
30k
views
Reflecting parameter name: abuse of C# lambda expressions or syntax brilliance? [closed]
I am looking at the MvcContrib Grid component and I'm fascinated, yet at the same time repulsed, by a syntactic trick used in the Grid syntax:
.Attributes(style => "width:100%")
The syntax above ...
430
votes
15
answers
495k
views
Break or return from Java 8 stream forEach?
When using external iteration over an Iterable we use break or return from enhanced for-each loop as:
for (SomeObject obj : someObjects) {
if (some_condition_met) {
break; // or return obj
...
389
votes
15
answers
207k
views
Difference between final and effectively final
I'm playing with lambdas in Java 8 and I came across warning local variables referenced from a lambda expression must be final or effectively final. I know that when I use variables inside anonymous ...
374
votes
18
answers
163k
views
How can I throw checked exceptions from inside Java 8 lambdas/streams?
How can I throw checked exceptions from inside Java 8 lambda, used in a stream for example?
In other words, I want to make code like this compile:
public List<Class> getClasses() throws ...
374
votes
8
answers
86k
views
What do lambda function closures capture?
Recently I started playing around with Python and I came around something peculiar in the way closures work. Consider the following code:
adders=[None, None, None, None]
for i in [0,1,2,3]:
adders[...
370
votes
3
answers
241k
views
Java 8 lambdas, Function.identity() or t->t
I have a question regarding the usage of the Function.identity() method.
Imagine the following code:
Arrays.asList("a", "b", "c")
.stream()
.map(Function.identity()) // <- ...
351
votes
10
answers
298k
views
Java 8 lambda Void argument
Let's say I have the following functional interface in Java 8:
interface Action<T, U> {
U execute(T t);
}
And for some cases I need an action without arguments or return type. So I write
...
345
votes
14
answers
84k
views
When to use lambda, when to use Proc.new?
In Ruby 1.8, there are subtle differences between proc/lambda on the one hand, and Proc.new on the other.
What are those differences?
Can you give guidelines on how to decide which one to choose?
In ...
345
votes
10
answers
277k
views
Passing capturing lambda as function pointer
Is it possible to pass a lambda function as a function pointer? If so, I must be doing something incorrectly because I am getting a compile error.
Consider the following example
using DecisionFn = ...
340
votes
8
answers
132k
views
E731 do not assign a lambda expression, use a def
I get this pep8 warning whenever I use lambda expressions. Are lambda expressions not recommended? If not why?
334
votes
24
answers
374k
views
Filter Java Stream to 1 and only 1 element
I am trying to use Java 8 Streams to find elements in a LinkedList. I want to guarantee, however, that there is one and only one match to the filter criteria.
Take this code:
public static void main(...
332
votes
13
answers
112k
views
Why does C++11's lambda require "mutable" keyword for capture-by-value, by default?
Short example:
#include <iostream>
int main()
{
int n;
[&](){n = 10;}(); // OK
[=]() mutable {n = 20;}(); // OK
// [=](){n = 10;}(); // Error: a by-...
331
votes
4
answers
303k
views
Java 8 Streams: multiple filters vs. complex condition
Sometimes you want to filter a Stream with more than one condition:
myList.stream().filter(x -> x.size() > 10).filter(x -> x.isCool()) ...
or you could do the same with a complex condition ...
331
votes
1
answer
42k
views
A positive lambda: '+[]{}' - What sorcery is this? [duplicate]
In Stack Overflow question Redefining lambdas not allowed in C++11, why?, a small program was given that does not compile:
int main() {
auto test = []{};
test = []{};
}
The question was ...
322
votes
10
answers
157k
views
Combining two expressions (Expression<Func<T, bool>>)
I have two expressions of type Expression<Func<T, bool>> and I want to take to OR, AND or NOT of these and get a new expression of the same type
Expression<Func<T, bool>> ...
321
votes
17
answers
248k
views
C# Lambda expressions: Why should I use them?
I have quickly read over the Microsoft Lambda Expression documentation.
This kind of example has helped me to understand better, though:
delegate int del(int i);
del myDelegate = x => x * x;
int ...
312
votes
12
answers
263k
views
Using Java 8's Optional with Stream::flatMap
The new Java 8 stream framework and friends make for some very concise Java code, but I have come across a seemingly-simple situation that is tricky to do concisely.
Consider a List<Thing> ...
306
votes
12
answers
239k
views
`break` and `continue` in `forEach` in Kotlin
Kotlin has very nice iterating functions, like forEach or repeat, but I am not able to make the break and continue operators work with them (both local and non-local):
repeat(5) {
break
}
(1..5)....
302
votes
12
answers
555k
views
Sorting a list using Lambda/Linq to objects
I have the name of the "sort by property" in a string. I will need to use Lambda/Linq to sort the list of objects.
Ex:
public class Employee
{
public string FirstName {set; get;}
public string ...
299
votes
3
answers
246k
views
Where do I mark a lambda expression async?
I've got this code:
private async void ContextMenuForGroupRightTapped(object sender, RightTappedRoutedEventArgs args)
{
CheckBox ckbx = null;
if (sender is CheckBox)
{
ckbx = ...
295
votes
4
answers
148k
views
How to merge a list of lists with same type of items to a single list of items?
The question is confusing, but it is much more clear as described by the following code:
List<List<T>> listOfList;
// add three lists of List<T> to listOfList, for example
/*...
295
votes
14
answers
186k
views
Can lambda functions be templated?
In C++11, is there a way to template a lambda function? Or is it inherently too specific to be templated?
I understand that I can define a classic templated class/functor instead, but the question is ...
285
votes
1
answer
16k
views
How is "int main(){(([](){})());}" valid C++?
I recently came across the following esoteric piece of code.
int main(){(([](){})());}
Reformat it as follows to make it more readable:
int main(){
(([](){})()); // Um... what?!?!
}
But I ...
278
votes
14
answers
357k
views
convert a list of objects from one type to another using lambda expression
I have a foreach loop reading a list of objects of one type and producing a list of objects of a different type. I was told that a lambda expression can achieve the same result.
var origList = List<...
271
votes
13
answers
504k
views
How to use a Java8 lambda to sort a stream in reverse order?
I'm using java lambda to sort a list.
how can I sort it in a reverse way?
I saw this post, but I want to use java 8 lambda.
Here is my code (I used * -1) as a hack
Arrays.asList(files).stream()
...
268
votes
1
answer
217k
views
Multiple Order By with LINQ [duplicate]
I start with a basic class that I want to manipulate in a List using LINQ, something like the following:
public class FooBar
{
public virtual int Id { get; set; }
public virtual string ...
266
votes
1
answer
112k
views
How to remove a lambda event handler [duplicate]
I recently discovered that I can use lambdas to create simple event handlers. I could for example subscribe to a click event like this:
button.Click += (s, e) => MessageBox.Show("Woho");
...
263
votes
6
answers
350k
views
OrderBy descending in Lambda expression?
I know in normal Linq grammar, orderby xxx descending is very easy, but how do I do this in Lambda expression?
260
votes
8
answers
413k
views
python max function using 'key' and lambda expression
I come from OOP background and trying to learn python.
I am using the max function which uses a lambda expression to return the instance of type Player having maximum totalScore among the list players....
257
votes
8
answers
152k
views
Is it possible to type hint a lambda function?
Currently, in Python, a function's parameters and return types can be type hinted as follows:
def func(var1: str, var2: str) -> int:
return var1.index(var2)
Which indicates that the function ...
255
votes
6
answers
448k
views
Filter values only if not null using lambda in Java8
I have a list of objects say car. I want to filter this list based on some parameter using Java 8. But if the parameter is null, it throws NullPointerException. How to filter out null values?
Current ...