3
\$\begingroup\$

I need to transform

List("home", "mens", "clothing", "jackets")

into

List(
  "/home",
  "/home/mens",
  "/home/mens/clothing",
  "/home/mens/clothing/jackets"
)

This is what I have so far:

val nodes = Array("home", "mens", "clothing", "jackets")
val (rootNode, otherNodes) = nodes.splitAt(1)
val tree = otherNodes.foldLeft(rootNode) { (list, token) =>
    list :+ (list.last + "/" + token)
}

What do you think? any obvious problems?

\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

It looks like you need a variation of the prefix sum algorithm applied to your list. In Scala this can be accomplished with scan:

val xs = List("home", "mens", "clothing", "jackets")
xs.scan("")(_ + "/" + _).tail
\$\endgroup\$
1
  • \$\begingroup\$ Very nice! I didn't know about scan \$\endgroup\$
    – user78169
    Mar 17, 2016 at 3:44
2
\$\begingroup\$

I think you don't need to split the nodes to run this correctly..

consider:

val tree = (nodes.foldLeft("") { (list, token) => 
    list :+ (list.last + "/" + token)
}).tail

I could also imagine extracting the current binary operator into a separate function.

Aside from that this is really nice and clean

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.