Wednesday, May 19, 2010

F# -- excessively lazy sequences and stateful visitors

Doing something a little bit complicated here: the functional equivalent of a visitor pattern, where I want to apply a few functions to a long and potentially expensive to traverse sequence of items (so ruling out a series of iterations over the visited nodes) --

BuildNodeSequence itself returns a nested sequence expression of the data to visit, and state is well, expected to be handled by mutable out-of-band means.

This works nicely, but is impure -- so let's try to fix that by having the visitor function update itself with the transient state we need to carry between (there will still be side-effects for output). The code becomes

where the Fix delegate type is a way of reifying an otherwise infinite type Node ->'a where 'a is also Node ->'a through

and have it build

Well, I run this and...

Nothing happens -- or at least apply gets called for every node to visit, but invoke never did; until I forced the evaluation of the visitors sequence by

So, what I finally ended up with is

where the inner iterable is evaluated eagerly, rather than being left to lazy IEnumerable expansion; and this then works.

Monday, May 17, 2010

An interesting bit of F# behaviour

In one assembly, define a public static class in C#:

In another do something similar in F#:

which Reflector tells us is equivalent to

inside namespace ClassLibrary1. Now create another F# library referencing the previous two containing

The first line compiles; the second doesn't, failing with compile error error FS0039: The type 'Module1' is not defined.

Clearly the CompilationMapping is being sniffed by the typeof operation, because that is the only difference between the two.

Friday, May 07, 2010

No real change here then

Conservative 47.4; Liberal Democrat 34.1; Labour 10.2; Constituency Swing 2.5% From CON to LD since last time (continuing small erosion).

At least the only fascist party standing locally came last -- and the local character and UKIP ejectee standing as an independent came in 4th, narrowly beating UKIP into 5th place out of six.

Whoever emerges from the rest of the shambles will probably be calling in the IMF in a few months, so it makes little difference.