Home > Raku > Reusing a wheel

Reusing a wheel

A while back I reinvented a wheel which is rolling slower then the one build into Rakudo. While reading BOOTSTRAP.nqp I discovered add_dispatchee. By stealing this wheel I might get better results. After all, this approach is working very well for manufacturers all over the world. Let’s have something to dispatch on.

my $emitter = Supplier.new;
my $s = $emitter.Supply;

my $p = start {
    loop {
        $emitter.emit: [42, 'answer', Any].roll;
        sleep 0.25;
    }
}

The Supply will spit out values we have to handle. We will need a proto to call add_dispatchee on and tap the Supply with.

sub handle-with(Supply:D $s, *@routines) {
    my proto pseudo-multi(|) {*}
    for @routines -> &b {
        &pseudo-multi.add_dispatchee(&b);
    }

    $s.tap: &pseudo-multi;
}

handle-with($s,
    sub (Int $_) { say .WHAT },
    sub (Str $_) { say .WHAT },
    sub (Any:U $_) { say 'undefined' },
);

await $p;

The multi method dispatcher does the heavy lifting and we might see the optimiser do some work too. We can’t use pointy blocks instead of subs because Rakudo wont let us. A multi sub without a handler for CX::Return doesn’t make sense.

All this is quite nice but comes with a catch. Roast doesn’t know know about add_dispatchee. So there might be a is implementation-detail missing. If that changes with new-dispatch, we will have to wait and see. I for one would like to see more possibilities for using dispatch in Raku.

Categories: Raku
  1. No comments yet.
  1. April 26, 2021 at 15:20

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: