Skip to content

Commit 8fcc065

Browse files
authored
Fix a bug where integer results of integer division are always returned as fractions (#1141)
Fixes #1140
1 parent e83b059 commit 8fcc065

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1515
* Fix a bug where tags in data readers were resolved as Vars within syntax quotes, rather than using standard data readers rules (#1129)
1616
* Fix a bug where `keyword` and `symbol` functions did not treat string arguments as potentially namespaced (#1131)
1717
* Fix a bug where `condp` would throw an exception if a result expression was `nil` (#1137)
18+
* Fix a bug where integer division which resulted in an integer would return a `fractions.Fraction` (#1140)
1819

1920
## [v0.3.2]
2021
### Added

src/basilisp/lang/runtime.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1655,7 +1655,9 @@ def divide(x: LispNumber, y: LispNumber) -> LispNumber:
16551655
@divide.register(int)
16561656
def _divide_ints(x: int, y: LispNumber) -> LispNumber:
16571657
if isinstance(y, int):
1658-
return Fraction(x, y)
1658+
frac = Fraction(x, y)
1659+
# fractions.Fraction.is_integer() wasn't added until 3.12
1660+
return frac.numerator if frac.denominator == 1 else frac
16591661
return x / y
16601662

16611663

tests/basilisp/runtime_test.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import fractions
12
import platform
23
import sys
34
from decimal import Decimal
@@ -599,6 +600,23 @@ def test_not_equals(v1, v2):
599600
assert not runtime.equals(v2, v1)
600601

601602

603+
@pytest.mark.parametrize(
604+
"v1,v2,expected_result,result_type",
605+
[
606+
(3, 3, 1, int),
607+
(3, 1, 3, int),
608+
(3, 1.001, 3 / 1.001, float),
609+
(3000, 1000, 3, int),
610+
(3000, 1001, fractions.Fraction(3000, 1001), fractions.Fraction),
611+
(3001, 1000, fractions.Fraction(3001, 1000), fractions.Fraction),
612+
],
613+
)
614+
def test_divide(v1, v2, expected_result, result_type):
615+
result = runtime.divide(v1, v2)
616+
assert result == expected_result
617+
assert isinstance(result, result_type)
618+
619+
602620
def test_pop_thread_bindings():
603621
with pytest.raises(runtime.RuntimeException):
604622
runtime.pop_thread_bindings()

0 commit comments

Comments
 (0)