© Moritz Lenz 2020
M. LenzRaku Fundamentals https://doi.org/10.1007/978-1-4842-6109-5_8

8. Review of the Raku Basics

Moritz Lenz1 
(1)
Fürth, Bayern, Germany
 

In the previous chapters, we discussed some examples interleaved with the Raku mechanics that make them work. Here I want to summarize and deepen the Raku knowledge that we’ve touched on so far, removed from the original examples.

8.1 Variables and Scoping

In Raku, variable names are made of a sigil, $, @, %, or &, followed by an identifier. The sigil implies a type constraint, where $ is the most general one (no restriction by default), @ is for arrays, % is for hashes (associative arrays/maps), and & is for code objects.

Identifiers can contain - and ' characters, as long as the character after it is a letter. Identifiers must start with a letter or underscore.

Subroutines and variables declared with my are lexically scoped. They are visible from the point of the declaration to the end of the current {}-enclosed block (or the current file, in case the declaration is outside a block). Subroutine parameters are visible in the signature and block of the subroutine.

An optional twigil between the sigil and identifier can influence the scoping. The * twigil marks a dynamically scoped variable; thus, lookup is performed in the current call stack. ! marks attributes, that is, a per-instance variable that’s attached to an object.

8.2 Subroutines

A subroutine, or sub for short, is a piece of code with its own scope and usually also a name. It has a signature that specifies what kind of values you have to pass in when you call it:
sub chunks(Str $s, Int $chars) {
#         ^^^^^^^^^^^^^^^^^^^^ signature
#   ^^^^^^ name
    gather for 0 .. $s.chars / $chars - 1 -> $idx {
        take substr($s, $idx * $chars, $chars);
    }
}

The variables used in the signature are called parameters, whereas we call the values that you pass in arguments.

To refer to a subroutine without calling it, put an ampersand (&) in front of it, like so:
say &chunks.name;     # Output: chunks
To call it, simply use its name, followed by the list of arguments, which can optionally be in parentheses:
say chunks 'abcd', 2;   # Output: (ab cd)
say chunks('abcd', 2);  # Output: (ab cd)
You only need the parentheses if some other construct would otherwise interfere with the subroutine call. Hence, if you intend to write
say chunks(join('x', 'ab', 'c'), 2);
and you leave out the inner pair of parentheses
say chunks(join 'x', 'ab', 'c', 2);
then all the arguments go to the join function, leaving only one argument to the chunks function. On the other hand, it is fine to omit the outer pair of parentheses and write
say chunks join('x', 'ab', 'c'), 2;

because there’s no ambiguity here.

One case worth noting is that if you call a subroutine without arguments as the block of an if condition or a for loop (or similar constructs), you have to include the parentheses, because otherwise the block is parsed as an argument to the function.
sub random-choice() {
    Bool.pick;
}
# right way:
if random-choice() {
    say 'You were lucky.';
}
# wrong way:
if random-choice {
    say 'You were lucky.';
}
If you do happen to make this mistake, the Raku compiler tries very hard to detect it. In the preceding example, it says
Function 'random-choice' needs parens to avoid gobbling block
and when it tries to parse the block for the if statement, it doesn’t find one:
Missing block (apparently claimed by 'random-choice')

When you have a sub called MAIN, Raku uses its signature to parse the command-line arguments and pass those command-line arguments to MAIN.

multi subs are several subroutines with the same name but different signatures. The compiler decides at runtime which of the candidates it calls based on the best match between arguments and parameters.

8.3 Classes and Objects

Class declarations follow the same syntactic schema as subroutine declarations: the keyword class, followed by the name, followed by the body in curly braces:
class OutputCapture {
    has @!lines;
    method print(s) {
        @!lines.push(s);
    }
    method captured() {
        @!lines.join;
    }
}
By default, type names are scoped to the current namespace; however, you can make it lexically scoped by adding a my in front of class:
my class OutputCapture { ... }
Creating a new instance generally works by calling the new method on the type object. The new method is inherited from the implicit parent class Any that all types get:
my $c = OutputCapture.new;
Per-instance state is stored in attributes, which are declared with the has keyword, as seen in the preceding has @!lines. Attributes are always private, as indicated by the ! twigil. If you use the dot . twigil in the declaration instead, you have both the private attribute @!lines and a public, read-only accessor method:
my class OutputCapture {
    has @.lines;
    method print(s) {
        # the private name with ! still works
        @!lines.push(s);
    }
    method captured() {
        @!lines.join;
    }
}
my $c = OutputCapture.new;
$c.print('42');
# use the `lines` accessor method:
say $c.lines;       # Output: [42]

When you declare attributes with the dot twigil, you can also initialize the attributes from the constructor through named arguments, as in OutputCapture.new( lines => [42] ).

Private methods start with a ! and can only be called from inside the class body as self!private-method.

Methods are basically subroutines, with two differences. The first is that they get an implicit parameter called self, which contains the object the method is called on (which we call the invocant). The second is that if you call a subroutine, the compiler searches for this subroutine in the current lexical scope as well as the outer scopes. On the other hand, method calls are looked up only in the class of the object and its superclasses.

The subroutine lookup can happen at compile time, because lexical scopes are immutable at runtime, so the compiler has knowledge of all lexical symbols. However, even in the presence of type constraints, the compiler can’t know if the type of an object is possibly a subtype of a type constraint, which means method lookups must be deferred to runtime.

8.4 Concurrency

Raku provides high-level primitives for concurrency and parallel execution. Instead of explicitly spawning new threads, you are encouraged to run a computation with start, which returns a Promise.1 This is an object that promises a future computation will yield a result. The status can thus be Planned, Kept, or Broken. You can chain promises, combine them, and wait for them.

In the background, a scheduler distributes such computations to operating system–level threads. The default scheduler is a thread pool scheduler with an upper limit to the number of threads available for use.

Communication between parallel computations should happen through thread-safe data structures. Foremost among them are Channel2 (a thread-safe queue) and Supply3 (Raku's implementation of the Observer Pattern4). Supplies are very powerful, because you can transform them with methods such as map, grep, throttle, or delayed and use their actor semantic5 to ensure that a consumer is run in only one thread at a time.

8.5 Outlook

When you understand the topics discussed in this chapter, and dig a bit into the built-in types, you should be familiar with the basics of Raku and be able to write your own programs.

Next we will look into one of the strengths of Raku: parsing, via regexes and grammars.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.105.137