Hi,
For a bit of holiday fun, I want to present a Rust implementation of
Knuth's man-or-boy <http://en.wikipedia.org/wiki/Man_or_boy_test> compiler
test.  Can this be improved?
Here's<http://rosettacode.org/wiki/Man_or_boy_test>how it looks in
other languages.

Right off the bat, I would say that would be prettier if we had argument
auto-borrowing, if invocation operator would auto-deref, and if closure
assignment was in scope to be captured inside the closure itself (wouldn't
have to do dummy init of the B var).

cheers,
Vadim

type T<'s> = 's || -> int;

fn man_or_boy(k:int) -> int {
    fn A(k:int, x1:&T, x2:&T, x3:&T, x4:&T, x5:&T) -> int {
        let mut k = k;

        let mut B: T = || {fail!()};
        B = || {
            k -= 1;
            A(k, &B, x1, x2, x3, x4)
        };

        if k <= 0 {
            (*x4)() + (*x5)()
        } else {
            B()
        }
    }
    A(k, &||{1}, &||{-1}, &||{-1}, &||{1}, &||{0})
}

fn main() {
    for k in range(0,20) {
        println!("{} => {}", k, man_or_boy(k));
    }
}


Sample output:

0 => 1
1 => 0
2 => -2
3 => 0
4 => 1
5 => 0
6 => 1
7 => -1
8 => -10
9 => -30
10 => -67
11 => -138
12 => -291
13 => -642
14 => -1446
task '<main>' has overflowed its stack
_______________________________________________
Rust-dev mailing list
Rust-dev@mozilla.org
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to