diff --git a/docs/language/core.rst b/docs/language/core.rst index b2e4e3e..deaf16b 100644 --- a/docs/language/core.rst +++ b/docs/language/core.rst @@ -6,6 +6,29 @@ Hy Core Core Functions =============== +.. _is-coll-fn: + +coll? +---- + +.. versionadded:: 0.9.13 + +Usage: ``(coll? x)`` + +Returns true if argument is iterable and not a string. + +.. code-block:: clojure + + => (coll? [1 2 3 4]) + True + + => (coll? {"a" 1 "b" 2}) + True + + => (coll? "abc") + False + + .. _dec-fn: dec diff --git a/hy/core/language.hy b/hy/core/language.hy index 8fcb615..0ccd3c6 100644 --- a/hy/core/language.hy +++ b/hy/core/language.hy @@ -30,6 +30,10 @@ (if (not (numeric? x)) (raise (TypeError (.format "{0!r} is not a number" x))))) +(defn coll? [coll] + "Checks whether item is a collection" + (and (iterable? coll) (not (string? coll)))) + (defn cycle [coll] "Yield an infinite repetition of the items in coll" (setv seen []) @@ -112,7 +116,7 @@ (defn flatten [coll] "Return a single flat list expanding all members of coll" - (if (and (iterable? coll) (not (string? coll))) + (if (coll? coll) (_flatten coll []) (raise (TypeError (.format "{0!r} is not a collection" coll))))) @@ -298,8 +302,8 @@ (_numeric_check n) (= n 0)) -(def *exports* '[calling-module-name cycle dec distinct disassemble drop - drop-while empty? even? filter flatten float? gensym +(def *exports* '[calling-module-name coll? cycle dec distinct disassemble + drop drop-while empty? even? filter flatten float? gensym inc instance? integer integer? iterable? iterate iterator? macroexpand macroexpand-1 neg? nil? none? nth numeric? odd? pos? remove repeat repeatedly second diff --git a/tests/native_tests/core.hy b/tests/native_tests/core.hy index 1427187..db2c9e5 100644 --- a/tests/native_tests/core.hy +++ b/tests/native_tests/core.hy @@ -30,6 +30,14 @@ (defn assert-equal [x y] (assert (= x y))) +(defn test-coll? [] + "NATIVE: testing coll?" + (assert-true (coll? [1 2 3])) + (assert-true (coll? {"a" 1 "b" 2})) + (assert-true (coll? (range 10))) + (assert-false (coll? "abc")) + (assert-false (coll? 1))) + (defn test-cycle [] "NATIVE: testing cycle" (assert-equal (list (cycle [])) [])