pythonoperatorsocamlmodulo

OCaml mod function returns different result compared with %


The modulo function in OCaml mod return results different when compared with the modulo operator in python.

OCaml:

# -1 mod 4
- : int = -1

Python:

>>> -1 % 4
3

Why are the result different?.

Is there any standard module function that operate as % in OCaml?.


Solution

  • Python is a bit different in its usage of the % operator, which really computes the modulo of two values, whereas other programming languages compute the remainder with the same operator. For example, the distinction is clear in Scheme:

    (modulo -1 4)    ; modulo
    => 3
    (remainder -1 4) ; remainder
    => -1
    

    In Python:

    -1 % 4           # modulo
    => 3
    math.fmod(-1, 4) # remainder
    => -1
    

    But in OCaml, there's only mod (which computes the integer remainder), according to this table and as stated in the documentation:

    -1 mod 4 (* remainder *)
    => -1
    

    Of course, you can implement your own modulo operation in terms of remainder, like this:

    let modulo x y =
      let result = x mod y in
      if result >= 0 then result
      else result + y