nim-lang / website

Code for the official Nim programming language website
https://nim-lang.org
Other
115 stars 78 forks source link

Nim homepage -- weak macro example #163

Open StefanSalewski opened 5 years ago

StefanSalewski commented 5 years ago

On Homepage we have

import macros, strutils

macro toLookupTable(data: static[string]): untyped =
  result = newTree(nnkBracket)
  for w in data.split(';'):
    result.add newLit(w)

const
  data = "mov;btc;cli;xor"
  opcodes = toLookupTable(data)

for o in opcodes:
  echo o

I can't see its benefit with current Nim, as this codes seems to do the same:

import strutils
const
  data = "mov;btc;cli;xor"
  opcodes = data.split(';')
for o in opcodes:
  echo o
SolitudeSF commented 5 years ago

macro produces an array, not sequence

but yes, it does look only marginally useful, and doesnt look useful at all if youre not familiar with language.

StefanSalewski commented 5 years ago

Ah thanks. But I would still like to have a better macro example on front page.

narimiran commented 5 years ago

Ok, any suggestions for a better (while still relatively small) macro example?

StefanSalewski commented 5 years ago

I think there are many, maybe the macro experts like mratsim or Arne can name a few. The myAssert() from tut3 is not bad, and one that I liked was for on the fly enum generation from https://forum.nim-lang.org/t/5052#31714

StefanSalewski commented 5 years ago

And I like the splat() for tuples of Mr Felsing, second post in

https://stackoverflow.com/questions/48418386/tuple-to-function-arguments-in-nim

Maybe not so nice as the prefix * in Ruby, but macro is short and useful.

metagn commented 4 years ago

I was just thinking, giving an example of a template is probably more welcoming than an example of a macro. Seeing macros first will make one think Nim's metaprogramming is needlessly complicated where it doesn't have to be. Maybe something like:

import times

template bench(body: untyped) =
  let startTime = cpuTime()
  body
  let endTime = cpuTime()
  echo "took ", endTime - startTime, " seconds"

bench:
  var sum = 0
  for i in 1..1000000:
    sum += i
  echo sum

Of course there would be comments, and I'm sure someone can think of a better example. It is important IMO that templates are shown off first though.