How to mark non-pure function as pure in Nim

Viewed 219

Is there a way to mark non-pure function p as pure? Maybe with some pragma?

I'm using p for debug, and it can't be used inside pure func procs.

playground

proc p(message: string): void = echo message

func purefn: void =
  p "track"
  
purefn()

Error:

/usercode/in.nim(3, 6) Error: 'purefn' can have side effects
2 Answers

Well, for a start you can just use debugEcho instead of echo - it has no side effects (and it's specifically made for use-cases like that).

In other cases you can "lie" to the compiler by doing:

proc p(message: string) = 
  {.cast(noSideEffect).}:
    echo message

func purefn =
  p "track"
  
purefn()

as described in https://nim-lang.org/docs/manual.html#pragmas-nosideeffect-pragma, but I would advise against it.

For your case, you can use debugEcho inside of echo which fakes having no side effects.

Other than that, you can use the {.cast(noSideEffect).} pragma if you're not using echo in your real code:

proc p(message: string): void = echo message

func purefn: void =
  {.cast(noSideEffect).}:
    p "track"
  
purefn()
Related