Given the string
val path = "/what/an/awesome/path"
how can I use Scala to create a list of absolute paths for each directory in path? The result should be:
List(/what, /what/an, /what/an/awesome, /what/an/awesome/path)
Bonus points for an elegant, functional solution.
val path = "/what/an/awesome/path"
val file = new java.io.File(path)
val prefixes = Iterator.iterate(file)(_.getParentFile).takeWhile(_ != null).toList.reverse
val path = "/what/an/awesome/path"
scala> path.tail.split("/").scanLeft(""){_ + "/" + _}.tail.toList
res1: List[java.lang.String] = List(/what, /what/an, /what/an/awesome, /what/an/awesome/path)
Using Jesse Eichar's new Scala IO library (version 0.2.0) it looks like you can do something like this:
val path = Path("/what/an/awesome/path")
val paths = (path :: path.parents).reverse
You might want to convert the Path objects in the resulting list to Strings but perhaps they would be safer and more useful left as Path objects.
This library, as far as I know, is being considered for inclusion in the Scala distribution.
path.drop(1).split("/").foldLeft(List.empty[String])((list, string) => ((list.headOption.getOrElse("") + "/" + string) :: list)).reverse.toList
There's probably a cleaner way using scanLeft, but I wasn't able to figure it out
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With