/
02.05.2025 at 10:05 pm
Cuttings

Nim / Exercise - Make an `info(expr)` macro

Get familiar witjh `quote do`.

info(3 + 4)


Output: type: int, value: 7

Hint:

  • Use typeof on `expr`.
  • Combine echo, astToStr, and type introspection.
  1. There's a difference between calling a function vs calling a macro. The parentheses syntax makes them feel the same, but they're not.

  2. You can echo the expression back from the macro.

Code (SolutiON)
     macro info(expr: untyped): untyped =
  result = quote do:
    echo astToStr(`expr`), " =", `expr`
    echo "type: ", typeof(`expr`), ", value: ", `expr`

#  Test cases

let n = 42
info(n + 1)

let word = "hi there"
info(word.len)

info(3.14 * 2)

                    
Filed under:
#
Words: 46 words approx.
Time to read: 0.18 mins (at 250 wpm)
Keywords:
, , , , , , , , ,

Latest Comments

© Wan Zafran. See disclaimer.