Joel asked: Can your language do this?
secretGeek .:dot Nuts about dot Net:.
home .: about .: sign up .: sitemap .: secretGeek RSS

Joel asked: Can your language do this?

And he gave this example to illustrate his point:

function Cook( i1, i2, f )
{
    alert("get the " + i1);
    f(i1);
    f(i2);
}

Cook( "lobster",
    "water",
    function(x) { alert("put " + x + " in pot"); } );
Cook( "chicken",
    "coconut",
    function(x) { alert("boom boom the " + x); } );

Which outputs something like:

get the lobster
put lobster in pot
put water in pot

get the chicken
boom boom chicken
boom boom coconut.

Simple, yeh?

Now how would you go about doing this in C#?

I can't find a way to do it without defining a delegate first. Albeit, a generic delegate... but it's still not quite as 'elegant'.



private delegate void D<T>(T x);


Set up your cook function -- almost the same (except we use generic types, to mimic javascript's non-static typing.


private void Cook<T1>(T1 i1, T1 i2, D<T1>  f)

{

    MessageBox.Show("get the " + i1);

    f(i1);

    f(i2);

}


And then rather than passing in anonymous functions, we can pass in anonymous delegates...


Cook("lobster",

   "water",

   delegate(string x) { MessageBox.Show("put " + x + " in pot"); });

 

Cook("chicken",

    "coconut",

    delegate(string x) { MessageBox.Show("boom boom the " + x); });


Your turn. ;-)





'Josh' on Fri, 04 Aug 2006 04:42:18 GMT, sez:

I wonder how many people played with this after Joel's post :)

Two things though - Java is VERY statically typed. It's JavaScript that isn't and they're quite different.

Secondly, you can actually type your anonymous delegate on the fly, i.e.:

new D<string>(delegate(string s) {...

can be replaced with just

delegate(string s) provided the sigs match.

Keep up the great work.

Josh



'Wesner Moise' on Fri, 04 Aug 2006 04:58:06 GMT, sez:

C# syntax is nearly as compact as Javascript, save for typed parameters.

Some caveats:
1)Generics is not necessary at all
2)String concatenation works with any object (as long as one of the parameters is a string)
3)Anonymous delegates are implicitly cast to the right delegate type (so you never need to add a cast).

void Cook( object i1, object i2, Action(object) f )
{
alert("get the " + i1);
f(i1);
f(i2);
}

Cook( "lobster",
"water",
delegate(x) { MessageBox.Show("put " + x + " in pot"); } );
Cook( "chicken",
"coconut",
delegate(x) { MessageBox.Show("boom boom the " + x); } );

Alternatively, you can use a delegate and DynamicInvoke for latebinding:
void Cook( object i1, object i2, Delegate f )
{
alert("get the " + i1);
f.DynamicInvoke(i1);
f.DynamicInvoke(i2);
}



'Wesner Moise' on Fri, 04 Aug 2006 05:01:05 GMT, sez:

Some errors in my last post:
1) Use delegate(object x) { ... } since all parameters require a type.
2) alert needs to be replaced with MessageBox.Show()



'Christian' on Fri, 04 Aug 2006 05:26:52 GMT, sez:

Ruby can:

----
def Cook( i1, i2 )
puts "get the #{i1}"
yield(i1)
yield(i2)
end

Cook( "lobster", "water") { |x| puts("put #{x} in pot") }
Cook( "chicken", "coconut") { |x| puts("boom boom the #{x}") }
----



'lb' on Fri, 04 Aug 2006 10:49:25 GMT, sez:

@Josh, re "Java is VERY statically typed. It's JavaScript that isn't"

sorry Josh, just a typo on my part. fixed.

also @Josh:
I took out the "new D<string>(" bit... yes glad that works without it. I originally had it all quite a bit more over wrought again.

I'm growing to like the way the code looks now.

@wesner:
i originally had f.DynamicInvoke -- except i found i had to wrap the args in an object array -- something like

f.DynamicInvoke(new object[]() = {i1});

how yucky is that?

re:"alert needs to be replaced with MessageBox.Show()"

...or abstracted out:

private void alert(string s) {
MessageBox.Show(s)
}

;-)

@christian: yes yes, we all know ruby is beautifully elegant. Thank you for sharing though -- i was pretty keen to find the ruby syntax for this kind of activity. whenever i see the |x| type syntax i think of 'why the lucky stiff' describing it as a little tube that the parameter slides down on its way into the block...

cheers
lb



'WaterBreath' on Fri, 04 Aug 2006 16:20:33 GMT, sez:

@Christian and lb: I actually would not describe the Ruby syntax as particularly elegant, though it is certainly concise. The reason I would not use the word "elegant" is that although the syntax is very compact, it seems not very mathematical.

The reason I say this is that the anonymous function (called by the "yield" keyword) doesn't quite appear and work like a normal function argument, for two reasons: 1) it has it's own place, outside the argument list and 2) you need a special (and ambiguous) keyword to reference it. (I say it's ambiguous because the first time I saw "yield", I assumed it meant the same thing as "return". Though I understand now that it references the current method "yielding control" to the other block.)

Then there's the fact that the Pragmatic guys, in "Programming Ruby" say it should not be thought of as an argument:

"Some people like to think of the association of a block with a method as a kind of parameter passing. This works on one level, but it isn't really the whole story. You might be better off thinking of the block and the method as coroutines, which transfer control back and forth between themselves."
(found here: http://www.rubycentral.com/book/intro.html)

And if it's not intended to work like a parameter, then it really is not-mathematical. Convenient, yes. Concise, yes. But IMHO it's no more elegant than the slightly more verbose but mathematical C# syntax Mr. Moise posted.



'J' on Fri, 04 Aug 2006 16:50:34 GMT, sez:

Just an FYI. They are not called anonymous delegates. The proper terminology is anonymous methods. The methods are anonymous, not the delegate.



'J' on Fri, 04 Aug 2006 17:09:07 GMT, sez:

Sorry, let me correct what I stated... They are not anonymous delegates. (Obviously it appears people call them what they are not.)



'mike' on Fri, 04 Aug 2006 19:41:32 GMT, sez:

Nikhil took this one on, too:

http://www.nikhilk.net/Entry.aspx?id=137



'Sun Digging Deep for Dynamic Language Support' on Tue, 08 Aug 2006 02:51:40 GMT, sez:

Java ('s virtual machine) isn't always going to be so VERY "statically" typed !!



'ks' on Wed, 09 Aug 2006 02:35:00 GMT, sez:

The powershell answer to this is even better!!

basically anything in "{}" is an anonymous method already (a block actually) -- (provided it's not preceeded by a function name and brackets.)

PS> Function Cook ($i1, $i2, $f)
>> { Alert "Get the $i1"
>> &$f $i1
>> &$f $i2
>> }
PS> Cook Lobster Water {Param($x) Alert "Pot $x"}
Get the Lobster
Pot Lobster
Pot Water
PS> Cook Chicken Coconut {Param($x) Alert "Boom $x"}
Get the Chicken
Boom Chicken
Boom Coconut



'DOA' on Tue, 29 Aug 2006 11:18:58 GMT, sez:

PHP can do it. Who knew....




name


website (optional)


enter the word:
 

comment (HTML not allowed)


All viewpoints welcome. But the right to delete any post for any reason is reserved. Don't make me do it. Comments may be republished, emailed to your loved ones or printed and used as toilet paper. Who reads this legal bit anyhow?

TimeSnapper is a life analysis system that stores and plays-back your computer use. It makes timesheet recording a breeze, helps you recover lost work and shows you how to sharpen your act.

TimeSnapper won last year's Developer Competition at Larkware.com, and is used by over 10,000 people.

Articles

The Movie Hollywood (And My Wife) Doesn't Want You To See: Weekend at Jacko's The Movie Hollywood (And My Wife) Doesn't Want You To See: Weekend at Jacko's
Sysi: the ultimate administrators toolkit Sysi: the ultimate administrators toolkit
Movie: Priest Academy Movie: Priest Academy
Inspirational Rat Story Inspirational Rat Story
A face-melting DSL that allows programming ON the iPhone (and iPad) A face-melting DSL that allows programming ON the iPhone (and iPad)
The secretGeek Disaster Recovery plan The secretGeek Disaster Recovery plan
Save KNVTn! Before it's too late Save KNVTn! Before it's too late
The Ultimate Agent of WERF Destruction The Ultimate Agent of WERF Destruction
The new prisoner's dilemma The new prisoner's dilemma
Original Premise for a road movie Original Premise for a road movie
What's a better game than Devshop? What's a better game than Devshop?
DevShop: The Cool Game that Makes Development Look Fun DevShop: The Cool Game that Makes Development Look Fun
Should be purple Should be purple
Kitchen Agile Kitchen Agile
Perhaps Perhaps "Go" is the new Visual Basic
zen-coding: turn those CSS selectors upside down zen-coding: turn those CSS selectors upside down
Debugging: It's all about finding Albuquerque. Debugging: It's all about finding Albuquerque.
The Real-Time online JQuery Editor The Real-Time online JQuery Editor
HTML5, a 3 minute guide HTML5, a 3 minute guide
Developer Codpieces Developer Codpieces
Agile for one: The Personal Story 'Wall' In Action Agile for one: The Personal Story 'Wall' In Action
Never work with thick people. Never work with thick people.
Cosmo: project status panel Cosmo: project status panel
Windows Search in Japan Windows Search in Japan
Project Management Zen Project Management Zen
Continuous Integration, Plugins and Going Too Far Continuous Integration, Plugins and Going Too Far
The Rules of Stand Up The Rules of Stand Up
Sydney International Airport: Stupid, Criminal, or Criminally Stupid? Sydney International Airport: Stupid, Criminal, or Criminally Stupid?
God No! ...The ReBuilder God No! ...The ReBuilder
Matt, The Office Mortar Matt, The Office Mortar
'Outlook style' rules for Subversion 'Outlook style' rules for Subversion
Really deep linking: Url + regex Really deep linking: Url + regex
hExcel -- A Hexagonal Spreadsheet hExcel -- A Hexagonal Spreadsheet
Is the remote control a thing of the past? Is the remote control a thing of the past?
The Utterly Thorough Guide To Awesome Application Compatibility on Windows 7. The Utterly Thorough Guide To Awesome Application Compatibility on Windows 7.
Astounding Hyperlinked Noticeboard Astounding Hyperlinked Noticeboard
Three Questions About Each Bug You Find Three Questions About Each Bug You Find
Recursing over the Pareto Principle... Recursing over the Pareto Principle...
Sometimes, The Better You Program, The Worse You Communicate. Sometimes, The Better You Program, The Worse You Communicate.

Archives .: secretGeek :: Complete Archives
TimeSnapper -- Automated Screenshot Journal TimeSnapper.com    
Version 3.3: true productivity boost

Next Action NextAction
Managing the top of your mind

World's Simplest Code Generator (html edition) World's Simplest Code Generator

25 steps for building a Micro-ISV 25 steps for building a Micro-ISV
3 minute guides -- babysteps in new technologies: powershell, JSON, watir, F# 3 Minute Guide Series
Universal Troubleshooting checklist Universal Troubleshooting Checklist
Top 10 SecretGeek articles Top 10 SecretGeek articles
ShinyPower (help with Powershell) ShinyPower
Now at CodePlex

Realtime CSS Editor, in a browser RealTime Online CSS Editor
Gradient Maker -- a tool for making background images that blend from one colour to another. Forget photoshop, this is the bomb. Gradient Maker


[powered by Google] 


How to be depressed How to be depressed
You are not inadequate.



Recommended Reading

The Best Software Writing I
The Business Of Software (Eric Sink)

Recommended blogs

Jeff Atwood
Reginald Braithwaite
Joseph Cooney
Phil Haack
Scott Hanselman
Julia Lerman
Rhys Parry
Joel Pobar
OJ Reeves
Eric Sink
Joel Spolsky
Des Traynor

Aggregated Links

programming.reddit.com
dzone
dot net kicks

Human Link Machines

interesting finds
a continuous learner's weblog
arjan's world
n links today
new and notable
morning coffee
learning .net
weekly link post
(my del.icio.us account)

LinkedIn profile
 
home .: about .: sign up .: sitemap .: secretGeek RSS .: © Leon Bambrick 2006 .: privacy

home .: about .: sign up .: sitemap .: RSS .: © Leon Bambrick 2006 .: privacy