Questions tagged [lambda]

Anonymous functions or closures in programming languages such as Lisp, C#, C++, Lua, Python, Ruby, JavaScript, or Java. (Also, lambda expression.)

1187
votes
8answers
348k views

What is a lambda expression in C++11?

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.
188
votes
6answers
31k 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=[0,1,2,3]for i in [0,1,2,3]:adders[i]=lambda a: ...
334
votes
7answers
63k views

When should I use Arrow functions in ECMAScript 6?

The question is directed at people who have thought about code style in the context of the upcoming ECMAScript 6 (Harmony) and who have already worked with the language.With ()=> {} and function ...
436
votes
18answers
178k 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 ...
1474
votes
5answers
88k 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 ...
806
votes
26answers
474k views

Why are Python 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 needed, but ...
439
votes
11answers
192k 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....
259
votes
11answers
127k 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 ...
119
votes
4answers
23k views

Is it possible to figure out the parameter type and return type of a lambda?

Given a lambda, is it possible to figure out it's parameter type and return type? If yes, how?Basically, I want lambda_traits which can be used in following ways:auto lambda=[](int i) { return ...
113
votes
11answers
47k views

Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)

In JDK 8 with lambda b93 there was a class java.util.stream.Streams.zip in b93 which could be used to zip streams (this is illustrated in the tutorial Exploring Java8 Lambdas. Part 1 by Dhananjay Nene)...
765
votes
9answers
173k 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>?
184
votes
7answers
74k 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 typeExpression<Func<T, bool>> ...
120
votes
3answers
17k views

Does a lambda expression create an object on the heap every time it's executed?

When I iterate over a collection using the new syntactic sugar of Java 8, such asmyStream.forEach(item -> {// do something useful});Isn't this equivalent to the 'old syntax' snippet below?...
131
votes
6answers
72k views

Passing 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 exampleusing DecisionFn=...
22
votes
1answer
9k views

Tkinter assign button command in loop with lambda

I'm trying to create a few buttons (with a for) like so:def a(self, name):print nameusers={"Test":"127.0.0.0", "Test2":"128.0.0.0"}row=1for name in users:user_button=Tkinter....
622
votes
17answers
305k 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 parameters,...
276
votes
14answers
205k 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 ...
340
votes
23answers
202k 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 ...
599
votes
13answers
494k views

list comprehension vs. lambda + filter

I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.My code looked like this:my_list=[x for x in my_list if x.attribute==...
233
votes
1answer
21k 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 ...
125
votes
4answers
23k views

How to serialize a lambda?

How can I elegantly serialize a lambda?For example, the code below throws a NotSerializableException. How can I fix it without creating a SerializableRunnable "dummy" interface?public static void ...
672
votes
17answers
420k 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> ...
46
votes
1answer
10k views

How will Java lambda functions be compiled?

Loop.times(5, () -> {System.out.println("looping");});Which of these would it effectively compile to?for(int i=0; i < 5; i++)System.out.println("looping");or something like...
613
votes
20answers
197k views

What is a lambda (function)?

For a person without a comp-sci background, what is a lambda in the world of Computer Science?
219
votes
14answers
87k views

How can I throw CHECKED exceptions from inside Java 8 streams?

How can I throw CHECKED exceptions from inside Java 8 streams/lambdas?In other words, I want to make code like this compile:public List<Class> getClasses() throws ClassNotFoundException { ...
24
votes
1answer
5k views

Python lambda closure scoping

I am trying to use closures to eliminate a variable from a function signature (the application is to make writing all the functions needed for connecting Qt signals for an interface to control a ...
298
votes
9answers
566k 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,...
197
votes
7answers
121k views

How do you perform a left outer join using linq extension methods

Assuming I have a left outer join as such:from f in Foojoin b in Bar on f.Foo_Id equals b.Foo_Id into gfrom result in g.DefaultIfEmpty()select new { Foo=f, Bar=result }How would I express ...
71
votes
2answers
12k views

Comparator.reversed() does not compile using lambda

I have a list with some User objects and i'm trying to sort the list, but only works using method reference, with lambda expression the compiler gives an error:List<User> userList=Arrays....
63
votes
6answers
5k views

Why filter() after flatMap() is “not completely” lazy in Java streams?

I have the following sample code:System.out.println("Result: " +Stream.of(1, 2, 3).filter(i -> {System.out.println(i);...
674
votes
10answers
100k 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?
329
votes
20answers
830k views

Finding the average of a list

I have to find the average of a list in Python. This is my code so farl=[15, 18, 2, 36, 12, 78, 5, 6, 9]print reduce(lambda x, y: x + y, l)I've got it so it adds together the values in the list,...
45
votes
2answers
8k views

C++11 does not deduce type when std::function or lambda functions are involved

When I define this function,template<class A>set<A> test(const set<A>& input) {return input;}I can call it using test(mySet) elsewhere in the code without having to ...
49
votes
2answers
13k views

Why is it bad to use an iteration variable in a lambda expression

I was just writing some quick code and noticed this complier error Using the iteration variable in a lambda expression may have unexpected results.Instead, create a local variable within the ...
167
votes
6answers
65k views

delegate keyword vs. lambda notation

Once it is compiled, is there a difference between:delegate { x=0; }and()=> { x=0 }?
195
votes
1answer
67k views

How to remove a lambda event handler [duplicate]

Possible Duplicates:Unsubscribe anonymous method in C#How do I Unregister ‘anonymous’ event handler I recently discovered that I can use lambdas to create simple event handlers. I ...
36
votes
4answers
9k views

Most efficient way to test equality of lambda expressions

Given a method signature:public bool AreTheSame<T>(Expression<Func<T, object>> exp1, Expression<Func<T, object>> exp2)What would be the most efficient way to say if ...
50
votes
6answers
24k views

How to convert a lambda to an std::function using templates

Basically, what I want to be able to do is take a lambda with any number of any type of parameters and convert it to an std::function.I've tried the following and neither method works.std::function(...
71
votes
7answers
36k views

C++ lambda with captures as a function pointer

I was playing with C++ lambdas and their implicit conversion to function pointers. My starting example was using them as callback for the ftw function. This works as expected.#include <ftw.h>#...
36
votes
2answers
28k views

Uncaught TypeError: Illegal invocation in javascript

I'm creating a lambda function that executes a second function with a concrete params.This code works in Firefox but not in Chrome, its inspector shows a weird error, Uncaught TypeError: Illegal ...
95
votes
6answers
21k views

What is the type of lambda when deduced with “auto” in C++11?

I had a perception that, type of a lambda is a function pointer. When I performed following test, I found it to be wrong (demo).#define LAMBDA [] (int i) -> long { return 0; }int main (){...
104
votes
6answers
40k views

Move capture in lambda

How do I capture by move (also known as rvalue reference) in a C++11 lambda?I am trying to write something like this:std::unique_ptr<int> myPointer(new int);std::function<void(void)> ...
65
votes
5answers
154k views

How to perform Join between multiple tables in LINQ lambda

I am trying to perform a Join between multiple tables in LINQ. I have the following classes:Product {Id, ProdName, ProdQty}Category {Id, CatName}ProductCategory{ProdId, CatId} //association ...
102
votes
6answers
108k views

Syntax behind sorted(key=lambda: …)

I don't quite understand the syntax behind the sorted() argument:key=lambda variable: variable[0]Isn't lambda arbitrary? Why is variable stated twice in what looks like a dict?
108
votes
6answers
129k 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....
101
votes
3answers
48k views

Performance of foreach, array_map with lambda and array_map with static function

What's the performance difference (if there is any) between these three approaches, both used to transform an array to another array?Using foreachUsing array_map with lambda/closure functionUsing ...
317
votes
14answers
75k 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 ...
138
votes
6answers
69k views

How to convert a String to its equivalent LINQ Expression Tree?

This is a simplified version of the original problem.I have a class called Person:public class Person {public string Name { get; set; }public int Age { get; set; }public int Weight { get; ...
91
votes
13answers
37k views

Recursive lambda functions in C++11

I am new to C++11. I am writing the following recursive lambda function, but it doesn't compile.sum.cpp#include <iostream>#include <functional>auto term=[](int a)->int {...
67
votes
3answers
7k views

Is there a way to compare lambdas?

Say I have a List of object which were defined using lambda expressions (closures). Is there a way to inspect them so they can be compared?The code I am most interested in isList<Strategy&...

153050per page
angop.ao, elkhabar.com, noa.al, afghanpaper.com, bbc.com, time.com, cdc.gov, nih.gov, xnxx.com, github.com,