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

后端 未结 4 1321
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 14:13

I understand the equivalent to flatMap in Scala is mapcat in Clojure.

I have an inkling that mapcat in clojure only works with sequences, unli

4条回答
  •  Happy的楠姐
    2021-02-08 14:44

    I know a little about Scala but it seems to me flatMap is the Scala bind function in a monad and mapcat is a possible implementation of the bind function for the sequence monad in Clojure. So they are the same for sequences.

    But Scala for example has a flatMap function for Futures: it takes a future and a mapping function and returns a future that will complete after input future completes. This operation doesn't seem to be a simple mapcat in Clojure. It may be realized this way instead

    (defn flat-map [f mv] (mapcat (fn [v] (future (f @v))) mv))
    

    So, no. They are not the same, neither in terms of what they operate on. In Scala flatMap is the common name for different functions and for example Futures' flatMap coordinates input and output futures. A simple mapcat in Clojure won't work because it won't return a future.

提交回复
热议问题