Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between A => 1 and 'A' => 1?

Tags:

raku

Using the Perl 6 REPL:

> Map.new: 'A' => 1, 'B' => 2;
Map.new((:A(1),:B(2)))
> Map.new: A => 1, B =>2;
Map.new(())

I previously thought that A => 1 and 'A' => 1 would be identical because => is supposed to autoquote the word to its left, but in the second example the pairs seem to disappear.


Disclaimer: This tripped me up earlier today, so I'm posting it as Q&A in case it is helpful to someone else too. Also feel free to add your own answers.

like image 222
Christopher Bottoms Avatar asked Aug 08 '17 18:08

Christopher Bottoms


1 Answers

In general, A => 1 and 'A' => 1 create equivalent Pair objects. But inside a subroutine or method call, the first syntax is parsed as named arguments instead of as a Pair. And in methods, unused named arguments are ignored, which explains the empty Map created in your second statement. So, you have to take a little extra care that the parser does not interpret your pairs as named arguments. The following are all distinguishable from named arguments:

Map.new: (A=>1, B=>2);    # extra set of parentheses 
Map.new: 'A'=>1, 'B'=>2;  # quote the keys
Map.new: 'A', 1, 'B', 2;  # Don't use fat commas `=>`

By the way, this also demonstrates another reason to use the colon : instead of () for method calls. Using parentheses may not be as clean:

Map.new( A=>1, B=>2);  # oops, named arguments
Map.new((A=>1, B=>2)); # extra set of parentheses solves the issue 
like image 170
Christopher Bottoms Avatar answered Nov 15 '22 09:11

Christopher Bottoms