たらいまわし

とかを読んで自分でもまわしたくなって見ました。とりあえずScheme版をもとにNemerle化。

  • 何も考えずにLazy使ったやつ


using System;
using Nemerle;

class Tarai
{
static tarai (x : LazyValue [int],
y : LazyValue [int],
z : LazyValue [int]) : LazyValue [int]
{
if (x.Value <= y.Value)
y.Value
else
tarai (lazy (tarai (lazy (x - 1), y, z)),
lazy (tarai (lazy (y - 1), z, x)),
lazy (tarai (lazy (z - 1), x, y)))
}

public static Main() : void
{
def x = 768;
def y = 384;
def z = 0;

Nemerle.IO.printf ("%d", tarai (lazy (x), lazy (y), lazy (z)));
}
}

何故か遅延評価にならず、全然終わる気配が見えません…(Nemerleよく分かってないので間違ってる可能性大)

  • Lazy使わずlambdaで代用


using System;
using Nemerle;

class TaraiLambda
{
static tarai (x : void -> int,
y : void -> int,
z : void -> int) : int
{
if (x () <= y ())
y ()
else
tarai (fun () { tarai (fun () { x () - 1 }, y, z) },
fun () { tarai (fun () { y () - 1 }, z, x) },
fun () { tarai (fun () { z () - 1 }, x, y) })
}

public static Main() : void
{
def x = 768;
def y = 384;
def z = 0;

Nemerle.IO.printf ("%d", tarai (fun () { x },
fun () { y },
fun () { z }));
}
}

こっちはすぐ終わってくれるのですが、それでも本当の遅延評価ほどは早くなってないようです。