January 28, 2012

Action, Func, void and unit

The .NET Framework defines two ‘standard’ delegate types: Action<> and Func<>.  The Func types are used for delegates that return values, and the Action types for those that don’t – in C# terms, for void methods.

This distinction can often be very annoying.  Consider a helper method such as:

public static T WithSomeResource<T>(Func<T> f) {
  AcquireSomeResource();
  try {
    return f();
  } finally {
    ReleaseSomeResource();
  }
}

This works fine when the thing you want to do returns a value:

int y = Helpers.WithSomeResource(() => x + 1);

But the compiler won’t let you pass anything that doesn’t return a value:

Helpers.WithSomeResource(() => Console.WriteLine(x));  // error

You have to create a separate overload that takes an Action instead of a Func, and has an identical implementation except for omitting the return keyword.  Granted, that’s not much work for a simple helper like the above, but what if it were more complicated?  Or what if you had a dozen of them?  Boring!  Also, maintenance nightmare!

The reason for this distinction is that although void sits in the position where you expect the return type to sit, and looks like a return type, it isn’t.  Visual Basic makes this much clearer by distinguishing between Sub and Function instead of abusing the return type identifier.  So in the WithSomeResource generic method, the type parameter T can’t be void, because void isn’t a type.  And so we end up needing the separate Action types, which do the job of Func<void>.

Contrast this with F#.  F# doesn’t have void: it has unit.  This may seem like it’s just a difference in naming, but it isn’t, because unit in F# is a real type.  A function that ‘doesn’t return a value’ in F# is considered to return type unit.

let f (s : string) = Console.WriteLine(s);; 
val f : string –> unit

So in F#, every function has a return type.  And therefore F# doesn’t need to distinguish between functions and actions.

let withSomeResource f = 
  acquireSomeResource() 
  try 
    f() 
  finally 
    releaseSomeResource();;
val withSomeResource : (unit –> 'a) –> 'a

The F# version of withSomeResource can be called interchangeably with ‘functions’ (that return real values) and ‘actions’ (that return unit) because unit is a valid type, and so the type parameter 'a can be unit just like any other type.

let y = withSomeResource (fun () –> x + 1);;  // okay 
withSomeResource(fun () –> Console.WriteLine(x));;  // also okay

Having unit instead of void makes it easier to write generic functions, because you don’t need to write separate implementations for the ‘value’ and ‘no value’ cases.

And that, my liege, is how we know the earth to be banana shaped.

January 28, 2012 in Software | Permalink | Comments (3) | TrackBack (0)

January 25, 2012

Wellington .NET user group - Windows 8 for .NET developers

Thanks to everyone who came along this evening to watch me trying to get a wireless connection to work, and especially to those who stuck around for the Windows 8 talk afterwards. Here are the slides from the session, which in a rare departure for me actually contain the content of the talk instead of a series of gnomic Talking Heads references. Enjoy!

Windows 8 presentation slides

And although we didn't really have time to look at samples, you can get source code for the Metro sample apps I used here.

January 25, 2012 in Software | Permalink | Comments (0) | TrackBack (0)

October 15, 2011

A tale of two elections

New Zealand is ramping up to an election. It’s pretty much a foregone conclusion that the National party will win; the only question is whether National will win enough votes to govern alone, or whether they’ll need the support of a minor party.  This is somewhat reminiscent of the situation in the last UK election, in which the question was not whether the Tories would get the most votes, but whether there would be a hung parliament.  But it’s interesting to compare attitudes in the two countries.

In the UK, absolute majorities are the norm. The voting system is designed to produce absolute majorities from voting pluralities, and a referendum on a change that would have mitigated this was recently defeated.  Voters are taught that governments need to be ‘strong’ so that they can enact all their policies.

In short, for one party to have an absolute majority to do with as it wishes is regarded as essential to effective government.

By contrast, I asked a friend what he thought of the possibility of National winning an absolute majority.  He wasn’t keen on the possibility.  Part of this was specific to National’s style of government – their routine use of urgency – but part of it also seemed to be a feeling that parties should not go unchecked.  No party should be free to just do what it wants without building at least some measure of consensus.  (To be clear, the friend in question is not anti-National.  I don’t know his voting intentions, but I’m pretty sure he won’t be shedding any tears over National getting a second term.  His concern was specifically about National winning an absolute majority.)

In short, for one party to have an absolute majority to do with as it wishes is regarded as not only inessential to effective government, but actively worrying in terms of keeping government in check.

It’s obviously invalid to extrapolate from one conversation with one person, and it’s certainly true that there are many people in New Zealand who do long for the jackboot of unchecked government (as long as it is their party wearing it, of course).  Still, I’d like to think it illustrates how Kiwis have in the last 15 years come to take consensus for granted as an expected and desirable outcome of an election, in contrast to Britons actively preferring absolutism.

Of course, the MMP referendum could be about to prove me wrong…

October 15, 2011 in Current Affairs | Permalink | Comments (0) | TrackBack (0)

September 03, 2011

Fortunately, we can save ourselves by leaving the lights on while we’re not using them

Stuff: “In a speech to ACT party faithful in Auckland today at its annual conference, new leader [Don] Brash delivered the keynote speech saying the country was in the grip of an emergency so bad New Zealand ‘faces serious threats to its continued existence.’”

Wake up, people!  He’s talking about Genghis Khan!

September 3, 2011 in Current Affairs | Permalink | Comments (0) | TrackBack (0)

September 01, 2011

Dynamic interfaces in C#

The always creative Bevan Arps demonstrates a neat prototype which uses the C# dynamic keyword to provide a concise and readable way of describing validations within C# code, and asks, “Does this qualify as evil code, or merely expressive?”

Well, it’s clearly expressive.  And languages like Ruby use this kind of idiom all the time, so it’s clearly not evil.  But there is something about it (and about some related code I demoed at TechEd) which might reasonably make you feel a bit doubtful.  It’s not evil per se, but is it un-C#-ish?  C# is traditionally a statically typed language, which encourages reliance on the compiler to check correctness: are Ruby-ish idioms simply inappropriate?

Idioms evolve with the language; or, rather, what is idiomatic develops from what people do with language features.  Take C# anonymous types.  They were initially designed to simplify writing LINQ projections, with the expectation that the results would be consumed in the same method where the anonymous type arose.  Maybe you could data-bind to them if you felt adventurous.  Then somebody realised that anonymous types made a really handy syntax for a set of key-value pairs – basically a dictionary, but without all the tedious overhead of C# dictionary literals.  An idiom was born: anonymous types are now firmly established as the C# equivalent of Ruby hashes.

So it is with dynamic.  ASP.NET MVC 3 uses a dynamic ViewBag to shield developers from the rather mild horrors of dictionary access syntax.  Libraries like Dapper, which uses dynamic properties to sweeten what would otherwise be a .NET 1.0 DataTable, are entering the vocabulary of the C# community.  People like Bevan are finding cases where dynamic interfaces enable them to write shorter, cleaner and more expressive code.  It may be unsafe, sure, but typically no more unsafe than the literal strings it often replaces.

Right now, using dynamic interfaces in C# does feel a bit weird.  And there’s no doubt that most C# code and APIs will remain statically typed and compiler verified.  But dynamic interfaces are clearly becoming part of the idiom: the question is not whether dynamic interfaces belong in C#, but where they belong and how much we should use them.

September 1, 2011 in Software | Permalink | Comments (0) | TrackBack (0)

August 28, 2011

But it has angle brackets!

Pro tip: describing a technique as “all XSLT, no code” makes about much sense as describing it as “all SQL, no code.”

August 28, 2011 in Software | Permalink | Comments (2) | TrackBack (0)

August 27, 2011

TechEd NZ 2011 demos and videos

Thanks to everyone who came along to my sessions on F# and dynamic programming. Here's the demo code from the talks. It includes a few fragments that go beyond what I covered in the talk -- I've tried to comment these to give you a few pointers as to what they're showing, but if you're still baffled, leave a comment and I'll try to write up what's going on!

Demos for F# talk

Demos for dynamic talk

It looks like the videos are now up for those who just can't get enough rude remarks about EF -- F# here, dynamic here.

August 27, 2011 in Software | Permalink | Comments (0) | TrackBack (0)

August 07, 2011

Random links

Just clearing out a few links.

Got Medieval: '”[The] image is taken from the British Library’s inexhaustibly weird MS Royal 10 E IV, a manuscript illuminated – as near as I can tell – by a homicidal nutjob.”  In a context where cats wield longbows and mice use catapults, this is high praise indeed.

Starts With A Bang collects some gobsmackingly beautiful pictures of exploding stars.

Doctor Who geek persuades his wife to watch the entire run of the show with him, chronicles her bafflement, boredom, bon mots and occasional bouts of enthusiasm, skirts divorce (via Sarah Proud and Tall).  Notable if only for introducing me to the term ‘ming-mong.’

No doubt this will earn me another chastisement from Dr Clements, but I can’t pass by this – admittedly very speculative – claim that cosmologists have found possible evidence for the ‘bubble universes’ theory, in which universes are being created all the time but never overlap because the space between them inflates faster than the universes grow.  Yes, I know, ‘not statistically significant,’ and ‘wait for Planck,’ but this would be so awesome.

August 7, 2011 | Permalink | Comments (1) | TrackBack (0)

July 21, 2011

You could be right about the fail

Huh.  If I start a sentence “If they sail…,” Word asks me to ‘correct’ sail to fail.  Doesn’t happen with any other pronoun.  Apparently groups only get to go sailing if they invite you or me.

July 21, 2011 | Permalink | Comments (1) | TrackBack (0)

July 17, 2011

Wanted

Browser whose usability does not suck more with each release.  Can offer part exchange on an arthritic cat.

July 17, 2011 in Usability | Permalink | Comments (1) | TrackBack (0)