Skip to content

Commit 7bf10ca

Browse files
committed
Edit flatten and its docstring
Returning a non-collection in a singleton list is more consistent behavior. The type check looks unlikely to be useful.
1 parent 903d119 commit 7bf10ca

File tree

3 files changed

+24
-13
lines changed

3 files changed

+24
-13
lines changed

Diff for: NEWS.rst

+2
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ New Features
1313
* New macro `pun`.
1414
* New macro `map-hyseq`.
1515
* `loop` allows more kinds of parameters.
16+
* `flatten`, given a non-collection, returns it as a singleton list,
17+
instead of raising an error.
1618

1719
Bug Fixes
1820
------------------------------

Diff for: hyrule/iterables.hy

+19-9
Original file line numberDiff line numberDiff line change
@@ -52,20 +52,30 @@
5252

5353

5454
(defn flatten [coll]
55-
#[=[Recurisvely collect all the elements and subelements of ``coll`` into a
56-
single list. :hy:func:`coll?` is used to decide whether objects should be
57-
descended into. ::
55+
#[=[Recurisvely collect all the elements and subelements of ``coll``,
56+
depth-first, and return them in a single list. :hy:func:`coll?` is used to
57+
decide whether objects should be descended into. ::
58+
5859

5960
(flatten ["foo" #(1 2) [1 [2 3] 4] "bar"])
60-
; => ["foo" 1 2 1 2 3 4 "bar"]]=]
61-
(if (coll? coll)
62-
(_flatten coll [])
63-
(raise (TypeError (.format "{0!r} is not a collection" coll)))))
61+
; => ["foo" 1 2 1 2 3 4 "bar"]
62+
63+
Since iteration is used to collect the elements of ``coll``, dictionaries
64+
are reduced to lists of keys::
65+
66+
(flatten [{"a" 1 "b" 2} {"c" 3 "d" 4}])
67+
; => ["a" "b" "c" "d"]
68+
69+
If ``coll`` isn't a collection at all, it's returned in a singleton list::
70+
71+
(flatten "hello")
72+
; => ["hello"]]=]
73+
(_flatten coll []))
6474

6575
(defn _flatten [coll result]
6676
(if (coll? coll)
67-
(do (for [b coll]
68-
(_flatten b result)))
77+
(for [x coll]
78+
(_flatten x result))
6979
(.append result coll))
7080
result)
7181

Diff for: tests/test_iterables.hy

+3-4
Original file line numberDiff line numberDiff line change
@@ -63,14 +63,13 @@
6363
(assert (=
6464
(flatten ["foo" #(1 2) [1 [2 3] 4] "bar"])
6565
["foo" 1 2 1 2 3 4 "bar"]))
66+
(assert (= (flatten "foo") ["foo"]))
67+
(assert (= (flatten 12.34) [12.34]))
6668
(assert (= (flatten [1]) [1]))
6769
(assert (= (flatten []) []))
6870
(assert (= (flatten #(1)) [1]))
6971
(assert (= (flatten #(1 #(None 3))) [1 None 3]))
70-
(try (flatten "foo")
71-
(except [e [TypeError]] (assert (in "not a collection" (str e)))))
72-
(try (flatten 12.34)
73-
(except [e [TypeError]] (assert (in "not a collection" (str e))))))
72+
(assert (= (flatten {"a" 1 "b" 2}) ["a" "b"])))
7473

7574

7675
(defn test-rest []

0 commit comments

Comments
 (0)