Search code examples
raku

Is it ok to use binding when declaring variables?


I keep asking questions about sets in Raku to several AIs.

Now I asked again a question about sets in Raku to Deepseek.

It gave me the following example

# Create a mutable SetHash
my %set := SetHash.new(1, 2, 3);

# Add elements
%set.set(4);
%set ∪= set(5, 6);

# Remove an element
%set.unset(2);

# Check membership
say 3 ∈ %set; # Output: True
say 2 ∈ %set; # Output: False

# Display the set
say %set; # Output: SetHash(1 3 4 5 6)

I tested the example, and it worked fine.

My question is, is it ok to declare (not scalar) variables using binding, or is there any downside to that ?


Solution

  • If you do not use binding in this case:

    my %set = SetHash.new(1, 2, 3);
    

    you will store the result of SetHash.new(1,2,3) in a Hash called %set. And then consequently, %set.set(4) will fail with: No such method 'set' for invocant of type 'Hash'.

    If you don't like the binding syntax, you can use the alternate syntax using the is trait:

    my %set is SetHash = 1, 2, 3;
    

    To get back to your question: "My question is, is it ok to declare (not scalar) variables using binding, or is there any downside to that ?"

    Yes, it is ok, and in situations like this, required to get the desired result.