Raku 中的列表解析

list comprehension in Raku

Raku 中的列表解析

看一看 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 , Raku 与原始语言最接近的语法是:

my \S = ($_² for 0 ... 9);
my \V = (1, 2, 4, 8 ... 2¹²); # almost identical
my \M = ($_ if $_ %% 2 for S);

Raku 与 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];

Raku 更惯用的语法是:

my \S = (0..9)»²;
my \V = 1, 2, 4 ... 2¹²;
my \M = S.grep: * %% 2;

具有无限序列的 Raku:

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]
  • Raku
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
comments powered by Disqus