List comprehensions: Difference between revisions

Content added Content deleted
(→‎{{header|Nim}}: Add example using collect())
(Updates example with macros to compile with Nim version 1.4.)
Line 1,586: Line 1,586:
var lc*: ListComprehension
var lc*: ListComprehension


macro `[]`*(lc: ListComprehension, x, t): expr =
macro `[]`*(lc: ListComprehension, x, t): untyped =
expectLen(x, 3)
expectLen(x, 3)
expectKind(x, nnkInfix)
expectKind(x, nnkInfix)
expectKind(x[0], nnkIdent)
expectKind(x[0], nnkIdent)
assert($x[0].ident == "|")
assert($x[0].strVal == "|")


result = newCall(
result = newCall(
Line 1,602: Line 1,602:
expectKind(y, nnkInfix)
expectKind(y, nnkInfix)
expectMinLen(y, 1)
expectMinLen(y, 1)
if y[0].kind == nnkIdent and $y[0].ident == "<-":
if y[0].kind == nnkIdent and $y[0].strVal == "<-":
expectLen(y, 3)
expectLen(y, 3)
result = newNimNode(nnkForStmt).add(y[1], y[2], result)
result = newNimNode(nnkForStmt).add(y[1], y[2], result)
Line 1,629: Line 1,629:


const n = 20
const n = 20
echo lc[(x,y,z) | (x <- 1..n, y <- x..n, z <- y..n, x*x + y*y == z*z),
echo lc[(x,y,z) | (x <- 1..n, y <- x..n, z <- y..n, x*x + y*y == z*z), tuple[a,b,c: int]]</lang>
tuple[a,b,c: int]]</lang>
Output:
Output:
<pre>@[(a: 3, b: 4, c: 5), (a: 5, b: 12, c: 13), (a: 6, b: 8, c: 10), (a: 8, b: 15, c: 17), (a: 9, b: 12, c: 15), (a: 12, b: 16, c: 20)]</pre>
<pre>@[(a: 3, b: 4, c: 5), (a: 5, b: 12, c: 13), (a: 6, b: 8, c: 10), (a: 8, b: 15, c: 17), (a: 9, b: 12, c: 15), (a: 12, b: 16, c: 20)]</pre>