Home > Raku > Making myself a present

Making myself a present

My last simple Christmas wish turned out to be quite complex. Testing an idea in actual code can reveal much of the problems that arise from changing CORE concepts. Luckily, we can tweak many things in Raku without changing code in Rakudo. One thing that always bugged me are Mixins of compound types. When mixing in a value, this value will be exposed by a method with the same name as the values’ type object name.

my $a = "foo" but %{ bar => 42 };
say $a.Hash<bar>;
# OUTPUT: 42

This is correct but not very DWIMy. As it turns out we don’t need to do much to change that.

multi sub infix:<but>(Mu \l, Associative \h) {
    constant &BUT = &infix:<but>;
    role MixinAssociative[%h, \v] does Associative {
        has $.the-value = v;
         has %.the-hash handles<AT-KEY EXISTS-KEY DELETE-KEY push iterator list kv keys values> = %h;
    }

    BUT(l, MixinAssociative[h, l]);
}

my $a = "foo" but %{ bar => 42 };
say $a<bar>;
# OUTPUT: 42

I need to stash the original &infix:<but> away to avoid infinite recursion. Any call to raku on a Mixin doesn’t really tell the full story thought.

my $a = "foo" but %{ bar => 42 };
dd $a;
# OUTPUT: Str+{<anon|1>} $a = "foo"

By providing our own raku method in MixinAssociative we can tell the truth.

...
method raku( --> Str ) {
    $!the-value.raku ~ " but " ~ %.the-hash.raku
}
...

my $a = "foo" but %{ bar => 42 };
dd $a;
# OUTPUT: Str+{MixinAssociative[Hash,Str]} $a = "foo" but {:bar(42)}

Changing the semantics of Mixins of values would be quite a drastic change to the language. Having better raku methods on Mixins would not. Yet, there may be fallout in Roast. This shows nicely that there are plenty of ideas left to explore in hopes to improve an already nice language.

Categories: Raku
  1. No comments yet.
  1. December 21, 2020 at 18:02

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: