I understand the equivalent to flatMap
in Scala is mapcat
in Clojure.
I have an inkling that mapcat
in clojure only works with sequences, unlike flatMap
in Scala which is more flexible.
My question is - what are the differences between mapcat
in Clojure and flatMap
in Scala in terms of what they operate on?
Assumptions:
flatMap
s functionality. In Scala, flatMap() method is identical to the map() method, but the only difference is that in flatMap the inner grouping of an item is removed and a sequence is generated. It can be defined as a blend of map method and flatten method.
flatMap() method is method of TraversableLike trait, it takes a predicate, applies it to each element of the collection and returns a new collection of elements returned by the predicate.
The flatMap() method is similar to the map() method, but the only difference is that in flatMap, the inner grouping of an item is removed and a sequence is generated. The flatMap method acts as a shorthand to map a collection and then immediately flatten it.
They seem very similar and appear to work on the same kind of things. From looking at the documentation and examples I can't see a functional difference.
mapcat
works on sequences, and just about every clojure data type can be a sequence. If you pass something that is not already a seq
to mapcat
it will call seq on it automatically, so in practice you can pass just about all clojure values to mapcat. If you want to iterate over a tree you would need to call prewalk
or postwalk
to specify the traversal order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With