简体   繁体   中英

Nim equivalent of Python's list comprehension

Since Nim shares a lot of features with Python, i would not be surprised if it implements Python's list comprehension too:

string = "Hello 12345 World"
numbers = [x for x in string if x.isdigit()]
# ['1', '2', '3', '4', '5']

Is this actually possible in Nim? If not, could be implemented with templates/macros ?

UPDATE: List comprehension has been deprecated since version 0.19.9 ( Source ). A good alternative is to use the new sugar.collect macro .


List comprehension is implemented in Nim in the sugar package (ie, you have to import sugar ). It is implemented as a macro called lc and allows to write list comprehensions like this:

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]]

Note that the macro requires to specify the type of the elements.

According to rosettacode , Nim has no list comprehensions, but they can be created through metaprogramming .

[EDIT]

As pointed out by bluenote10, list comprehensions are now part of the future module :

import future
var str = "Hello 12345 World"
echo lc[x | (x <- str, ord(x) - ord('0') in 0..9),  char]

The above snippet yields @[1, 2, 3, 4, 5]

Original

import sugar

let items = collect(newSeq):
  for x in @[1, 2, 3]: x * 2

echo items

outputs @[2, 4, 6]

Updated to answer question

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

outputs @['1', '2', '3', '4', '5']

Nim translation of your code:

import sugar, strutils
var str = "Hello 12345 World"
echo collect(for s in str:
  if s.isDigit(): s)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM