Perl 6 中的列表解析
Posted YoungForPerl6
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Perl 6 中的列表解析相关的知识,希望对你有一定的参考价值。
Perl 6 中的列表解析
看一看 Python 中关于列表推导的页面。
S = {x² : x in {0 ... 9}}
V = (1, 2, 4, 8, ..., 2¹²)
M = {x | x in S and x even}
Python 列表解析:
S = [x**2 for x in range(10)]
V = [2**i for i in range(13)]
M = [x for x in S if x % 2 == 0]
在原始定义中我没有看到 10 或 13 , Perl 6 与原始语言最接近的语法是:
my \S = ($_² for 0 ... 9);
my \V = (1, 2, 4, 8 ... 2¹²); # almost identical
my \M = ($_ if $_ %% 2 for S);
Perl 6 与 Python 最接近的语法是:
my \S = [-> \x { x**2 } for ^10];
my \V = [-> \i { 2**i } for ^13];
my \M = [-> \x { x if x % 2 == 0 } for S];
Perl 6 更惯用的语法是:
my \S = (0..9)»²;
my \V = 1, 2, 4 ... 2¹²;
my \M = S.grep: * %% 2;
具有无限序列的 Perl 6:
my \S = (0..*).map: *²;
my \V = 1, 2, 4 ... *;
my \M = S.grep: * %% 2;
Python
string = 'The quick brown fox jumps over the lazy dog'
words = string.split()
stuff = [[w.upper(), w.lower(), len(w)] for w in words]
Perl 6
my \string = 'The quick brown fox jumps over the lazy dog';
my \words = string.words;
my \stuff = [[.uc, .lc, .chars] for words]
这里有一些使用 Set 运算符的其他翻译
primes = [x for x in range(2, 50) if x not in noprimes] # python
my \primes = (2..^50).grep: * ∉ noprimes;
my \prime-set = 2..^50 (-) noprimes; # a Set object
my \primes = prime-set.keys.sort;
另外我相当确定 Python 没有在 Supply 上并发地使用它们的方法。
# create a prime supply and act on it in the background
Supply.interval(1).grep(*.is-prime).act: &say;
say 'main thread still running';
# says 'main thread still running' immediately
# deadlock main thread,
# otherwise the program would terminate
await Promise.new;
# waits 2 seconds from the .act call, says 2
# waits 1 second , says 3
# waits 2 seconds, says 5
# waits 2 seconds, says 7
# waits 4 seconds, says 11
# and so on until it is terminated
以上是关于Perl 6 中的列表解析的主要内容,如果未能解决你的问题,请参考以下文章