Course of Raku / Addendum 🆕 / Types and text machines / Objects and classes / Exercises / A stack class
Solution: A stack class
Here is a possible solution to the task.
Code
class Stack {
has @!items;
method push($x) { @!items.push($x) }
method pop { @!items.pop }
method peek { @!items.tail }
method size { @!items.elems }
}
my $stack = Stack.new;
$stack.push($_) for 1, 2, 3;
say $stack.peek;
say $stack.pop;
say $stack.size;🦋 You can find the source code in the file stack.raku.
Output
3
3
2Comments
@!itemsis a private attribute — the!twigil means it is reachable only from inside the class, which is exactly what a stack’s storage should be.peekuses.tailto look at the last element without removing it, whilepopactually takes it off, so the size drops from3to2.
Course navigation
← A stack class | A bank account →