I recently created this extension method:
public static TR Calculate<TS, TR>(this TS item, Func<TS, TR> selector)
=> selector(item);
Then, I am able to refactor this ugly code, from:
int value = panel.Controls.Cast<Control>().Last().Location.Y
+ panel.Controls.Cast<Control>().Last().Size.Height;
to:
int value = panel.Controls.Cast<Control>().Last().Calculate(
o => o.Location.Y + o.Size.Height);
I would like to know if there is a way to do this using built in .NET functions instead?
By "innate", I guess you mean you don't want to any new methods yourself?
Well, you can do something like this:
value = ((Func<InputType, OutputType>)(o => o.First + o.Second + o.Property.Value))(collection[calc(param)]);
Basically, casting the lambda to a delegate type and then calling the delegate.
Or maybe I have overcomplicated this. What you actually want might toto just not write collection[calc(param)] that many times. If that's the case, you can just:
var o = collection[calc(param)];
value = o.First + o.Second + o.Property.Value;
I don't see why you can't do it like that.
I really suggest you write a separate a method for this kind of transformation. It will be much more readable.
// name this properly so that it describes what you actually want.
public OutputType TransformCollectionItem(TInput o) {
return o.First + o.Second + o.Property.Value;
}
I'm going to say that you shouldn't do that - I don't think it really makes the code more readable.
Given the original code:
int value = panel.Controls.Cast<Control>().Last().Location.Y
+ panel.Controls.Cast<Control>().Last().Size.Height;
Your extension method lets you do this:
int value = panel.Controls.Cast<Control>().Last().Calculate(
o => o.Location.Y + o.Size.Height);
But there seems to be very little advantage over doing this instead:
var c = panel.Controls.Cast<Control>().Last();
int value = c.Location.Y + c.Size.Height;
The latter is actually shorter, and doesn't require the reader to know about an extension method.
Also, your extension method will appear in the tooltip for EVERYTHING...
Mind you, it does allow some interesting code such as
double negated = 1.0.Calculate(x => -x);
The operation you're describing here is usually called "apply", since it is simply applying a function to an argument as an extension method. You ask for a way to do it "innately"; I'm not quite sure what you mean. Function application is already innately built into the syntax of C#. To apply a function F to an argument a to get a result r in C# you do it like this:
r = F(a)
So in your case you would assign the lambda to a variable and then apply it, or, as the other answer notes, cast it to the appropriate function type and apply it.
If you want function application as an extension method that takes a lambda, you'll have to write it yourself.
What you are effectively calling out here is that "let expressions" are missing from C#. What I would really want to write here is:
int value =
let o = panel.Controls.Cast<Control>().Last() in
o.Location.Y + o.Size.Height;
Which many languages support, but C# only supports in query comprehensions.
See my answer to this question for more on "let expressions" in C# and why they would be useful, and how they are equivalent to your application function: DRY (Don't Repeat Yourself) and if assignements
Incidentally, if you name your method Select and make a double-application version called SelectMany, then you can use LINQ on... well, anything:
using System;
static class X
{
public static R Select<A, R>(this A item, Func<A, R> selector) =>
selector(item);
public static R SelectMany<A, B, R>(this A item, Func<A, B> toB, Func<A, B, R> toR) =>
toR(item, toB(item));
}
public class P
{
public static void Main()
{
string myString = "hello";
string result = from s in myString
from b in s + "goodbye"
select b.ToUpper() + " " + s;
Console.WriteLine(result);
}
}
That is a bizarrely baroque way to write a simple program, but if you are really bent on making extension methods that do things that are already in the language, you can do it!
Exercise: Implement the identity monad. You are well on your way!
Related
After reading this article, I can't figure out why lambda expressions are ever used. To be fair, I don't think I have a proper understanding of what delegates and expression tree types are, but I don't understand why anyone would use a lambda expression instead of a declared function. Can someone enlighten me?
First: brevity and locality:
Which would you rather write, read and maintain? This:
var addresses = customers.Select(customer=>customer.Address);
or:
static private Address GetAddress(Customer customer)
{
return customer.Address;
}
... a thousand lines later ...
var addresses = customers.Select(GetAddress);
What's the point of cluttering up your program with hundreds or thousands of four-line functions when you could just put the code you need where you need it as a short expression?
Second: lambdas close over local scopes
Which would you rather read, write and maintain, this:
var currentCity = GetCurrentCity();
var addresses = customers.Where(c=>c.City == currentCity).Select(c=>c.Address);
or:
static private Address GetAddress(Customer customer)
{
return customer.Address;
}
private class CityGetter
{
public string currentCity;
public bool DoesCityMatch(Customer customer)
{
return customer.City == this.currentCity;
}
}
....
var currentCityGetter = new CityGetter();
currentCityGetter.currentCity = GetCurrentCity();
var addresses = customers.Where(currentCityGetter.DoesCityMatch).Select(GetAddress);
All that vexing code is written for you when you use a lambda.
Third: Query comprehensions are rewritten to lambdas for you
When you write:
var addresses = from customer in customers
where customer.City == currentCity
select customer.Address;
it is transformed into the lambda syntax for you. Many people find this syntax pleasant to read, but we need the lambda syntax in order to actually make it work.
Fourth: lambdas are optionally type-inferred
Notice that we don't have to give the type of "customer" in the query comprehension above, or in the lambda versions, but we do have to give the type of the formal parameter when declaring it as a static method. The compiler is smart about inferring the type of a lambda parameter from context. This makes your code less redundant and more clear.
Fifth: Lambdas can become expression trees
Suppose you want to ask a web server "send me the addresses of the customers that live in the current city." Do you want to (1) pull down a million customers from the web site and do the filtering on your client machine, or (2) send the web site an object that tells it "the query contains a filter on the current city and then a selection of the address"? Let the server do the work and send you only the result that match.
Expression trees allow the compiler to turn the lambda into code that can be transformed into another query format at runtime and sent to a server for processing. Little helper methods that run on the client do not.
The primary reason you'd use a lambda over a declared function is when you need to use a piece of local information in the delegate expression. For example
void Method(IEnumerable<Student> students, int age) {
var filtered = students.Where(s => s.Age == age);
...
}
Lambdas allow for the easy capture of local state to be used within the delegate expression. To do this manually requires a lot of work because you need to declare both a function and a containing type to hold the state. For example here's the above without a lambda
void Method(IEnumerable<Student> students, int age) {
var c = new Closure() { Age = age };
var filtered = students.Where(c.WhereDelegate);
...
}
class Closure {
public int age;
bool WhereDelegate(Student s) {
return s.Age == age;
}
}
Typing this out is tedious and error prone. Lambda expressions automate this process.
Let's leave expression trees out of the equation for the moment and pretend that lambdas are just a shorter way to write delegates.
This is still a big win in the realm of statically typed languages like C# because such languages require lots of code to be written in order to achieve relatively simple goals. Do you need to compare sort an array of strings by string length? You need to write a method for that. And you need to write a class to put the method into. And then good practice dictates that this class should be in its own source file. In any but the smallest project, all of this adds up. When we 're talking about small stuff, most people want a less verbose path to the goal and lambdas are about as terse as it can get.
Furthermore, lambdas can easily create closures (capture variables from the current scope and extend their lifetime). This isn't magic (the compiler does it by creating a hidden class and performing some other transformations that you can do yourself), but it's so much more convenient than the manual alternative.
And then there are expression trees: a way for you to write code and have the compiler transform this code into a data structure that can be parsed, modified and even compiled at runtime. This is an extremely powerful feature that opens the door to impressive functionality (which I definitely consider LINQ to be). And you get it "for free".
http://msdn.microsoft.com/en-us/magazine/cc163362.aspx
Great article on what lambdas are, and why you can/should use them.
Essentially, the lambda expression
provides a shorthand for the compiler
to emit methods and assign them to
delegates; this is all done for you.
The benefit you get with a lambda
expression that you don't get from a
delegate/function combination is that
the compiler performs automatic type
inference on the lambda arguments
They are heavily used with LINQ, actually LINQ would be pretty bad without it. You can do stuff like:
Database.Table.Where(t => t.Field ==
"Hello");
They make it easy to pass a simple piece of functionality to another function. For example, I may want to perform an arbitrary, small function on every item in a list (perhaps I want to square it, or take the square root, or so on). Rather than writing a new loop and function for each of these situations, I can write it once, and apply my arbitrary functionality defined later to each item.
Lambda makes code short and sweet. Consider the following two examples:
public class Student
{
public string Name { get; set; }
public float grade { get; set; }
public static void failed(List<Student> studentList, isFaild fail)
{
foreach (Student student in studentList)
{
if(fail(student))
{
Console.WriteLine("Sorry" + " "+student.Name + " "+ "you faild this exam!");
}
}
}
public delegate bool isFaild(Student myStudent);
class Program
{
static void Main(string[] args)
{
List<Student> studentsList = new List<Student>();
studentsList .Add(new Student { ID = 101, Name = "Rita", grade = 99 });
studentsList .Add(new Student { ID = 102, Name = "Mark", grade = 48 });
Student.failed(studentsList, std => std.grade < 60); // with Lamda
}
}
private static bool isFaildMethod(Student myStudent) // without Lambda
{
if (myStudent.grade < 60)
{
return true;
}
else
{
return false;
}
}
Trying to build a formatting delegate/function. It's mainly for printing exercise results.
I am trying to access the result of a argument but I think my understanding of delegates is still kind of bad. The method is invokable in the block itself but I would like the result, currently it prints the result definition.
System.Func2[ConsoleApp1.LoanQueries,System.Collections.Generic.IEnumerable1[System.Decimal]]
Below is the code that will create to result to parse, the parsing method and a code snippet that I based my code on.
My questions are:
Is this possible or am I breaking some rules?(trying to use expressions/functional)
Is it possible to declare just a delegate instead of the function(This would probably involve formatting every time instead of the function.)
Create data to format
// Method bodied expression
public IEnumerable<decimal> LoanQueryBodied =>
from amount in LoanAmounts
where amount % 2 == 0
orderby amount ascending
select amount;
// Query expression:
public IEnumerable<decimal> LoanQueryExpression () =>
LoanAmounts
.Where(a => a % 2 == 0)
.OrderBy(r => r);
Method for data and final formatting
public static void FormatLoans<TObject>(
Func<TObject> instance,
Func<TObject, IEnumerable<decimal>> function)
{
// This is the function object but should be IEnumerable<decimal> result passed down.
// Just like TObject is passed , but how?
Console.WriteLine(string.Join(" - ",function));
}
Use method
LoanQueries.FormatLoans<LoanQueries>(() =>
new LoanQueries()
, inst => inst.LoanQueryBodied);
LoanQueries.FormatLoans<LoanQueries>(() =>
new LoanQueries()
, inst => inst.LoanQueryExpression());
Code that I based it loosely on
public static class Disposable
{
public static TResult Using<TDisposable, TResult>(
Func<TDisposable> factory,
Func<TDisposable, TResult> map)
where TDisposable : IDisposable
{
using (var disposable = factory())
{
return map(disposable);
}
}
}
Example invoked
var time= Disposable
.Using(
() => new WebClient(),
client => XDocument.Parse(client.DownloadString("http://time.gov/actualtime.cgi")))
.Root
.Attribute("time")
.Value;
I would like to chain my method like this but if this is not possible or bad practice I would also like to know.
You need to call function and instance using ():
Console.WriteLine(string.Join(" - ",function(instance())));
And apparently you want to return the string, rather than printing it, to allow chaining, so:
public static string FormatLoans<TObject>(
Func<TObject> instance,
Func<TObject, IEnumerable<decimal>> function) =>
string.Join(" - ",function(instance()));
However, I think you are really over-complicating/over-generalising this. Your method is not nearly as general as the Disposable.Using method you showed. Your method could just be declared like this:
public static string FormatLoans(IEnumerable<decimal> loans) =>
string.Join(" - ", loans);
Callers:
LoanQueries.FormatLoans(new LoanQueries().LoanQueryBodied)
LoanQueries.FormatLoans(new LoanQueries().LoanQueryExpression)
Disposable.Using uses delegates because it is trying to recreate the using statement. The second argument must be evaluated inside the using statement, so that any exceptions thrown lead to the disposal of the IDisposable, which is why it has to be wrapped up in a delegate. If not, the second argument would be evaluated before the Using method runs, and that misses the whole point.
However, your method does not have special requirements like that, so you don't need delegates.
I'm a big fan of log4net and log4j's "format" API for logging messages, which avoids the cost of calling ToString() on arguments if the necessary log level is not enabled.
But there are times when one or more of the arguments I'd use is not a simple object, it needs to be constructed in some way. For example, like this:
logger.DebugFormat("Item {0} not found in {1}",
itemID,
string.Join(",", items.Select(i => <you get the idea>))
);
Is there a technique to encapsulate the second argument (the Join expression) such that it won't be executed unless DebugFormat decides that it should be (like it does for the ToString of the first argument)?
It feels like a lambda or func or something should be able to help here, but I'm fairly new to C# and I can't quite put my finger on it.
You can create extension method or wrapper class, but it's not easy to get satisfying syntax, because you want some parameters (itemID in your example) to be stated explicitly, and some to be resolved only if necessary. But you cannot pass anonymous function as object. Instead I'd use another solution which does not require extension methods or wrappers. Create class like this:
public sealed class Delayed {
private readonly Lazy<object> _lazy;
public Delayed(Func<object> func) {
_lazy = new Lazy<object>(func, false);
}
public override string ToString() {
var result = _lazy.Value;
return result != null ? result.ToString() : "";
}
}
This accepts function which returns object in constructor and will not call this function until ToString() is called, which as you know is called by log4net only if necessary (if such debugging level is enabled). Then use like this:
logger.DebugFormat("Item {0} not found in {1}",
itemID,
new Delayed(() => string.Join(",", items.Select(i => <you get the idea>)))
);
This is one of the hardest questions I've ever had to title here on SO. :) Although the title might not make sense, hopefully the question itself will.
Let's say I have a data structure like a Dictionary<string, List<double>>, and that I have functions that then take List<double>s as a parameter:
Dictionary<string, List<double>> candy_positions = new Dictionary<string, List<double>>();
candy_positions.Add( "Godiva", new List<double> { 1.0, 2.0, 4.0 });
EatCandy( candy_positions["Godiva"]);
...
But now I have decided that I don't want to do it this way. I want to replace my Dictionary with a List<CandyPositions>, where CandyPositions looks something like this:
public class CandyPositions
{
public double Sees;
public double Godiva;
public double Lindt;
}
However, I really would like to leave EatCandy() alone. Obviously, the problem is now that my data doesn't lend itself to be passed directly into the method. Instead, I have to do something lame like:
List<CandyPositions> candy_positions = new List<CandyPositions>();
...
var positions = from x in candy_positions select x.Godiva;
EatCandy( positions.ToList());
every time I want to call the method. I'd prefer to be able to do this in a more simple way, like:
EatCandy( candy_positions.GetPositionsFor( "Godiva"));
where the parameter "Godiva" matches the property name in the CandyPositions class.
After writing this question, I've realized that it isn't really about transposing data -- that part of it can be handled by writing an extension method. The part I don't know how to do is to pass in a property name, so that the extension method can take this and associate it with a class's property. I don't want to pass in a string, either, mainly because this will open the door for all sorts of runtime errors. I know how to make this work by passing "Godiva" to my extension method. What I really want to pass in is something akin to CandyPositions.Godiva instead.
This question is probably a little confusing, so in summary, I would accept the best of two types of answers:
Is there a better way to deal with transposing data, than to use an extension method + some way of accessing a property name?
Is there a way to specify the property that I want my extension method to retrieve, other than by a string?
My current extension method looks like this:
public static List<double> GetPositions( this List<CandyPositions> positions, string candy_name)
{
return (from x in positions select x.GetType().GetProperty(candy_name).GetValue(x, null)).Cast<double>().ToList();
}
Well, you could use:
public static List<double> GetPositions(this List<CandyPositions> positions,
Func<CandyPositions, double> projection)
{
return positions.Select(projection).ToList();
}
and call it with:
EatCandy(candyPositions.GetPositions(x => x.Godiva));
On the other hand, if you can change EatCandy to accept an IEnumerable<double> instead, you don't need the extra method - you can just use:
EatCandy(candyPositions.Select(x => x.Godiva));
without writing an extra method at all.
EDIT: If you need to iterate over two sequences at once, there are two options:
If you're using .NET 4, you can use the Zip extension method.
Otherwise, you can basically write your own:
using (var iterator1 = sequence1.GetEnumerator())
using (var iterator2 = sequence2.GetEnumerator())
{
while (iterator1.MoveNext() && iterator2.MoveNext())
{
var value1 = iterator1.Current;
var value2 = iterator2.Current;
// Use the values here
}
}
Can someone tell me the advantages of using a delegate as opposed to calling the function itself as shown below (or in other words why choose Option A over Option B)? I was looking at someone's linq code last night and they had something similar to Option A but it was being used to return a compiled linq query.
I realize the former can now be passed around to other functions.. just not sure of its practicality. BTW, I realize this wouldn't compile as-is.. uncommented one of the functions before posting. TYIA
class Program
{
static void Main(string[] args)
{
Console.WriteLine(SayTwoWords("Hello", "World"));
Console.ReadKey();
}
// Option A
private static Func<string, string, string>
SayTwoWords = (a, b) => String.Format("{0} {1}", a, b);
// Option B
private static string SayTwoWords(string a, string b)
{
return String.Format("{0} {1}", a, b);
}
}
************EDIT************
Not sure if it explains my question better but here is an example of the type of code that originally got me thinking about this:
public static class clsCompiledQuery
{
public static Func<DataContext, string, IQueryable<clsCustomerEntity>>
getCustomers = CompiledQuery.Compile((DataContext db, string strCustCode)
=> from objCustomer in db.GetTable<clsCustomerEntity>()
where objCustomer.CustomerCode == strCustCode
select objCustomer);
}
Is there any advantage to writing a function in this way?
There is no advantage in the code you posted. In your code, using the delegate just adds complexity as well as an extra runtime cost - so you're better off just calling the method directly.
However, delegates have many uses. "Passing around" to other methods is the primary usage, though storing a function and using it later is also very useful.
LINQ is built on top of this concept entirely. When you do:
var results = myCollection.Where(item => item == "Foo");
You're passing a delegate (defined as a lambda: item => item == "Foo") to the Where function in the LINQ libraries. This is what makes it work properly.
A very useful function of delegates is that you can send them wherever you want. It's like having your function everywhere you need it. A big use for this is event handling. Say you have a button, and when a user clicks this button you want any number of functions to be called. If you think about this there are a couple of ways you could do this:
You Could:
Call a function that calls each other function you want called.
This means that for each new function you want to be called, you must hard code it into this function. Very annoying.
OR
You could have a public list of the names of each function you want to call (delegates), and anyone can add or remove these functions at any time without the owner of the click event having to know or even do any work regarding any of them. When the click event happens, every event in the list is called and sent the same parameters, and you're done.
It's only useful if you have to pass the delegate around. If you can resolve the function at compile time, it's less useful.
With the static method you have to pass in all the variables needed.
With the delegate you could inline your implementation and have access to the variables in scope.
you can use delegates as "function pointers", so you can give the functions or "actions" to other functions to execute.
what also would be interesting with delegates is the possibility of "precompiling", like you "build" a new function and then return this function to your application
// Option A
private static Func<string, string, string>
SayTwoWords = (a, b) => String.Format("{0} {1}", a, b);
// Option B
private static string SayTwoWords(string a, string b)
{
return String.Format("{0} {1}", a, b);
}
In the above case, Option B is what I would go with, unless I need functionality of SayTwoWords to be changed. In the case of Option A, SayTwoWords can be assigned a different function. Catch more detailed differences in this answer:
There is a situation where Option A makes sense. Consider a case where you have to compile an expression to a delegate. Since compiling expression is heavy, that's something you would want to do it only once. A pattern like this helps:
public static class Cache<T>
{
public static readonly Func<T> Get = GetImpl();
static Func<T> GetImpl()
{
//build expression and return compiled delegate
}
}
instead of
public static class Cache<T>
{
public static T Get()
{
//build expression, compile delegate and invoke the delegate
}
}
In the first case when you call Get, GetImpl is executed only once, where as in the second case, (expensive) Get will be called every time.