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

Using Perl 6 REPL:

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

Earlier I thought that A => 1 and 'A' => 1 would be identical, because => should automatically authorize the word on the left, but in the second example the pairs seem to disappear.


Disclaimer: Today it worked earlier, so I send it as Q&A if it is useful for someone else. Also feel free to add your own answers.

+5
source share
2 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, not as a pair. And in methods, unused named arguments are ignored , which explains the empty Map created in the second expression. Thus, you need to make sure that the parser does not interpret your pairs as named arguments. All of the following differences 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 for using a 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 
+4
source

In 'A' => 1 , 'A' is a string, in A => 1 A is an identifier.

Relevant discussion ...

If the key is a syntactic identifier, and it is directly in the argument list, it will be accepted as a named argument. Otherwise it will be a couple

"foo" => "bar" is not a syntactic identifier, (foo => "bar") is not directly in the argument list, nor is (: foo)

foo => "bar" and: foo ("bar") are equivalent, and both have a key that is a syntactic identifier

Q: Does identifier do "ident" => "foo" outside the argument list?

This is the wrong way. They are always pairs, which means that they move along named arguments when at the top level of the argument list

Q: and does: 2 <> and: 2nd do not turn into pairs for convenience only?

: 2nd is just: nd (2)

Q: why not "2nd" => "True"? because not an identifier?

Also because it is not very useful. Imagine that you are trying to implement s: 2nd / foo / bar / You should take a dirty hash and try to parse the number from it

Q: if the thing after: can only be an identifier in the base case, then everything is fine and good at doing things with non-identifiers.

Yes, something non-identifier after it is a special form

+1
source

Source: https://habr.com/ru/post/1270691/


All Articles