The Topic is the topic
I lamented in my last post that we got a lack of beginners material. The reason I gave is that writing such guides is hard. Which leaves the question why it is that hard. While plugging holes in the docs I found that many features of the language pop up in many places. Raku is intertwined with itself. For a beginner you would want to start with something simple and than build on that until you reach maximum complexity. What could be more simple then then humble if
statement? A lot, actually. And the reason is the Topic. This shall be the topic of this post.
As one can expect the Topic shows up in Raku in many places. The uninitiated might even think it apears like magic. So lets add a magic variable to a Callable.
my $magic = 42;
sub s( $hmm? is raw = OUTER::<$magic>) { $magic = $magic == 42 ?? 'answer' !! 'nope' }
s;
say $magic;
# OUTPUT: answer
That’s exactly how a Block gets handed over the Topic.
my &block = {;}
say &block.signature;
# OUTPUT: (;; $_? is raw = OUTER::<$_>)
Many language elements in Raku set the topic by default. If does so only when we ask for it.
if 42 { $_.say }
if 42 -> $_ { $_.say }
# OUTPUT: (Any)
# 42
How does the compiler know the difference?
my &pointy = -> $_ {;};
say &pointy.signature;
# OUTPUT: ($_)
The explicit Parameter in a pointy block is not optional. We can use arity and count to tell them apart.
say [&block.signature.arity, &pointy.signature.arity];
say [&block.signature.count, &pointy.signature.count];
# OUTPUT: [0 1]
# [1 1]
There is another way how to change the arity of a block.
&block = { $^a.say };
say [&block.signature, &block.signature.arity];
if 42 { say $^a }
# OUTPUT: [($a) 1]
# 42
Still not conviced the compiler doesn’t cheat?
if 42 { say $^_ }
# OUTPUT:
# Redeclaration of symbol '$^_' as a placeholder parameter
# at /home/dex/projects/blog/topic-is-topic.raku:69
# ------> if 42 { say $^_⏏ }
Which doesn’t mean the compiler wont cheat. It’s the compiler after all. But this is one of those places in Raku where things fall into place. By having a language called Signature to describe parameters of Callables and access to the scope no magic is required to implement magic variables.
This blog post was sparked by a hole in the docs. By writing this post I spotted another one. We forgot the mention that the literal for an empty block is {;}
. All we would need to do to find all holes is going through Roast and see if anything mentioned there is also in the docs. Sadly I got other things to do in the next 900 days or so.
But enough moaning. Let’s end with a positive conclusion. Raku may look like magic. It isn’t. It’s just very clever indeed.
-
June 15, 2020 at 17:102020.24 Cloud Approaching – Rakudo Weekly News