473,698 Members | 1,967 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Functions as return values

Hi all,
I'm trying to understand the concept of returning functions from the
enclosing functions. This idea is new to me and I don't understand when and
why I would need to use it.
Can someone please shed some light on this subject?

Thanks a lot,

Ben
Aug 11 '08 #1
14 2017
On Aug 11, 11:24*pm, Ben <B...@discussio ns.microsoft.co mwrote:
Hi all,
I'm trying to understand the concept of returning functions from the
enclosing functions. This idea is new to me and I don't understand when and
why I would need to use it.
Can someone please shed some light on this subject?

Thanks a lot,

Ben
"returning functions from the enclosing functions"

Ummm... Which concept you are talking about???

-Cnu
Aug 11 '08 #2
On Mon, 11 Aug 2008 11:24:08 -0700, Ben <Be*@discussion s.microsoft.com >
wrote:
Hi all,
I'm trying to understand the concept of returning functions from the
enclosing functions. This idea is new to me and I don't understand when
and
why I would need to use it.
Can someone please shed some light on this subject?
Do you mean "anonymous methods"? If so, that's a sub-set of a broader
topic related to delegate types.

The anonymous methods themselves are, IMHO, useful because they allow
implementation details to remain close to where they are used, and can
even avoid the need to define a new class for the purpose holding data
specific to the implementation (see "variable capturing"). But much of
the usefulness is just the same as for delegates generally.

Jon Skeet has a nice article on delegates generally here:
http://yoda.arachsys.com/csharp/events.html

He's also written an article on "closures" that discusses the concept,
albeit in the context of lambda expressions (which can be used in ways
similar to anonymous methods). Here's a link to that:
http://csharpindepth.com/Articles/Ch.../Closures.aspx

It's difficult in the context of a newsgroup to provide a complete
discussion that answers a question as broad as yours. Hopefully the above
links will help. If you have more specific questions remaining after
reading those articles, please feel free to post those here and we can try
to elaborate.

If the above doesn't seem to be addressing your question, then maybe you
can be more specific about what you're asking. The phrase "concept of
returning functions from the enclosing functions" doesn't literally
describe anything in C# at all, so I've made some inferences regarding
what you really mean. If I've made an incorrect assumption, you may want
to try to rephrase your question in a more specific way (including code
examples if necessary).

Pete
Aug 11 '08 #3
Ben wrote:
Hi all,
I'm trying to understand the concept of returning functions from the
enclosing functions. This idea is new to me and I don't understand when and
why I would need to use it.
Can someone please shed some light on this subject?

Thanks a lot,

Ben
What you would actually return from the method would be a delegate.

Returning delegates from a method is not so common, but a delegate is a
type that can be used for the return value just like any other type.
Delegates are most commonly used by events, but they are also used in
other ways. The Array.Sort method for example has some overloads that
takes delegates, which is used to compare the items when they are sorted.

You can make a method that compares two strings in a special way:

public static int CompareIgnoreCa se(string x, string y) {
return string.Compare( x, y, true);
}

Then you can use the name of the method to send a delegate to the Sort
method:

Array.Sort<stri ng>(myStringArr ay, CompareIgnoreCa se);
Or using an anonymous method:

Array.Sort<stri ng>(myStringArr ay, delegate(string x, string y) { return
string.Compare( x, y, true); } );

Or even a lambda expression if you are using C# 3:

Array.Sort<stri ng>(myStringArr ay, (x, y) =string.Compare (x, y, true));
To expand this in the direction of your original question, you could
have a method that returns different delegates depending on how you want
to sort:

public static Comparison<stri ngGetComparer(b ool ignoreCase) {
if (ignoreCase) {
return delegate(string x, string y) {
return string.Compare( x, y, true);
};
} else {
return delegate(string x, string y) {
return string.Compare( x, y);
};
}
}

Calling the method would return a delegate, which you then can use in
the call to the Sort method:

Array.Sort<stri ng>(myStringArr ay, GetComparer(tru e));

You can of course call the delegate directly also:

int result = GetComparer(tru e)("Peter", "Paul");

Or store it in a variable, and call it:

Comparison<stri ngcomp = GetComparer(tru e);
int result = comp("Jack", "Jill");

--
Göran Andersson
_____
http://www.guffa.com
Aug 11 '08 #4
On Aug 11, 10:24*pm, Ben <B...@discussio ns.microsoft.co mwrote:
Hi all,
I'm trying to understand the concept of returning functions from the
enclosing functions. This idea is new to me and I don't understand when and
why I would need to use it.
Can someone please shed some light on this subject?
First of all, I would recommend to read the Wikipedia article on
closures:

http://en.wikipedia.org/wiki/Closure_(computer_science)

While it doesn't have any C# examples, it does have some JavaScript
ones (oh, the pains I had to go through to put them there together
with Scheme in spite of people claiming that JS closures are not
"pure"...), which is reasonably close, and hopefully understandable
enough. The article does have some examples of functions returning
functions.

As for the more practical usage - for example, you can use such a
pattern when you have several controls which have mostly similar, but
yet subtly different event handlers (particularly so when the
difference is in signatures, return types, or types of local
variables). In this case, it makes sense to have a factory method that
can generate and return various versions of the same event handler,
using anonymous delegate.
Aug 11 '08 #5
Thank you all for the kind replies,

and sorry for the confusion. Yes, what I meant was returning anonymous methods
as return values of methods (which is done in .net using delegates).
I will take a look at the various links that you guys have kindly provided and
hopefully I will have a better grasp of this whole closure subject.

Thanks again for everyone,

Ben
Aug 12 '08 #6
Ben wrote:
Thank you all for the kind replies,

and sorry for the confusion. Yes, what I meant was returning anonymous methods
as return values of methods (which is done in .net using delegates).
I will take a look at the various links that you guys have kindly provided and
hopefully I will have a better grasp of this whole closure subject.

Thanks again for everyone,

Ben
Do you mean the specific case of returning an anonymous method as a
delegate, or returning a delegate in general? To return a delegate from
a method it doesn't have to come from an anonymous method.

Example:

public static Comparison<stri ngGetComparison (bool returnAnonymous ) {
if (returnAnonymou s) {
// this returns an anonymous method as a delegate:
return delegate(string x, string y) { return string.Compare( x, y) };
} else {
// this returns a named method as a delegate:
return CompareStrings;
}
}

public static int CompareStrings( string x, string y) {
return string.Compare( x, y);
}

--
Göran Andersson
_____
http://www.guffa.com
Aug 12 '08 #7
Yes, you're right Goran. Since C# 2.0 we can have both anonymous methods and
delegates as return values of methods, and we might see more developers using
anonymous methods/lambdas because C# 2.0/3.0 allows it.
What I meant was returning a delegate in general. It's just that we are now
starting to see this kind of way of programming more and more because the
language offers some additional stuff like closures, but my question id
really simple (and kind of silly, i know :)). I can understand when a method
returns an int, a class, an array etc. but a function? I don't get this
simple idea of returning functionality :) When would I want to return
functionality?

Thanks again,

Ben
Aug 13 '08 #8
On Aug 13, 11:53*am, Ben <B...@discussio ns.microsoft.co mwrote:
Yes, you're right Goran. Since C# 2.0 we can have both anonymous methods and
delegates as return values of methods, and we might see more developers using
anonymous methods/lambdas because C# 2.0/3.0 allows it.
What I meant was returning a delegate in general. It's just that we are now
starting to see this kind of way of programming more and more because the
language offers some additional stuff like closures, but my question id
really simple (and kind of silly, i know :)). I can understand when a method
returns an int, a class, an array etc. but a function? I don't get this
simple idea of returning functionality :) When would I want to return
functionality?
One use is to defer execution of something. "Give me something I can
call at a later date to open the relevant file" or "Give me something
I can call at any time to compare items in an appropriate way". If you
think of a delegate type as being like a single-method interface, that
may help.

Another use I've recently blogged about is improving the performance
of reflection: you can (with care) create delegates from MethodInfo
objects:
http://msmvps.com/blogs/jon_skeet/ar...delegates.aspx

(Warning: there's some hairy stuff in there.)

Jon
Aug 13 '08 #9
Jon,

Thank you very much for your reply.
The tip about thinking of delegates as being like single method interfaces
was great. And I'm gonna take a look at the link you provided.

P.S.
You're one of my favorite authors, right up there with Jeffrey Richter and
Andrew Troelsen (You can make hard stuff look simple and not the other way
around). How do you know all this stuff? :)
Aug 13 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

99
5890
by: David MacQuigg | last post by:
I'm not getting any feedback on the most important benefit in my proposed "Ideas for Python 3" thread - the unification of methods and functions. Perhaps it was buried among too many other less important changes, so in this thread I would like to focus on that issue alone. I have edited the Proposed Syntax example below to take out the changes unecessary to this discussion. I left in the change of "instance variable" syntax (...
7
2264
by: BlueDragon | last post by:
The place where I work is moving to MS SQL Server from Lotus Notes. I have done a lot of coding in Lotus Notes, and have, I suppose, intermediate skills in basic SQL -- queries, insert, updates, table design, etc. I have a couple of questions, however. First, stored procedures vs. functions. In my world, a function is a body of code that returns a value; a procedure is a body of code that does things but does not return a value (other than...
2
3786
by: Bryan Olson | last post by:
The current Python standard library provides two cryptographic hash functions: MD5 and SHA-1 . The authors of MD5 originally stated: It is conjectured that it is computationally infeasible to produce two messages having the same message digest. That conjecture is false, as demonstrated by Wang, Feng, Lai and Yu in 2004 . Just recently, Wang, Yu, and Lin showed a short- cut solution for finding collisions in SHA-1 . Their result
8
2965
by: silly | last post by:
/* hello, I have some fairly naive queries here related to optimising code! I know the first answer is 'don't' but leave that to one side for the moment. 1) I'm looking for constructive comments on the mul_a() and pow_a() below comments on style/clarity/portability/obvious efficiency issues are welcome - any better ways to write them without changing the algorithm. 2) Comments on mul_b() and pow_b() below which attempt to optimise them.
13
2196
by: agentxx04 | last post by:
Hi. Our assignment was to creat a program that can find the average, median & mode of a #of integers. Here's my program: #include<stdio.h> int main() { int item; int a, b, t, mode; int median_index;
9
5061
by: Mikhail Teterin | last post by:
Hello! I'd like to have a variable of a pointer-to-function type. The two possible values are of type (*)(FILE *) and (*)(void *). For example: getter = straight ? fgetc : gzgetc; nextchar = getter(file); What type should I give to `getter' so that the compiler does not issue
14
1417
by: Kejpa | last post by:
Hi, I have a function Sum as.... Function Sum(ByVal ParamArray Values() As Double) As Double Dim rSum, itm As Double For Each itm In Values rSum += itm Next Return rSum End Function
1
19399
MMcCarthy
by: MMcCarthy | last post by:
Access has a number of built-in functions which can be generally used in queries or VBA code. Some of the more common ones are: Note: anything in square brackets is optional Date Functions Date() - Returns the current system date Now() - Returns the current system timestamp (date and time)
0
16496
yasirmturk
by: yasirmturk | last post by:
Standard Date and Time Functions The essential date and time functions that every SQL Server database should have to ensure that you can easily manipulate dates and times without the need for any formatting considerations at all. They are simple, easy, and brief and you should use them any time you need to incorporate any date literals or date math in your T-SQL code. create function DateOnly(@DateTime DateTime) -- Returns @DateTime...
9
3987
by: Gabriel Rossetti | last post by:
Hello, I can't get getattr() to return nested functions, I tried this : .... def titi(): .... pass .... f = getattr(toto, "titi") .... print str(f) .... Traceback (most recent call last):
0
8600
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9155
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8890
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7711
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4360
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4614
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3038
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2322
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.