How to use flat map in Clojure and Scala

Flat map is an operation that first map then flat the result. Flat simply removes one level of nesting.

In Clojure

 
(defn foo [l]
  (> l 0)
)
 
(mapcat #(filter foo %) '((-1 0 2 3) (1 0 -2 3)))
(flatten (map #(filter foo %) '((-1 0 2 3) (1 0 -2 3))))
 
 
user> (map #(filter foo %) '((-1 0 2 3) (1 0 -2 3)))
((2 3) (1 3))
 
user> (flatten (map #(filter foo %) '((-1 0 2 3) (1 0 -2 3))))
(2 3 1 3)
 

In Scala

 
object HelloWorld {
    def main(args: Array[String]) {
        println("Hello Scala!")
        val l = 1 :: 2 :: 3 :: Nil
        println(l.map(_ :: 2 :: Nil))
        println(l.flatMap(_ :: 2 :: Nil))        
    }
}
 
 
Hello Scala!
List(List(1, 2), List(2, 2), List(3, 2))
List(1, 2, 2, 2, 3, 2)