Mark is a graph advocate and field engineer for Neo Technology, the company behind the Neo4j graph database. As a field engineer, Mark helps customers embrace graph data and Neo4j building sophisticated solutions to challenging data problems. When he's not with customers Mark is a developer on Neo4j and writes his experiences of being a graphista on a popular blog at http://markhneedham.com/blog. He tweets at @markhneedham. Mark is a DZone MVB and is not an employee of DZone and has posted 524 posts at DZone. You can read more from them at their website. View Full User Profile

Clojure: Equivalent to Scala’s flatMap/C#’s SelectMany

07.03.2011
| 4459 views |
  • submit to reddit

I’ve been playing around with Clojure a bit over the weekend and one thing I got stuck with was working out how to achieve the functionality provided by Scala’s flatMap or C#’s SelectMany methods on collections.

I had a collection of zip files and wanted to transform that into a collection of all the file entries in those files.

If we just use map then we’ll end up with a collection of collections which is more difficult to deal with going forward.

In Scala we’d do the following:

import scala.collection.JavaConversions._
 
val zip1 = new ZipFile(new File("/Users/mneedham/Documents/my-zip-file.zip"))
val zip2 = new ZipFile(new File("/Users/mneedham/Documents/my-zip-file2.zip"))
 
List(zip1, zip2).flatMap(_.entries)

I was originally make using of map followed by flatten but I learnt from my colleague Phil Calcado that the function I wanted is mapcat which leads to this solution:

(def zip1 (new ZipFile (file "/Users/mneedham/Documents/my-zip-file.zip")))
(def zip2 (new ZipFile (file "/Users/mneedham/Projects/springer/aim/src/test/unit/resources/small_delivery.zip")))
 
(mapcat (fn [file] (enumeration-seq (.entries file))) (list zip1 zip2))

I also learnt about the various functions available to create sequences, such as enumeration-seq from other types which are listed at the bottom of this page.

Scala uses implicit conversions to do that and presumably you’d hide away the conversion in a helper function in Clojure.

From http://www.markhneedham.com/blog/2011/07/03/clojure-equivalent-to-scalas-flatmapcs-selectmany/

Published at DZone with permission of Mark Needham, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Paul Michael Bauer replied on Mon, 2011/07/04 - 12:26am

(mapcat #(enumeration-seq (.entries %)) [zip1 zip2])

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.