Arr*_*rrr 14 python list-comprehension nim-lang
由于Nim与Python共享许多功能,如果它也实现了Python的列表理解,我也不会感到惊讶:
string = "Hello 12345 World"
numbers = [x for x in string if x.isdigit()]
# ['1', '2', '3', '4', '5']
Run Code Online (Sandbox Code Playgroud)
这在Nim实际上是否可行?如果没有,可以用模板/宏实现吗?
blu*_*e10 15
列表理解已在Nim中实现,但目前仍在sugar包中(即,您必须import sugar).它被实现为一个被调用的宏,lc并允许编写这样的列表推导:
lc[x | (x <- 1..10, x mod 2 == 0), int]
lc[(x,y,z) | (x <- 1..n, y <- x..n, z <- y..n, x*x + y*y == z*z), tuple[a,b,c: int]]
Run Code Online (Sandbox Code Playgroud)
请注意,宏需要指定元素的类型.
根据rosettacode,Nim没有列表推导,但它们可以通过元编程创建.
[编辑]
正如bluenote10所指出的,列表推导现在是未来模块的一部分:
import future
var str = "Hello 12345 World"
echo lc[x | (x <- str, ord(x) - ord('0') in 0..9), char]
Run Code Online (Sandbox Code Playgroud)
上面的代码段产生了 @[1, 2, 3, 4, 5]
原来的
import sugar
let items = collect(newSeq):
for x in @[1, 2, 3]: x * 2
echo items
Run Code Online (Sandbox Code Playgroud)
输出@[2, 4, 6]
更新以回答问题
import sugar
import sequtils
import strutils
let numbers = collect: # collect from suger
for x in "Hello 12345 World".toSeq: # toSeq from sequtils
if x.isDigit: # isDigit from strutils
x
echo numbers
Run Code Online (Sandbox Code Playgroud)
输出@['1', '2', '3', '4', '5']