Skip to content

Instantly share code, notes, and snippets.

@flyx

flyx/test1.nim Secret

Last active April 24, 2017 14:55
Show Gist options
  • Save flyx/0c98d205c96c84279ce2ae4f20a8225f to your computer and use it in GitHub Desktop.
Save flyx/0c98d205c96c84279ce2ae4f20a8225f to your computer and use it in GitHub Desktop.
import macros
macro optRepeat{repeat(value, num)}(value: untyped, num: static[int]): untyped =
echo "static repeat called"
result = newNimNode(nnkBracket)
for i in 1..num:
result.add(value)
proc repeat[T](value: T, num: int): seq[T] =
echo "dynamic repeat called"
result = newSeqOfCap[T](num)
for i in 0..<num:
result.add(value)
var myArr = [1, 2, 3, 4, 5, 6]
var a = 3
myArr[0..1] = repeat(42, 2)
myArr[3..5] = repeat(42, a)
echo @myArr
@Araq
Copy link

Araq commented Apr 24, 2017

import macros

macro optRepeat{repeat(value, num)}(value: untyped, num: int{lit}): untyped =
  echo "static repeat called"
  result = newNimNode(nnkBracket)
  for i in 1..num.intVal:
    result.add(value)

proc repeat[T](value: T, num: int): seq[T] =
  echo "dynamic repeat called"
  result = newSeqOfCap[T](num)
  for i in 0..<num:
    result.add(value)

var myArr = [1, 2, 3, 4, 5, 6]
var a = 3

myArr[0..1] = repeat(42, 2)
myArr[3..5] = repeat(42, a)

echo @myArr

@Araq
Copy link

Araq commented Apr 24, 2017

macro optRepeat{`[]=`(x, `..`(a, b)) = repeat(value, num)}(x, a, b, value: untyped, num: int{lit}): untyped =
  echo "static repeat called"
  result = newNimNode(nnkStmtList)
  template singleAsgn(x, a, i, val) =
    x[a+i] = val
  for i in 1..num.intVal:
    result.add(getAst singleAsgn(x, a, newLit i, value))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment