I'm trying to solve a little problem I have. I have a function myFunction(paramA: int, paramB: float): int that calculates something. In some situation I want to get additional information from inside this calculation like this: myFunction(paramA: int, paramB: float, info: var Info): int. Because this is performance sensitive I want the additional code for writing stuff into info: var Info only there when I need it.
My idea was something like this:
import math
type Info = object
importantInfo: bool
alsoImportant: float
type Nothing = enum nothing
type InfoOrNothing = Info or Nothing
var v: Nothing
proc myFunction(paramA: int, paramB: float, info: var InfoOrNothing = v): int =
result = paramA mod 10
when info is Info:
info.importantInfo = result mod 2 == 0
result = sqrt(result.float * paramB).int
when info is Info:
info.alsoImportant = result.float * paramB
# normal use (faster):
echo myFunction(paramA = 120, paramB = 0.5)
# use with additional info
var info: Info
echo myFunction(paramA = 120, paramB = 0.5, info)
echo info
Unfortunately this doesn't work:
/usercode/in.nim(22, 16) template/generic instantiation of `myFunction` from here
/usercode/in.nim(11, 45) Error: cannot instantiate: 'InfoOrNothing'
But this works, so I am wondering if there is a simple workaround for the first example:
import math
type Info = object
importantInfo: bool
alsoImportant: float
type Nothing = enum nothing
type InfoOrNothing = Info or Nothing
var v: Nothing
proc myFunction(paramA: int, paramB: float, info: InfoOrNothing = v): int =
result = paramA mod 10
when info is Info:
debugEcho "info.importantInfo = result mod 2 == 0"
result = sqrt(result.float * paramB).int
when info is Info:
debugEcho "info.alsoImportant = result.float * paramB"
# normal use (faster):
echo myFunction(paramA = 120, paramB = 0.5)
# use with additional info
var info: Info
echo myFunction(paramA = 120, paramB = 0.5, info)
echo info
For default arguments, there is always a workaround:
var v: Nothing
proc myFunction(paramA: int, paramB: float, info: var InfoOrNothing): int =
...
proc myFunction(paramA: int, paramB: float): int =
myFunction(paramA, paramB, v)