Sunday, January 31, 2010

“Hello Glade#” from F#

Another bit of spiking, a rather tardy follow up from raw GTK#, starting from the C# example at the Mono Project site, but incorporating the earlier example, so as to build in a clean application exit, for one thing.

In the .glade file, I changed the label size from 38, as in

<widget class="GtkLabel" id="label1">
       <property name="width_request">38</property>

to 88, so as to allow the displayed text to be longer.

In VS2008 I added the .glade file by including a new F# script file, but renaming it to gui.glade, pasting in the XML, and setting its properties to have a Build Action of Embedded Resource. The code looks like:

Here the widgets are surfaced via a plain data object, Handler, and their events are wired up much as before via F#'s first class reactive events, which are much more natural (especially when combining events to one handler is required). The project needs a reference to the glade-sharp assembly, above and beyond the ones already required for pure GTK#

Unfortunately, the need for CLR attributes on members is problematic for IronPython -- the least nasty way to achieve the equivalent of the Handler class would be to compile some C# on the fly.

Unchanged by version 1.9.9.9, February 2010 CTP.

Unchanged by version 3.1.1, January 2014 (except that Add Existing Item works better for the .glade file in VS2010 and up).

Monday, January 18, 2010

Hello, Functional World! -- A gap in the market

Reading my newly arrived copy of Real World Functional Programming, I couldn't help but feel that its very gentle introduction to the style so nearly makes it suited to being a pure introduction to programming via the functional style, if only it were not for the compare/contrast with an assumed fluency in C#; in the same way that Scala texts do with Java.

If functional programming is the up and coming thing as it is seeming to be, wouldn't it be nice to have a book at the level of, say, Hello World! or Python Programming for the Absolute Beginner? Something which really does start teaching programming in a functional way from the ground up, and, moreover, try to make it fun for youngsters by bringing in some eye-candy in the form of games. That rules out SICP, or even the Little Schemer, which is very abstruse for all its wry humour.

So what has a games platform? With F#, we can use either the old managed DirectX, or XNA, but those are very tied to Windows; Scala or Clojure could tie into the MIDP with phone emulators; at a pinch, you can write games in wxWidgets and might be able to do something with wxErlang. Masochists have even tried writing GUI games in Haskell. So it's not as if there is a dearth of possible languages to work with, even if they may not approach having something like PyGame to do a lot of the heavy lifting.

Possibly the main limit is in tooling -- no integrated chroma-coded REPL like IDLE offers for Python. There are chroma-coded editors with some shell integration -- Scite has Erlang mode, Scala comes with scala.properties in Scala\misc\scala-tool-support\scite (though you may need to edit the command lines in it to have an explicit .bat on the scripts -- but pretty much every instruction I see for anything on MacOS X starts with "Download Xcode ... its little over 1 GB." -- well, I exaggerate; not all the instructions mention the sheer size of the bundle. Even instructions for setting environment variables reach for Xcode, which puts a big burden on top of setting up Scala-on-NetBeans, which would otherwise be comparatively lightweight.

But wouldn't it be great to start beginners off without mutability and iteration?

Sunday, January 17, 2010

Review catch-up — Anime

Asura Cryin' second season

For the first half at least, it carried on as before, throwing ever more stuff into the pot every episode; before suddenly deciding to pick one of the multiplicity of minor characters, nominate them as Final Boss, and go for the sort of ending which clearly wanted to be Gurren Lagann when it grew up, with our hero doing a "Man up and save the world! Twice!" before reverting to schoolboy with harem end.

Overall: showy trash.

Mouryou no Hako

Despite my worst fears, this best series of 2008 finally got subbed in dribs and drabs over the year, with the concluding episode available only a year after the fact.

And, suprisingly, the conclusion was a remarkably satisfying one.

In all, this series felt more like cinema; but with the length -- and the seamless SFX -- that the 13 episode animated format afforded being used to advantage.

One of the very best of the decade, and probably the best of 2008.

My top 20 of the Noughties

In alphabetical order:

Akagi
Blue Drop ~Tenshi-tachi no Gikyoku~
Chi's Sweet Home
Dennou Coil 
Gankutsuou
Ghost in the Shell: Stand Alone Complex
Hataraki Man
Kemonozume
Kino's Journey
Mahou Shoujo Lyrical Nanoha
Maria-sama ga Miteru
Mononoke
Mouryou no Hako
Mushishi
Nijuu Mensou no Musume
Planetes
Princess Tutu
Ristorante Paradiso
Seirei no Moribito
Simoun

2009 -- the rest

A thin year -- total number of new series I watched was about the number I picked up for Q2 '08 alone -- but one where Crunchyroll expanded its operation enough that, love them or loathe them, I was able to watch a good number of series in a context other than "try before buy" (even if some of the advertising was terribly, terribly bad and repeated 3+ times per episode).

I'll get to Kemono no souja Erin and Miracle Train as and when I finish; but they aren't exactly burn through to marathon types of series. Tried and dropped were Sasameki Koto -- the other yuri series of the year started with so many school clichés, the sort of things that Aoi Hana avoided, that I gave up after a few minutes. Falling into the "who are these people and why should I care about them?" and the "Oh, my eyes, the CGI!" traps was the Book of Bantorra -- I just have better things to do than the second episode.

Although I raved about the novel adaptation of Mouryou no Hako, the material in Aoi Bungaku led off with the sort of self-indulgent self loathing material that too often passes for literary merit for my tastes, so I gave that a miss; and it took only a couple of episodes of Kūchū Buranko to decide that, literary provenance and associations with Mononoke be damned, under the psychedelia, this was boring and repetitive.

Also belatedly tried, and dropped like a brick:

Texhnolyze

I bought this a while back, after watching Serial Experiments Lain and Haibane Renmei, but had never found a gap to watch it in. Such a gap arose about a year ago; and I wish I had not wasted the money, but had instead done a "try before buy". Had I done so, after a first episode with essentially no dialogue or narrative structure, that just spent its 25 minutes waving its art in my face, I would have stopped. As it was I went "Next Episode", expecting perhaps more of the same and instead suffered through effective animation used for malign ends. Each time I thought things had bottomed out, the clinically sadistic depiction of some person suffering massive and essentially self-inflicted (by interfering where self-preservation would have held up a massive "KEEP AWAY" sign) injuries went on and got worse.

It is perhaps a tribute to the skill involved that I ended up queasy, with cold sweat, but having massively failed on the "who are these people and why should I care about them?" test -- mainly because there has been no time spent on such persiflage as who they are because "it's, like, Art, man!"; and depicting them as it does as undeserving of sympathy, it had not only failed to intrigue, but had completely discouraged me from wondering what happened next. So while I dropped Baccano! after a similar amount for just being nasty, this I dropped for being actively evil. Definitely the worst of the decade of those things I watched.

An interlude of thaw

Finally a few mild days, and the heap of snow shovelled from the drive has finally melted, leaving the garden snow free after a whole month. The milder weather and the sun was enough that the greenhouse windows even started to open a little, very comfortable when harvesting the chillies. Having layered bubble-wrap over them and the other tender plants that live on the patio in the summer, and just keeping that little tent frost-free, seems to be preserving them in generally good shape, except those branches closest to the glass.

Of course, with the thaw, it's back to raking up dead leaves, and piling them on the part of the garden where I need to dig in some more organic matter; and to look at the lawn and think that it's a couple of months at least yet before I can sensibly apply a much needed moss treatment.

Thursday, December 31, 2009

The importance of API design

Reflecting on the exercise leading up to yesterday's post, one of the things that struck me in the comparison of the .net Framework used from F# and the Java APIs available to Scala/JVM was how much the former got little details right to facilitate working in the web-page embedded context. Take the simple task of getting at the URL query parameters for the page in which the applet is embedded

In Silverlight, in the main UserControl class:

In an applet, where peer is the Applet instance:

Perhaps this just shows how the old-style Java applet has withered on the vine, while Silverlight as a competitor to Flash has taken on a more aggressive stance for developer acceptance -- but with the decade-plus that Java has under its belt compared with Silverlight's barely more than a year (1.0 not really counting), the comparison is rather disappointing.

I shall have to investigate whether the continued work on scala-msil has led to any material improvements in its robustness since I looked at it last, six months ago.

A few minutes later

Well, my six month old port of the Scala actors package to pure Scala calling the .Net APIs still blows the compiler up in a Scala 2.8 nightly that's just a few days old. The explosion is in pure Scala code taken directly from the 2.7.5 actors package, and not the Scala-calling-.net replacements I coded of the Java parts of that package:

object Eval$2
  symbol = final case  object Eval$2
  owner  = final  object Futures
with methods = List(scala.actors.Futures.Eval$2., scala.actors.Futures.Eva
l$2.readResolve, scala.actors.Futures.Eval$2.canEqual, scala.actors.Futures.Eval
$2.productElement, scala.actors.Futures.Eval$2.productArity, scala.actors.Future
s.Eval$2.productPrefix, scala.actors.Futures.Eval$2.toString, scala.actors.Futur
es.Eval$2.productElements, scala.actors.Futures.Eval$2.productIterator)
Exception in thread "main" java.lang.RuntimeException: ILGenerator.emit(): Stack
 underflow in method: public static System.Void scala.actors.Futures$+scala.acto
rs.Futures.Eval$2$::.cctor()
        at ch.epfl.lamp.compiler.msil.emit.ILGenerator.emit(ILGenerator.scala:48
7)

So, still not ready for prime-time.

Wednesday, December 30, 2009

Anime — Aoi Hana (Sweet Blue Flowers)

A quiet little story of school-girl romance, very sweetly done; and with a delicate and restrained art style, presumably heavily post-processed photographs in the main. The story follows childhood friends Fumi and Akira though Fumi's first romance with an older and generally very popular pupil from her school, and the messy break-up that follows. But even through that, all the characters involved are just all-around nice -- no real catty or bitchy episodes (unlike the superficially similar schoolgirl story in Marimite, with the insufferable Touko-chan).

Based on an on-going manga, it ends like a chapter ending rather than the tale being all told, but for all that it comes to a satisfying conclusion. Alas, poor DVD sales means a second series is unlikely -- which is disappointing as it's one of the better shows in what has been a dreadfully thin year for new anime.

Presumably there aren't enough trainspotters to buy it on the strength of the many railway scenes during Fumi and A-chan's commute to their adjoining schools (if Aria can be considered scenery porn, this verges of the train porn at times).


Sample frames and a YouTube link removed following DMCA complaint. If the buggers can't understand fair use quotation for purposes of review, then my recommendation would be to not reward them with any of your hard earned.

Monday, December 28, 2009

A quick Scala gotcha

Wouldn't it be nice, I thought, to be able to put UI decoration as a mixin to any sort of component, like


In Scala 2.8 recent nightlies, this compiles happily -- but when you run it, the self.paintComponent(g) call just stack overflows, flipping between TiledContainer.paintComponent and Tiled.paintComponent as it goes.

At 2.7.x, it doesn't compile -- which at least prevents you getting the run-time error

error: overriding method paintComponent in class Component of type
(g: scala.swing.package.Graphics2D)Unit; method paintComponent in trait Tiled of type
(g: java.awt.Graphics2D)Unit cannot override a concrete member without a third member 
that's overridden by both (this rule is designed to prevent ``accidental overrides'')
class TiledContainer(tiledBackgroundImage : Image, constraints :Seq[String]) extends 
Form(constraints) with Tiled with HasImage {

Friday, December 25, 2009

Winter Wonderland

Thursday evening last, it started to snow -- blizzarding enough that Karen's evening call carers got lost on the way back, took the wrong turn and ended up stuck in the snow on a farm road, and had to be towed out by tractor.

Friday, the snow was drifted deep against the front door, and going out to the village shop, it was calf-deep in places where it had drifted. A definite work from home day.

Saturday, pulled my boots on, and yomped the footpaths across the fields into town to do some shopping, on an exhilarating crisp winter's morning, where the long grass was sticking through the snow like through blown sand on a beach. Traffic was horrid in town, and for the return journey, when I went part of the way along the main road, the snow had clearly turned to slush and been refrozen, horrible going. So on the last, off-road, leg, when I was getting tired and footsore, when confronted by a pitbull thing, I just kept on going. This unsetled it, and when I got within about six feet, in pronked off and started circling, despite being yelled at by its human. I eventually had just to grab the thing by the harness and wait for the lead to be clipped back on.

Deep and crisp and even

Deep and crisp and even

Sunday, I thought it would be a good idea to clear the drive -- but under what looked like nigh virgin snow there was a thick layer of ice. Monday, worked from home again, did some clearing -- though the main bus-route through the village was still thick with ice (no gritting done whatsoever). Tuesday, discover that the other road through the village was clear, so very gingerly make the short drive onto the clear road and the long main-road detour to work. Head home after lunch, expecting the other end of the village to be as clear as the way I went in the morning -- to find a horrible scary drive.

Worked from home the rest of the week, probably getting more done than had I gone in. Yesterday afternoon wheeled the bike out to the main road, then cycled to the nearest supermarket for some last minute food shopping. The main roads were clear, but some of the side roads near the supermarket were sheet ice (one gentle slide to my knees while wheeling over that on the way back).

Today, the thaw was setting in, but there was still snow lying morning and evening -- the first white Christmas I can remember, certainly in the 20+ years living here. the main road was clear, and in the close, the ice was soft and breaking into slush where cars were driving -- but some of the pavements (especially uncleared driveways) were solid slippery sheet ice. One old gent visiting the family for the day managed to get stuck for lack of traction, until I helped him.

Monday, December 14, 2009

Using a different mscorlib for F# in Visual Studio (Silverlight and probably XNA too)

It turns out that I was lucky last year when building an F# Silverlight 2 application by hand in Visual Studio -- I didn't make an explicit reference to mscorlib.

If you explicitly browse to the Silverlight mscorlib assembly to make an explicit reference, the .fsproj file still only gets the basic

    <Reference Include="mscorlib"/>

which falls back to the full framework version of the assembly when you compile. This behaviour has caused some people to abandon the exercise of getting F# to build against something non-default in Visual Studio.

However, the way forward is very simple indeed -- simply edit the .fsproj to give an explicit hint path pointing at the mscorlib you really mean:

    <Reference Include="mscorlib">
      <HintPath>C:\Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v3.0\mscorlib.dll</HintPath>
    </Reference>

and get the confirmation that this sticks in the command line that echoes to the Output window

C:\Program Files\FSharp-1.9.7.8\\bin\fsc.exe -o:obj\Debug\Library3.dll -g --debug:full --noframework --define:DEBUG --define:TRACE --optimize- --tailcalls- -r:"C:\Program Files\FSharp-1.9.7.8\Silverlight\2.0\bin\FSharp.Core.dll" -r:"C:\Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v3.0\mscorlib.dll" --target:library --warn:3 --warnaserror:76 --vserrors --utf8output --fullpaths --flaterrors Module1.fs

Problem sorted.

(Generalise as required to any other assemblies which refuse to stay pointed at the platform you want.)

Save the version number in the output, this advice is unchanged by the February 2010 CTP.

Sunday, December 13, 2009

Packaging Scala applets into one jar in NetBeans with JarJar [Updated]

Pretty much a note to self; using NetBeans that started off as 6.7.1, but has the bleeding-edge depot, and using a Scala 2.8 nightly, FWIW.

Get the jarjar tool; put it and a copy of scala-library.jar and scala-swing.jar in a lib directory under the project. Create a build.xml post-jar target to read

    <target name="-post-jar">
      <taskdef name="jarjar" classname="com.tonicsystems.jarjar.JarJarTask"
               classpath="lib/jarjar-1.0.jar"/>
      <jarjar jarfile="${dist.jar}">
        <fileset dir="${build.classes.dir}"/>
        <zipgroupfileset dir="lib" includes="scala-*.jar" />
        <keep pattern="[your.root.package].*"/>
      </jarjar>
    </target>

Clean and build, get a lot of Scala classes in your output jar file. For which there is then pack200 support to crunch further.

There is an Ant task for that, which we can add to the post-jar target in build.xml thus

    <target name="-post-jar">
      <taskdef name="jarjar" classname="com.tonicsystems.jarjar.JarJarTask"
               classpath="lib/jarjar-1.0.jar"/>
      <taskdef name="pack200"
               classname="com.sun.tools.apache.ant.pack200.Pack200Task"
               classpath="lib/Pack200Task.jar"/>
      <jarjar jarfile="${dist.jar}">
        <fileset dir="${build.classes.dir}"/>
        <zipgroupfileset dir="lib" includes="scala-*.jar" />
        <keep pattern="[your.root.package].*"/>
      </jarjar>
      <pack200 src="${dist.jar}"
               destfile="${dist.jar}.pack.gz"
               GZIPOutput="yes"
               verbose="0"
               />
    </target>

which brings in my first test case, a 2.5Mb jar down to just under 900kb.

Saturday, December 05, 2009

F# and Silverlight 3 addendum

You can make a permanent fix for the hint path needed to find FSharp.Core.dll by editing the template in C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ProjectTemplatesCache\FSharp\Silverlight\SilverlightLibrary3.zip\SilverlightLibrary.fsproj (and probably the version of the file in C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ProjectTemplates\FSharp\Silverlight\SilverlightLibrary3.zip just to be certain).

Proof of concept -- my orrery-clock upgraded to Silverlight 3.0 (with all the source bundled into the .xap file) here.

F# October CTP and Silverlight 3.0

With the February 2010 CTP, obviously change the version number to 1.9.9.9 instead!

Following on from last year's compendium for Silverlight 2 --

There's an official Silverlight 3.0 project template for Visual Studio 2008; while targetted at the May CTP, these can be used with the October CTP by opening up the .fsproj file and amending the file path for the FSharp.Core assembly -- unload project, edit, and change the version in the hint path for the reference to be 1.9.7.8 like

    <Reference Include="FSharp.Core.dll">
      <HintPath>$(ProgramFiles)\fsharp-1.9.7.8\Silverlight\2.0\bin\FSharp.Core.dll</HintPath>
    </Reference>

and then reload.

The template is still useful as it automatically picks up all the other Silverlight platform assemblies from their location in the Silverlight reference assemblies folder, saving you having to do that manually from C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Reference Assemblies and seems to provide some other integration in conjunction with the Silverlight tools.

Unfortunately, none of the samples provided are pure F# -- they all use a C# bootstrap for XAML and the AppManifest packaging. However we can still use last year's recipe with only minimal changes -- just update the RuntimeVersion in AppManifest.xaml to "3.0.40818.0", and the FSharp.Core.dll which you wrap in the .xap file is, of course, the one from the October CTP at C:\Program Files\FSharp-1.9.7.8\Silverlight\2.0\bin\FSharp.Core.dll (not the one from last year!)

Friday, December 04, 2009

The Moon in Winter

This morning at 07:13, about 35 minutes before sunrise, the sky was pale in the east with the approaching dawn -- and when I went downstairs, the just-past-full moon was casting shadows in the dining room.

The cats all agreed that this was good for their crepuscular activites.