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
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
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
Well, the expression fun() -> 2 is a function. Not a number, not a string, not an array of bytes, but a function. The only thing to do with a function is to call it. Or, in other words, execute it. Invoke it. That's what you do with a(). You pass it a parameter () (yes, two parentheses in a row is an actual thing in F#, you can pass it as a parameter), and the function runs and returns you a result. Which is 2. A number.
So, once again: first you have a function. Then you execute it. And the result of that execution is a number.
Now, if you want to multiply a function by three... What do you mean by that? That's kinda nonsensical. Do you mean for it to execute three times longer? Or return three results instead of one? Multiplying by a number is not something you can do with a function.
If you want another function that returns a 6 instead of 2, then just say so:
let a = fun() -> 2*3
Or, if you want to take your first function and build another function on top of it, by multiplying the result of the first function, - then you need to have this second function first call (invoke, execute) the first function, take its result, and multiply that by three:
let a = fun() -> 2
let b = fun() -> a() * 3
As for the very last example - that's a bit trickier.
First, the expression fun _ -> 2. That's also a function. And it takes one parameter. And it doesn't care what that parameter is. It sort of says "I'll take any parameter, whatever you throw at me, I don't care, I'll return you 2 anyway". So you can throw any parameter at it. For example, you can throw a 4 at it. It will take a 4, it's not proud. 4 is just fine. That's what you're doing by (fun _ -> 2) 4. This means "create a function that takes any parameter and returns 2, and execute that function with parameter 4".
You can express the same idea in a way that's a bit longer, but easier to understand:
let a = fun _ -> 2
let b = a 4 // b = 2
And then, as the last step, you take that result of executing the function with parameter 4, and multiply that result by 3. And you get 6. Which is a number. And not a function. So you can't execute (invoke, call) it anymore. Because, you know, you can't execute a number. Only a function.
I understand. So if I want it to be expression, not a function, I need function to be invoked:
let a = 3* (fun () -> 2)()
so, here a=6
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);