Skip to content

Commit 2e864d9

Browse files
authored
baislisp.core/count should return 0 on nil input (#760)
Hi, could you please review fix for `(count nil)` to return 0. Fixes #759. Rudimentary tests added for `count`. Thanks Co-authored-by: ikappaki <[email protected]>
1 parent 85ffd66 commit 2e864d9

File tree

4 files changed

+25
-10
lines changed

4 files changed

+25
-10
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
66

77
## [Unreleased]
88

9+
### Fixed
10+
* Fix issue with `(count nil)` throwing an exception (#759).
11+
912
## [v0.1.0b0]
1013
### Added
1114
* Added rudimentary support for `clojure.stacktrace` with `print-cause-trace` (part of #721)

src/basilisp/core.lpy

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -265,8 +265,9 @@
265265
;;;;;;;;;;;; full support for syntax quote begins here ;;;;;;;;;;;;
266266

267267
(def
268-
^{:doc "Return the length of ``coll`` as by Python's ``len`` builtin. If the
269-
collection does not respond to ``__len__``\\, then count it manually."
268+
^{:doc "Return the length of ``coll`` as by Python's ``len`` builtin, or 0 if
269+
``coll`` is nil. If the collection does not respond to ``__len__``\\,
270+
then count it manually."
270271
:arglists '([coll])
271272
:inline true}
272273
count

src/basilisp/lang/runtime.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1115,15 +1115,18 @@ def apply_kw(f, args):
11151115

11161116

11171117
def count(coll) -> int:
1118-
try:
1119-
return len(coll)
1120-
except (AttributeError, TypeError):
1118+
if coll is None:
1119+
return 0
1120+
else:
11211121
try:
1122-
return sum(1 for _ in coll)
1123-
except TypeError as e:
1124-
raise TypeError(
1125-
f"count not supported on object of type {type(coll)}"
1126-
) from e
1122+
return len(coll)
1123+
except (AttributeError, TypeError):
1124+
try:
1125+
return sum(1 for _ in coll)
1126+
except TypeError as e:
1127+
raise TypeError(
1128+
f"count not supported on object of type {type(coll)}"
1129+
) from e
11271130

11281131

11291132
__nth_sentinel = object()

tests/basilisp/runtime_test.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,14 @@ def test_apply():
260260
)
261261

262262

263+
def test_count():
264+
assert 0 == runtime.count(None)
265+
assert 0 == runtime.count(vec.v())
266+
assert 0 == runtime.count("")
267+
assert 3 == runtime.count(vec.v(1, 2, 3))
268+
assert 3 == runtime.count("123")
269+
270+
263271
def test_nth():
264272
assert None is runtime.nth(None, 1)
265273
assert "not found" == runtime.nth(None, 4, "not found")

0 commit comments

Comments
 (0)