Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between mapcat in Clojure and flatMap in Scala in terms of what they operate on?

Tags:

scala

clojure

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:

  • I understand that Scala has a rich type system and Clojure has optional typing - I'm interested to know if the is a limitation in the parameters that mapcat accepts that make it only have a subset of flatMaps functionality.
like image 274
hawkeye Avatar asked Dec 03 '13 22:12

hawkeye


People also ask

What is difference between MAP and flatMap in Scala?

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.

What is flatMap in Scala?

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.

When to use map vs flatMap Scala?

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.


1 Answers

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.

like image 193
Arthur Ulfeldt Avatar answered Sep 29 '22 02:09

Arthur Ulfeldt