The first expression will be used where you get 2 parameters for a method and return a value.
The second expression will be used
x -> x * xwhere you get 1 parameters for a method and return a value.The third expression
( ) -> xwill be used( ) -> xwhere you get 0 parameters for a method and return a value.
Let's take the third one. Suppose you have an interface which takes no parameters and returns a value.
static interface RandomMath {
public int random();
}
Now You want to instantiate this interface along with its implementation. Without using lambda it will be done as below:-
Random random = new Random();
RandomMath randomMath = new RandomMath() {
@Override
public int random() {
return random.nextInt();
}
};
Using lambda it will be like:-
Random random = new Random();
RandomMath randomMath = () -> random.nextInt(); //the third type.
Similarly, for first two it can be used for methods which take two and one parameters and return a value.
static interface PlusMath {
public int plus(int a, int b);
}
PlusMath plusMath = (a, b) -> a + b;
static interface SquareMath {
public int square(int a);
}
SquareMath squareMath = a -> a * a;
Answer from Mritunjay on Stack Overflow
The first expression will be used where you get 2 parameters for a method and return a value.
The second expression will be used
x -> x * xwhere you get 1 parameters for a method and return a value.The third expression
( ) -> xwill be used( ) -> xwhere you get 0 parameters for a method and return a value.
Let's take the third one. Suppose you have an interface which takes no parameters and returns a value.
static interface RandomMath {
public int random();
}
Now You want to instantiate this interface along with its implementation. Without using lambda it will be done as below:-
Random random = new Random();
RandomMath randomMath = new RandomMath() {
@Override
public int random() {
return random.nextInt();
}
};
Using lambda it will be like:-
Random random = new Random();
RandomMath randomMath = () -> random.nextInt(); //the third type.
Similarly, for first two it can be used for methods which take two and one parameters and return a value.
static interface PlusMath {
public int plus(int a, int b);
}
PlusMath plusMath = (a, b) -> a + b;
static interface SquareMath {
public int square(int a);
}
SquareMath squareMath = a -> a * a;
The first two examples are different from the last one. The variables in the function (lambda expression) refer to its parameters.
While in the third example the x refers to variable outside of the lambda expression but within the lexical scope (can be either local variable from the method or instance variable).
Example 1 (typically stream reduce), computes the sum by passing the so far computed sum and next item from the list to lambda function:
int sum = list.stream().reduce((int x, int y) -> x+y);
Example 2, computes the squares from the elements:
squares = list.stream().map((int x) -> x*x).collect(Collectors.toList());
Example 3, sets the element to default value if it's null in the list:
final int x = MY_DEFAULT_VALUE;
// lambda refers the the variable above to get the default
defaults = list.stream().map((Integer v) -> v != null ? v : x);
Or better for example 3 is the map atomic methods:
int x = MY_DEFAULT_VALUE;
// lambda refers the the variable above to get the default
map.computeIfAbsent(1, (Integer key) -> x);
// the same could be achieved by putIfAbsent() of course
// but typically you would use (Integer key) -> expensiveComputeOfValue(x)
// ...
// or quite common example with executor
public Future<Integer> computeAsync(final int value) {
// pass the callback which computes the result synchronously, to Executor.submit()
// the callback refers to parameter "value"
return executor.submit(() -> computeSync(value));
}
Well, the other answers cover what \() -> "something" means in Haskell: an unary function that takes () as argument.
What is a function without arguments? – A value. Actually, it can occasionally be useful to think of variables as nullary functions that evaluate to their value. The
let-syntax for a function without arguments (which doesn't actually exist) ends up giving you a variable binding:let x = 42 in ...Does lambda calculus have nullary functions? – No. Every function takes exactly one argument. However, this argument may be a list, or the function may return another function that takes the next argument. Haskell prefers the latter solution, so that
a b cis actually two function calls((a b) c). To simulate nullary functions, you have to pass some unused placeholder value.
You're misinterpreting what () means in Haskell. It isn't the lack of a value, it is rather the only value of the Unit type (the type itself being referred to by an empty set of parentheses ()).
Since lambdas can be constructed to use pattern matching, the lambda expression \() -> "s" is explicitly saying "create an anonymous function, expecting an input that matches the () pattern". There isn't much point to doing it, but it's certainly allowed.
You can use pattern matching with lambdas in other ways as well, for example:
map (\(a, b) -> a + b) [(1,2), (3,4), (5,6)] -- uses pattern matching to destructured tuples
map (\(Name first _) -> first) [Name "John" "Smith", Name "Jane" "Doe"] -- matches a "Name" data type and its first field
map (\(x:_) -> x) [[1,2,3], [4,5,6]] -- matches the head of a list
The nullary lambda equivalent would be () => 2.
That would be:
() => 2
Example usage:
var list = new List<int>(Enumerable.Range(0, 10));
Func<int> x = () => 2;
list.ForEach(i => Console.WriteLine(x() * i));
As requested in the comments, here's a breakdown of the above sample...
// initialize a list of integers. Enumerable.Range returns 0-9,
// which is passed to the overloaded List constructor that accepts
// an IEnumerable<T>
var list = new List<int>(Enumerable.Range(0, 10));
// initialize an expression lambda that returns 2
Func<int> x = () => 2;
// using the List.ForEach method, iterate over the integers to write something
// to the console.
// Execute the expression lambda by calling x() (which returns 2)
// and multiply the result by the current integer
list.ForEach(i => Console.WriteLine(x() * i));
// Result: 0,2,4,6,8,10,12,14,16,18
The addActionListener method requires an ActionListener, which is an interface with a single method
public void actionPerformed(ActionEvent e);
In Java 8, you can use a lambda expression to implement an interface with a single method like this one. The rule is that the lambda expression must have the same parameter types and return types as the method in the interface. The compiler can then convert the lambda expression into a class that implements the interface.
So in this particular case, you need a lambda expression that
- has a single parameter - an
ActionEvent - has
voidreturn type - that is, it doesn't return anything.
In e -> System.out.println("something");, the e is the ActionEvent. You could only replace it with () if the single method in the interface had no parameters at all.
e here is the name of the variable (parameter of the method), it could be anything. e is possibly of type ActionEvent, a () indicates a method with no parameters
Use a Func<T1, T2, TResult> delegate as the parameter type and pass it in to your Query:
public List<IJob> getJobs(Func<FullTimeJob, Student, FullTimeJob> lambda)
{
using (SqlConnection connection = new SqlConnection(getConnectionString())) {
connection.Open();
return connection.Query<FullTimeJob, Student, FullTimeJob>(sql,
lambda,
splitOn: "user_id",
param: parameters).ToList<IJob>();
}
}
You would call it:
getJobs((job, student) => {
job.Student = student;
job.StudentId = student.Id;
return job;
});
Or assign the lambda to a variable and pass it in.
If I understand you need following code. (passing expression lambda by parameter) The Method
public static void Method(Expression<Func<int, bool>> predicate) {
int[] number={1,2,3,4,5,6,7,8,9,10};
var newList = from x in number
.Where(predicate.Compile()) //here compile your clausuly
select x;
newList.ToList();//return a new list
}
Calling method
Method(v => v.Equals(1));
You can do the same in their class, see this is example.
public string Name {get;set;}
public static List<Class> GetList(Expression<Func<Class, bool>> predicate)
{
List<Class> c = new List<Class>();
c.Add(new Class("name1"));
c.Add(new Class("name2"));
var f = from g in c.
Where (predicate.Compile())
select g;
f.ToList();
return f;
}
Calling method
Class.GetList(c=>c.Name=="yourname");
I hope this is useful
Sort of! There is a new idiom in town, that is nice and may help you in some cases. It is not fully what you want, but sometimes I think you will like it.
Since underscore ("_") is a valid C# identifier, it is becoming a common idiom to use it as a parameter name to a lambda in cases where you plan to ignore the parameter anyway. If other coders are aware of the idiom, they will know immediately that the parameter is irrelevant.
For example:
ExternalId.IfNotNullDo( _ => ExternalId=ExternalId.Trim());
Easy to type, conveys your intent, and easier on the eyes as well.
Of course, if you're passing your lambda to something that expects an expression tree, this may not work, because now you're passing a one-parameter lambda instead of a no-parameter lambda.
But for many cases, it is a nice solution.
For a lambda, no: you need () =>
Is it for a delegate or an expression? For delegates, another option is delegate {...}. This may or may not be desirable, depending on the scenario. It is more keys, certainly...
In some cases (not this one) you can use a target method directly - i.e.
ExternalId.IfNotNullDo(SomeMethod);
Your case is similar with Supplier in Java 8
Supplier<Integer> supplier = () -> 0;
System.out.println(supplier.get());
You do not really convert methods into lambdas directly. Lambdas are more-or-less implementations of Functional Interfaces created on the fly without the overhead of the classic anonymous inner function approach.
So, if you want to pass it around as a lambda, you need to find a matching Functional Interface and assign a lambda to it.
In this case, you have a method without parameters that returns an int and one of the possible choices would be to use IntSupplier:
IntSupplier supplier = () -> 0;
and now, you can call it by doing:
supplier.getAsInt()
If you want to return a boxed Integer, you would need to use a generic Supplier<T>:
Supplier<Integer> supplier = () -> 0;
supplier.get(); // 0