3 ms·
The equivalent of `flatMap` is not `flatten`. Semantically `flatMap` is equivalent to `(comp flatten map)` – hence the name! – but Clojure does offer it as a si
by Sharlin 8y ago
The equivalent of `flatMap` is not `flatten`. Semantically `flatMap` is equivalent to `(comp flatten map)` – hence the name! – but Clojure does offer it as a single function named `mapcat` (”map and catenate”).
- jetrink 8y ago> Semantically `flatMap` is equivalent to `(comp flatten map)` 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.) (flatten [1 [2 3] [[4 5 6]]]) > [1 2 3 4 5 6] (mapcat identity [1 [2 3] [[4 5 6]]]) > IllegalArgumentException Don't know how to create ISeq from: java.lang.Long (mapcat identity [[1] [2 3] [[4 5 6]]]) > (1 2 3 [4 5 6]) (flatten [nil [1 2 3]]) > (nil 1 2 3) (mapcat identity [nil [1 2 3]]) > (1 2 3)
- Sharlin 8y agoThanks, I wasn’t aware that flatten is recursive.
- TeMPOraL 8y agoThat's sort of implied by the name. A non-recursive flatten wouldn't really flatten much, and would be called join, or concatenate.
- Sharlin 8y agoThe 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).
- TeMPOraL 8y agoInteresting. 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-word-flatmap-originate-from https://stackoverflow.com/questions/49843262/where-does-the-...
- cgrand-net 8y agoFlatten is a steam-roller and should be used wisely: it recursively flatten a sequential collection. Most of the time this is not what you want. Most of the rest of the time when you think that’s what you want it’s a code smell telling you that the shape of your items has gone out of control. And there’s the rare occurrence where you can really use it.
- Sharlin 8y agoOops, indeed. Didn’t realize that Clojure flatten is recursive.