Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic Scala to iterate over all substrings [closed]

Something less imperative than this:

def subs(s: String) = for {start <- 0 to s.length; end <- i to s.length} yield s.substring(start, end)

like image 362
pathikrit Avatar asked Feb 13 '13 20:02

pathikrit


1 Answers

scala> "asdf".inits.flatMap(_.tails).toList
res2: List[String] = List(asdf, sdf, df, f, "", asd, sd, d, "", as, s, "", a, "", "")

If you want to remove empty strings:

scala> "asdf".inits.flatMap(_.tails.toList.init).toList
res3: List[String] = List(asdf, sdf, df, f, asd, sd, d, as, s, a)

But note that this incantation is not so obvious to the reader, as @Randall Schulz points out in comments. Your original version, on the other hand, is instantly clear.

like image 193
Rogach Avatar answered Sep 28 '22 09:09

Rogach