/
py-nutshell.pod6
749 lines (543 loc) · 15.3 KB
/
py-nutshell.pod6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
=begin pod
=TITLE Python to Perl 6 - nutshell
=SUBTITLE Learning Perl 6 from Python, in a nutshell
This page is an attempt to provide a way to learn Perl 6
for folks coming from a Python background. We discuss
the equivalent syntax in Perl 6 for a number of Python
constructs and idioms.
=head1 Basic syntax
=head2 Hello, world
Let's start with printing "Hello, world!". L<put> in Perl 6 is the
equivalent of L<print> in Python. Like Python 2, parentheses are
optional. A return is added to the end of the line.
Python 2
=for code :lang<python>
print "Hello, world!"
Python 3
=for code :lang<python>
print("Hello, world!")
Perl 6
put "Hello, world!"
There is also L<say>, which behaves similarly, but will call
the L<gist> method of its argument.
Perl 6
my $hello; ...;
say "Hello, world!"; # also prints "Hello, world"
say $hello; # same as: put $hello.gist
In Python, C<'> and C<"> are interchangeable.
In Perl 6, both may be used for quoting, but double
quotes (C<">) signify that interpolation should be performed.
For instance, variables that start with a C<$>, and expressions
contained in curly braces are interpolated.
Perl 6
my $planet = 'earth';
say "Hello, $planet"; # Hello, earth
say 'Hello, $planet'; # Hello, $planet
say "Hello, planet number { 1 + 2 }"; # Hello, planet number 3
=head2 Statement separators
In Python, a newline signifies the end of a statement.
There are a few exceptions: A backslash before a newline
continues a statement across lines. Also if there is
an unmatched opening parentheses, bracket, or curly
brace, the statement continues across lines, until the
matching braces are closed.
In Perl 6, a semicolon signifies the end of a statement.
The semicolon may be omitted if it is the last statement
of a block. The semicolon may also be omitted if there
is a closing curly brace followed by a newline.
Python
=for code :lang<python>
print 1 + 2 + \
3 + 4
print ( 1 +
2 )
Perl 6
say 1 + 2 +
3 + 4;
if True { say 1 + 2 }
=head2 Blocks
In Python, indentation is used to indicate a block. Perl 6
uses curly braces.
Python
=for code :lang<python>
if 1 == 2:
print "Wait, what?"
else:
print "1 is not 2."
Perl 6
if 1 == 2 {
say "Wait, what?"
} else {
say "1 is not 2."
}
Parentheses are optional in both languages in expressions in
conditionals, as shown above.
=head2 Variables
In Python, variables are declared and initialized at the same time:
=for code :lang<python>
foo = 12
bar = 19
In Perl 6, C<my> declares a lexical variable. A variable can be
initialized with C<=>. i.e. these can be written as two statements or one.
my $foo; # declare
$foo = 12; # initialize
my $bar = 19; # both at once
Also, as you may have noticed, variables in Perl 6 usually start with
sigils -- symbols indicating the type of their container. Variables
starting with a C<$> hold scalars. Variables starting with an C<@>
hold arrays, and variables starting with a C<%> hold a hash (dict).
Immutable variables can be sigil-less, if they are declared with a C<\>.
Python
=begin code :lang<python>
s = 10
l = [1, 2, 3]
d = { a : 12, b : 99 }
print s
print l[2]
print d['a']
# 10, 2, 12
=end code
Perl 6
my $s = 10;
my @l = 1, 2, 3;
my %d = a => 12, b => 99;
my \x = 99;
say $s;
say @l[1];
say %d<a>; # or %d{'a'}
say x;
# 10, 2, 12, 99
=head2 Scope
In Python, functions and classes create a new scope, but no other
block constructor (e.g. loops, conditionals) creates a scope. In
Python 2, list comprehensions do not create a new scope, but in Python 3, they do.
In Perl 6, every block creates a lexical scope.
Python
=for code :lang<python>
if True:
x = 10
print x
# x is now 10
Perl 6
=for code :skip-test<compile time error>
if True {
my $x = 10
}
say $x
# error, $x is not declared in this scope
=for code
my $x;
if True {
$x = 10
}
say $x
# ok, $x is 10
Python
=for code :lang<python>
x = 10
for x in 1, 2, 3:
pass
print x
# x is 3
Perl 6
my \x = 10;
for 1, 2, 3 -> \x {
# do nothing
}
say x;
# x is 10
Lambdas in Python can be written as blocks or pointy blocks in Perl 6.
Python
=for code :lang<python>
l = lambda i: i + 12
Perl 6
=for code :preamble<my $i>
my $l = -> $i { $i + 12 }
Another Perl 6 idiom for constructing lambdas is the Whatever star, C<*>.
Perl 6
my $l = * + 12 # same as above
A C<*> in an expression will become a placeholder for the argument,
and transform the expression into a lambda at compile time. Each
C<*> in an expression is a separate positional parameter.
See the section below for more constructs regarding subroutines and blocks.
Another example (from the Python L<FAQ|https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result>):
Python
=for code :lang<python>
squares = []
for x in range(5):
squares.append(lambda: x ** 2)
print squares[2]()
print squares[4]()
# both 16 since there is only one x
Perl 6
my \squares = [];
for ^5 -> \x {
squares.append({ x² });
}
say squares[2]();
say squares[4]();
# 4, 16 since each loop iteration has a lexically scoped x,
Note that C<^N> is like C<range(N)>. Similarly,
C<N..^M> works like C<range(N, M)> (a list from N
to M - 1). C<N..M> is a list from N to M. The
C<^> before or after the C<..> indicates that the
beginning or ending endpoint of the list (or both)
should be excluded.
Also, C<x²> is a cute way of writing C<x ** 2> (which also
works fine); the unicode superscript 2 squares a number.
Many of the other unicode operators work as you would expect
(exponents, fractions, π), but every unicode operator
or symbol that can be used in Perl 6 has an ASCII equivalent.
=head2 X<Control flow|Python>
Python has C<for> loops and C<while> loops:
=for code :lang<Python>
for i in 1, 2:
print i
j = 1
while j < 3:
print j
j += 1
# 1, 2, 1, 2
Perl 6 also has C<for> loops and C<while> loops:
for 1, 2 -> $i {
say $i
}
my $j = 1;
while $j < 3 {
say $j;
$j += 1
}
(Perl 6 also has a few more looping constructs: C<repeat, until>,
C<repeat, while>, C<until>, and C<loop>.)
C<last> leaves a loop in Perl 6, and is analogous to
C<break> in Python. C<continue> in Python is C<next>
in Perl 6.
Python
=for code :lang<python>
for i in range(10):
if i == 3:
continue
if i == 5:
break
print i
Perl 6
for ^10 -> $i {
next if $i == 3;
last if $i == 5;
say $i;
}
Using C<if> as a statement modifier (as above) is acceptable
in Perl 6, even outside of a list comprehension.
The C<yield> statement within a C<for> loop in Python, which produces a
C<generator>, is like a C<gather>/C<take> construct in Perl 6. These both print
1, 2, 3.
I<Python>
=begin code :lang<python>
def count():
for i in 1, 2, 3:
yield i
for c in count():
print c
=end code
I<Perl 6>
sub count {
gather {
for 1, 2, 3 -> $i {
take $i
}
}
}
for count() -> $c {
say $c;
}
=head2 X<Lambdas, functions and subroutines|Python>
Declaring a function (subroutine) with C<def> in Python is accomplished
with C<sub> in Perl 6.
=begin code :lang<python>
def add(a, b):
return a + b
sub add(\a, \b) {
return a + b
}
=end code
The C<return> is optional; the value of the last expression is used as
the return value:
=begin code
sub add(\a, \b) {
a + b
}
=end code
=begin code
# using variables with sigils
sub add($a, $b) {
$a + $b
}
=end code
Python 2 functions can be called with positional arguments
or keyword arguments. These are determined by the caller.
In Python 3, some arguments may be "keyword only".
In Perl 6, positional and named arguments are determined
by the signature of the routine.
Python
=begin code :lang<python>
def speak(word, times):
for i in range(times):
print word
speak('hi', 2)
speak(word='hi', times=2)
=end code
Perl 6
Positional parameters:
sub speak($word, $times) {
say $word for ^$times
}
speak('hi', 2);
Named parameters start with a colon:
sub speak(:$word, :$times) {
say $word for ^$times
}
speak(word => 'hi', times => 2);
speak(:word<hi>, :times<2>); # Alternative, more idiomatic
Perl 6 supports multiple dispatch, so several signatures
could be made available by declaring a routine as a C<multi>.
multi sub speak($word, $times) {
say $word for ^$times
}
multi sub speak(:$word, :$times) {
speak($word, $times);
}
speak('hi', 2);
speak(:word<hi>, :times<2>);
Named parameters can be sent using a variety of formats:
sub hello {...};
# all the same
hello(name => 'world'); # fat arrow syntax
hello(:name('world')); # pair constructor
hello :name<world>; # <> quotes words and makes a list
my $name = 'world';
hello(:$name); # lexical var with the same name
Creating an anonymous function can be done with C<sub>, with a block or with
a pointy block.
Python
=for code :lang<python>
square = lambda x: x ** 2
Perl 6
my $square = sub ($x) { $x ** 2 }; # anonymous sub
my $square = -> $x { $x ** 2 }; # pointy block
my $square = { $^x ** 2 }; # placeholder variable
my $square = { $_ ** 2 }; # topic variable
Placeholder variables are lexicographically ordered to form positional parameters.
i.e. these are the same:
my $power = { $^x ** $^y };
my $power = -> $x, $y { $x ** $y };
=head2 X<List comprehensions|Python>
Postfix statement modifiers and blocks can be combined to make list
comprehensions.
Python
=for code :lang<python>
print [ i * 2 for i in 3, 9 ] # OUTPUT: «[6, 18]»
Perl 6
say ( $_ * 2 for 3, 9 ); # OUTPUT: «(6 18)»
say ( { $^i * 2 } for 3, 9 ); # OUTPUT: «(6 18)»
say ( -> \i { i * 2 } for 3, 9 ); # OUTPUT: «(6 18)»
Conditionals can be applied, but the C<if> comes first,
unlike in Python where the if comes second.
=for code :lang<python>
print [ x * 2 for x in 1, 2, 3 if x > 1 ] # OUTPUT: «[4, 6]»
vs
say ( $_ * 2 if $_ > 1 for 1, 2, 3 ); # OUTPUT: «(4 6)»
For nested loops, the cross product operator C<X>
will help:
=for code :lang<python>
print [ i + j for i in 3,9 for j in 2,10 ] # OUTPUT: «[5, 13, 11, 19]»
becomes either of these:
say ( { $_[0] + $_[1] } for (3,9) X (2,10) ); # OUTPUT: «(5 13 11 19)»
say ( -> (\i, \j) { i + j } for (3,9) X (2,10) ); # OUTPUT: «(5 13 11 19)»
Using C<map> (which is just like Python's C<map>) and
C<grep> (which is like Python's C<filter>) is an alternative.
=head2 X<Classes and objects|Python>
Here's an example from the Python
L<docs|https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables>.
First, "instance variables", aka attributes in Perl 6:
Python:
=for code :lang<python>
class Dog:
def __init__(self, name):
self.name = name
Perl 6:
class Dog {
has $.name;
}
Constructors by default take named arguments in Perl 6,
and use the method C<new>.
Python:
=for code :lang<python>
d = Dog('Fido')
e = Dog('Buddy')
print d.name
print e.name
Perl 6
class Dog {}; ...;
my $d = Dog.new(:name<Fido>);
my $e = Dog.new(:name<Buddy>);
say $d.name;
say $e.name;
Class attributes in Perl 6 can be declared in a few ways. One way
is to just declare a lexical variable and a method for accessing it.
Python:
=for code :lang<python>
class Dog:
kind = 'canine' # class attribute
def __init__(self, name):
self.name = name # instance attribute
d = Dog('Fido')
e = Dog('Buddy')
print d.kind
print e.kind
print d.name
print e.name
Perl 6:
class Dog {
my $kind = 'canine'; # class attribute
method kind { $kind }
has $.name; # instance attribute
}
my $d = Dog.new(:name<Fido>);
my $e = Dog.new(:name<Buddy>);
say $d.kind;
say $e.kind;
say $d.name;
say $e.name;
To mutate attributes, in Perl 6 you"ll want to use C<is rw>:
Python:
=for code :lang<python>
class Dog:
def __init__(self, name):
self.name = name
d = Dog()
d.name = 'rover'
Perl 6:
class Dog {
has $.name is rw;
}
my $d = Dog.new;
$d.name = 'rover';
Inheritance is done using C<is>:
Python
=begin code :lang<python>
class Animal:
def jump(self):
print ("I am jumping")
class Dog(Animal):
pass
d = Dog()
d.jump()
=end code
Perl 6
class Animal {
method jump {
say "I am jumping"
}
}
class Dog is Animal {
}
my $d = Dog.new;
$d.jump;
Multiple inheritance is possible by using C<is> multiple times, or with C<also>.
Python
=for code :lang<python>
class Dog(Animal, Friend, Pet):
pass
Perl 6
class Animal {}; class Friend {}; class Pet {};
...;
class Dog is Animal is Friend is Pet {};
or
class Animal {}; class Friend {}; class Pet {};
...;
class Dog is Animal {
also is Friend;
also is Pet;
...
}
=head2 X<Decorators|Python>
Decorators in Python are a way of wrapping a function
in another one. In Perl 6, this is done with C<wrap>.
Python
=begin code :lang<python>
def greeter(f):
def new():
print 'hello'
f()
return new
@greeter
def world():
print 'world'
world();
=end code
Perl 6
sub world {
say 'world'
}
&world.wrap(sub () {
say 'hello';
callsame;
});
world;
An alternative would be to use a trait:
# declare the trait 'greeter'
multi sub trait_mod:<is>(Routine $r, :$greeter) {
$r.wrap(sub {
say 'hello';
callsame;
})
}
sub world is greeter {
say 'world';
}
world;
=head2 X<Context managers|Python>
Context managers in Python declare actions that happen when entering
or exiting a scope.
Here's a Python context manager that prints the strings
'hello', 'world', and 'bye'.
=begin code :lang<python>
class hello:
def __exit__(self, type, value, traceback):
print 'bye'
def __enter__(self):
print 'hello'
with hello():
print 'world'
=end code
For "enter" and "exit" events, passing a block as
an argument would be one option:
sub hello(Block $b) {
say 'hello';
$b();
say 'bye';
}
hello {
say 'world';
}
A related idea is 'L<Phasers|/language/phasers>' which may be set up to
run on entering or leaving a block.
{
LEAVE say 'bye';
ENTER say 'hello';
say 'world';
}
=head2 X<C<input>|Python>
In Python 3, the C<input> keyword is used to prompt the user. C<input> can be
provided with an optional argument which is written to standard output without
a trailing newline:
=begin code :lang<python>
user_input = input("Say hi → ")
print(user_input)
=end code
When prompted, you can enter C<Hi> or any other string, which will be stored
in the C<user_input> variable. This is similar to L<prompt> in Perl 6:
my $user_input = prompt("Say hi → ");
say $user_input; # OUTPUT: whatever you entered.
=end pod
# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6