Functions as return values

  • Thread starter Thread starter Ben
  • Start date Start date
B

Ben

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
 
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
 
Ben said:
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<string> GetComparer(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<string> comp = GetComparer(true);
int result = comp("Jack", "Jill");
 
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.
 
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
 
Ben said:
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<string> GetComparison(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);
}
 
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
 
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/a...g-reflection-fly-and-exploring-delegates.aspx

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

Jon
 
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? :)
 
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
 
Jon said:
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
 
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top