3

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
Alex Craft
  • 13,598
  • 11
  • 69
  • 133

2 Answers2

5

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.

Optimon
  • 723
  • 1
  • 8
  • 17
4

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()
lqdev
  • 403
  • 3
  • 12