471,321 Members | 1,768 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,321 software developers and data experts.

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 1814
On Aug 11, 11:24*pm, Ben <B...@discussions.microsoft.comwrote:
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*@discussions.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 CompareIgnoreCase(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<string>(myStringArray, CompareIgnoreCase);
Or using an anonymous method:

Array.Sort<string>(myStringArray, delegate(string x, string y) { return
string.Compare(x, y, true); } );

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

Array.Sort<string>(myStringArray, (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<stringGetComparer(bool 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<string>(myStringArray, GetComparer(true));

You can of course call the delegate directly also:

int result = GetComparer(true)("Peter", "Paul");

Or store it in a variable, and call it:

Comparison<stringcomp = GetComparer(true);
int result = comp("Jack", "Jill");

--
Göran Andersson
_____
http://www.guffa.com
Aug 11 '08 #4
On Aug 11, 10:24*pm, Ben <B...@discussions.microsoft.comwrote:
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<stringGetComparison(bool returnAnonymous) {
if (returnAnonymous) {
// 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...@discussions.microsoft.comwrote:
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
On Wed, 13 Aug 2008 03:53:02 -0700, Ben <Be*@discussions.microsoft.com>
wrote:
Yes, you're right Goran. Since C# 2.0 we can have both anonymous methods
and
delegates as return values of methods,
No, not really. Anonymous methods and delegates are two different
things. A delegate is a type. An anonymous method is just that: a method
without a name.

Warning: pedantry coming up. But it's important pedantry, IMHO.

Strictly speaking, your statement is correct. But only because you seem
to be using the phrase "return values" where you really mean "return
type". Inferring that you really mean "return type" (that is, the type of
the return value for a method), then only a delegate can be used as a
"return type of methods". A method, anonymous or names, isn't a type and
so can't be used as a type.

Conversely, if I take your statement literally, then sure...you can have
an anonymous method as a return value as well as a delegate. But they
can't be used interchangeably. An anonymous method returned from a method
would be returned as a delegate type, but a delegate returned from a
method would be returned as a Type type.

Why am I making this distinction? Because IMHO it's very important to
understand the difference between a type (delegate) and an instance of a
type (anonymous method). You wouldn't write "we can have both integer
literals and ints as return types of methods", would you?

Now, I realize that's not really the question you were asking. But it
seems to me that it's important to get the terminology straight first.
Otherwise, we might be trying to talk about some topic with each other and
completely fail to understand each other.

Bringing it back full circle, you can only have a delegate as a return
type for a method. It's true that you can instantiate the delegate with
an anonymous method, but that's not really any different from
instantiating it with a named method. The important thing here is the
returning of a delegate.

So, as far as your actual question goes...
[...] 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?
Just FYI, there are a number of languages for which "returning
functionality" is essentially the main paradigm. That is, the language is
based primarily or entirely on the concept of functionality as a type.
Realizing that, hopefully that illustrates that even if one cannot
immediately see the use, you can in fact write entire programs around the
idea.

As for how it's useful in C#, I would say that it's not something that
comes up a lot. But when it does come up, it's likely to be the most
elegant way to do something.

Jon provides some abstract suggestions as to when you might want to use
it, plus one pretty esoteric concrete example (he's trying to improve a
reflection-based implementation by calling methods through the faster
delegate-based mechanism). :) Here's something that might be a little
more "real-world" (or at the very least, maybe easier to understand):

delegate object IntOperator(int i1, int i2);

Operator GetIntOperator(char chOperator)
{
switch (chOperator)
{
case '+':
return (x, y) =x + y;
case '-':
return (x, y) =x - y;
case '*':
return (x, y) =x * y;
case '/':
return (x, y) =x / y;
}

return null;
}

So, then some code parsing textual representations of expressions could
use the GetOperator() method to get an implementation of an operator based
on some character input. (This isn't necessarily the _best_ way to
implement an interpreter, but then the example would work so well
otherwise :) ).

Lamba expressions especially, but even anonymous methods, provide a nice
paradigm for representing some functional logic that you want to pass
around for use later. It can be very expressive, as compared to a more
imperative way of writing the program.

Pete
Aug 13 '08 #11
On Aug 13, 5:09*pm, Ben <B...@discussions.microsoft.comwrote:
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.
Cool. Just be prepared to slow down when there are too many levels of
indirection. It's an evil piece of code - fun, but evil.
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? :)
You're very kind. As for knowing stuff, I think I manage to make look
like I know more than I actually do, just by going into about as much
depth as I'm confident in. Anyone who's read everything I've written
probably knows more than I do :)

When it comes to making hard things look simple - I'm glad you think
I'm successful on that front. I'm still annoyed at how hard it seems
to be to explain the differences between value types and reference
types, and a few other bits and pieces. Delegates are another tricky
topic - and don't get me started on C# 3 type inference (lovely though
it is). We can always do better...

If you're in the market for a new favourite author, you should try
Josh Bloch's "Effective Java" (2nd edition) - even if you only use C#,
vast swathes of it is applicable to C#, and it's exquisitely written.

Jon
Aug 13 '08 #12
Jon Skeet [C# MVP] wrote:
If you
think of a delegate type as being like a single-method interface, that
may help.
Coincidentally, I've implemented anonymous functions in the upcoming
release of the Delphi compiler using exactly that - single method
interfaces behind the scenes :)

-- Barry

--
http://barrkel.blogspot.com/
Aug 13 '08 #13
Is it just me or do others feel too that their post becomes irrelevant when
it's no longer on the first page? :)

Anyways, I absolutely agree with you that terminology is of utmost
importance, and I admit that I did mess things up a little bit in this regard
:)

Regarding your example, I think it is quite good actually in illustrating
the point of having "mobile" functionality :)

Thanks,
Ben

Aug 13 '08 #14
On Wed, 13 Aug 2008 11:08:10 -0700, Ben <Be*@discussions.microsoft.com>
wrote:
Is it just me or do others feel too that their post becomes irrelevant
when
it's no longer on the first page? :)
Well, at most it's others who are also using Microsoft's web portal to
this newsgroup. Most of us are using more traditional means to read the
newsgroup. Mostly regular newsreaders, with the occasional person using
the Google Groups newsgroup interface.
Anyways, I absolutely agree with you that terminology is of utmost
importance, and I admit that I did mess things up a little bit in this
regard
:)

Regarding your example, I think it is quite good actually in illustrating
the point of having "mobile" functionality :)
Oh, good...glad it helped!

Pete
Aug 13 '08 #15

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

99 posts views Thread by David MacQuigg | last post: by
7 posts views Thread by BlueDragon | last post: by
2 posts views Thread by Bryan Olson | last post: by
13 posts views Thread by agentxx04 | last post: by
9 posts views Thread by Mikhail Teterin | last post: by
14 posts views Thread by Kejpa | last post: by
9 posts views Thread by Gabriel Rossetti | last post: by
reply views Thread by rosydwin | last post: by

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.