diff --git a/guppylang/src/guppylang/std/num.py b/guppylang/src/guppylang/std/num.py index 919c2bfaf..74aa85eb4 100644 --- a/guppylang/src/guppylang/std/num.py +++ b/guppylang/src/guppylang/std/num.py @@ -448,8 +448,13 @@ def __rmod__(self: float, other: float) -> float: ... @custom_function(checker=ReversingChecker(), unitary_flags=UnitaryFlags.Dagger) def __rmul__(self: float, other: float) -> float: ... - @hugr_op(float_op("fround"), unitary_flags=UnitaryFlags.Dagger) # TODO - def __round__(self: float) -> float: ... + @hugr_op(float_op("froundeven"), unitary_flags=UnitaryFlags.Dagger) # TODO + def ___round__hugr(self: float) -> float: ... + + @guppy + @no_type_check + def __round__(self: float) -> int: + return int(self.___round__hugr()) @custom_function(checker=ReversingChecker(), unitary_flags=UnitaryFlags.Dagger) def __rpow__(self: float, other: float) -> float: ... diff --git a/tests/integration/test_arithmetic.py b/tests/integration/test_arithmetic.py index ae6a95abd..1c9808896 100644 --- a/tests/integration/test_arithmetic.py +++ b/tests/integration/test_arithmetic.py @@ -405,3 +405,29 @@ def rem() -> int: run_int_fn(quot, -1) run_int_fn(rem, 3) + + +def test_round(run_int_fn, run_float_fn_approx) -> None: + """Asserts that the `round` prelude function behaves like a drop-in replacement for + the Python built-in variant.""" + + @guppy + def int_round() -> int: + return round(1) # noqa: RUF057 + + @guppy + def nat_round() -> int: + return round(nat(2)) + + @guppy + def float_round_tie_down() -> int: + return round(2.5) + + @guppy + def float_round_tie_up() -> int: + return round(3.5) + + run_int_fn(int_round, 1) + run_int_fn(nat_round, 2) + run_int_fn(float_round_tie_down, 2) + run_int_fn(float_round_tie_up, 4)