There is no error with the following code.
import math
echo 2^2
However, the following code will raise an error as type mismatch,
import math
echo 2^2*2.0
I try to fix this problem using flowing code,
import math
echo float(2^2)*2.0
But the above solution is very unelegant, is there a better solution?
Nim is statically typed, meaning it checked at compile-time that you are not mixing apples and oranges unless you specifically allows that.
That is because mixing types (integers and booleans, floats and integers) or quantities (miles and meters) is a big source of bugs in weakly typed languages.
You can import the lenientops module if you want less strict math operators:
import math, lenientops
echo 2^2*2.0
To add to mratsim answer, you can also write:
import math
echo 2.0^2 * 2.0
and even:
import math
echo 2.0^2 * 2
In the latter code, the compiler convert 2 to 2.0 as it knows that a float is expected. So, there is some flexibility though.
I think that this is the best solution, and it just so happens to be consistent other languages (Java and Kotlin come to mind).
import math
echo 2f^2*2.0
You could even do this:
import math
echo 2f^2*2
However, the following code will raise an error as type mismatch...
It is a type mismatch, so, good. I've had it with languages whose solution for easily preventable errors is Segmentation fault or Bus error, especially when those errors could be caught at compile time.