Re:Learning Clojure: comparing with Java streams
by Sharlin on Sunday November 04, 2018 @06:39PM
(#18378692)
Thanks, I wasn’t aware that flatten is recursive.
Re:Learning Clojure: comparing with Java streams
by TeMPOraL on Monday November 05, 2018 @03:07AM
(#18380666)
That's sort of implied by the name. A non-recursive flatten wouldn't really flatten much, and would be called join, or concatenate.
Re:Learning Clojure: comparing with Java streams
by Sharlin on Monday November 05, 2018 @06:22AM
(#18381457)
The flatten functions I know from statically typed languages (eg. Rust, Scala) only flatten one level. So flatMap is actually more or less equivalent to (flatten . map).
Re:Learning Clojure: comparing with Java streams
by TeMPOraL on Monday November 05, 2018 @07:52AM
(#18381880)
Interesting. My experience is the opposite - in dynamically typed languages like Erlang, Clojure or Common Lisp, flatten is understood to flatten lists, and flatmap is something else entirely - from what I gather, it's Scala that made the weird choice of naming a concatenation function `flatten`, thus creating `flatMap`[0], and then people started borrowing the name.
From this I provisionally conclude that "flatten" being non-recursive is an artifact of Scala confusing things; not an unusual thing in my experience with this language, but this time it seems to have gotten out of hand, instead of being contained within Scala ecosystem.
--
[0] - Even Haskell calls this `concatMap`, see [1].
[1] - https://stackoverflow.com/questions/49843262/where-does-the-...
With the caveat that `flatten` is recursive and can handle a mix of collections and non-collections, while `mapcat` is non-recursive and every value returned by the mapcatted function must be a collection or nil.
(Identity returns its argument.)