Scala Create All Paths

Posted on Thursday, June 12, 2014


I was recently talking to a colleague of mine who had been presented a problem from a friend of his.   In Scala take a files path as a string and return all sub paths of that string.

… In other words

Given a path as a String like this


val str:String = "/foo/bar/test/me"



Produce a List that contains


 
"/foo"
"/foo/bar/"
"/foo/bar/test/"
"/foo/bar/test/me/"



My colleague first came up with a nice recursive algorithm and then thought there had to be a better way.   He found a fancy one liner in Scala that worked but I found a little confusing, mostly because I am not familiar with all the cool tools Scala has added to its collection classes.

Looking at his solution forced me to poke around a bit at the List Scala Doc http://www.scala-lang.org/api/current/#scala.collection.immutable.List [1]


I found this function, scanLeft, which according to the documentation

Produces a collection containing cumulative results of applying the operator going left to right.

This allows me to do the following


val str:String = "/foo/bar/test/me"

val dirStructure:List[String] = str.split("/").toList.filter(_.length > 0)
val allFolderPaths:List[String] =
           dirStructure.scanLeft("")((path, dir) => path + "/" + dir).tail.map(_ + "/")


The first part of this simply splits the paths up into individual directory names in a List and removes anything in the List with no text.  This is required because of the way split works.

The second part scans the list from left to right and replaces each element as it goes along.  As it traverses the list it passes along the value of the last updated item in the List.   This creates all sub paths.  But the subpaths now lack a final “/” at the end which .map(_ + "/") provides.

Anyone else have a different solution to this problem?  Please post it.


References
[1]        Scala Doc List

                Accessed 06/2014 

No comments:

Post a Comment