lenientops.nim 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2017 Nim contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module offers implementations of common binary operations
  10. ## like ``+``, ``-``, ``*``, ``/`` and comparison operations,
  11. ## which work for mixed float/int operands.
  12. ## All operations convert the integer operand into the
  13. ## type of the float operand. For numerical expressions, the return
  14. ## type is always the type of the float involved in the expression,
  15. ## i.e., there is no auto conversion from float32 to float64.
  16. ##
  17. ## Note: In general, auto-converting from int to float loses
  18. ## information, which is why these operators live in a separate
  19. ## module. Use with care.
  20. ##
  21. ## Regarding binary comparison, this module only provides unequal operators.
  22. ## The equality operator ``==`` is omitted, because depending on the use case
  23. ## either casting to float or rounding to int might be preferred, and users
  24. ## should make an explicit choice.
  25. proc `+`*[I: SomeInteger, F: SomeFloat](i: I, f: F): F {.noSideEffect, inline.} =
  26. F(i) + f
  27. proc `+`*[I: SomeInteger, F: SomeFloat](f: F, i: I): F {.noSideEffect, inline.} =
  28. f + F(i)
  29. proc `-`*[I: SomeInteger, F: SomeFloat](i: I, f: F): F {.noSideEffect, inline.} =
  30. F(i) - f
  31. proc `-`*[I: SomeInteger, F: SomeFloat](f: F, i: I): F {.noSideEffect, inline.} =
  32. f - F(i)
  33. proc `*`*[I: SomeInteger, F: SomeFloat](i: I, f: F): F {.noSideEffect, inline.} =
  34. F(i) * f
  35. proc `*`*[I: SomeInteger, F: SomeFloat](f: F, i: I): F {.noSideEffect, inline.} =
  36. f * F(i)
  37. proc `/`*[I: SomeInteger, F: SomeFloat](i: I, f: F): F {.noSideEffect, inline.} =
  38. F(i) / f
  39. proc `/`*[I: SomeInteger, F: SomeFloat](f: F, i: I): F {.noSideEffect, inline.} =
  40. f / F(i)
  41. proc `<`*[I: SomeInteger, F: SomeFloat](i: I, f: F): bool {.noSideEffect, inline.} =
  42. F(i) < f
  43. proc `<`*[I: SomeInteger, F: SomeFloat](f: F, i: I): bool {.noSideEffect, inline.} =
  44. f < F(i)
  45. proc `<=`*[I: SomeInteger, F: SomeFloat](i: I, f: F): bool {.noSideEffect, inline.} =
  46. F(i) <= f
  47. proc `<=`*[I: SomeInteger, F: SomeFloat](f: F, i: I): bool {.noSideEffect, inline.} =
  48. f <= F(i)
  49. # Note that we must not defined `>=` and `>`, because system.nim already has a
  50. # template with signature (x, y: untyped): untyped, which would lead to
  51. # ambiguous calls.