Skip to content

Commit

Permalink
baislisp.core/count should return 0 on nil input (#760)
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
ikappaki and ikappaki authored Dec 29, 2023
1 parent 85ffd66 commit 2e864d9
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 10 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed
* Fix issue with `(count nil)` throwing an exception (#759).

## [v0.1.0b0]
### Added
* Added rudimentary support for `clojure.stacktrace` with `print-cause-trace` (part of #721)
Expand Down
5 changes: 3 additions & 2 deletions src/basilisp/core.lpy
Original file line number Diff line number Diff line change
Expand Up @@ -265,8 +265,9 @@
;;;;;;;;;;;; full support for syntax quote begins here ;;;;;;;;;;;;

(def
^{:doc "Return the length of ``coll`` as by Python's ``len`` builtin. If the
collection does not respond to ``__len__``\\, then count it manually."
^{:doc "Return the length of ``coll`` as by Python's ``len`` builtin, or 0 if
``coll`` is nil. If the collection does not respond to ``__len__``\\,
then count it manually."
:arglists '([coll])
:inline true}
count
Expand Down
19 changes: 11 additions & 8 deletions src/basilisp/lang/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1115,15 +1115,18 @@ def apply_kw(f, args):


def count(coll) -> int:
try:
return len(coll)
except (AttributeError, TypeError):
if coll is None:
return 0
else:
try:
return sum(1 for _ in coll)
except TypeError as e:
raise TypeError(
f"count not supported on object of type {type(coll)}"
) from e
return len(coll)
except (AttributeError, TypeError):
try:
return sum(1 for _ in coll)
except TypeError as e:
raise TypeError(
f"count not supported on object of type {type(coll)}"
) from e


__nth_sentinel = object()
Expand Down
8 changes: 8 additions & 0 deletions tests/basilisp/runtime_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,14 @@ def test_apply():
)


def test_count():
assert 0 == runtime.count(None)
assert 0 == runtime.count(vec.v())
assert 0 == runtime.count("")
assert 3 == runtime.count(vec.v(1, 2, 3))
assert 3 == runtime.count("123")


def test_nth():
assert None is runtime.nth(None, 1)
assert "not found" == runtime.nth(None, 4, "not found")
Expand Down

0 comments on commit 2e864d9

Please sign in to comment.