Hello,
Is it possible to define a proc based on the fact that a type is defined from an imported module?
Here is an example of what I want to do. Suppose I'm writing a library to help with LaTeX formatting and I want to create a proc $$ to create LaTeX representation of mathematical variables. For instance, if we have let c: Complex = (re: 1.0, im: 2.0) then $$c would create the LaTeX code for printing c as 1 + 2j. Similarly, if m is a Matrix, $$m would create a string with the LaTeX representation of that matrix...
As the Complex type is defined in the standard library and the Matrix one is defined in linalg, it would make sense to have the proc `$$`*(c: Complex): string and proc `$$`*(m: Matrix): string operators defined in these libraries. But not everyone needs to generate LaTeX code fragments, and it would be more sensible to regroup them in a latexutils library.
The problem is now that to compile this latexutils library, it needs to have knowledge of the types Complex and Matrix, if used in the project, and import the corresponding modules. Complex is part of Nim's standard but that's not the case of linalg. Adding support for more type will add strong coupling to external libraries in that file if it add to import all existing maths modules...
So is there a way to write something like:
if module complex is imported in the project:
if type Complex is defined:
proc `$$`*(c: Complex): string =
...
if module linalg is imported in the project:
if type Matrix is defined:
proc `$$`*(m: Matrix): string =
...
This can be done in C where each header file usually define a MYHEADER_H compile time constant and the pre-processor can take actions based on the fact it is defined or not. Is it possible to have a similar behaviour in Nim?
Thanks
This should work
when compiles((var x: Complex; x)):
proc `$$`(x: Complex): string = discard