比这更不重要的事情:
def subs(s: String) = for {start <- 0 to s.length; end <- i to s.length} yield s.substring(start, end)
比这更不重要的事情:
def subs(s: String) = for {start <- 0 to s.length; end <- i to s.length} yield s.substring(start, end)
scala> "asdf".inits.flatMap(_.tails).toList
res2: List[String] = List(asdf, sdf, df, f, "", asd, sd, d, "", as, s, "", a, "", "")
如果要删除空字符串:
scala> "asdf".inits.flatMap(_.tails.toList.init).toList
res3: List[String] = List(asdf, sdf, df, f, asd, sd, d, as, s, a)
但请注意,正如@Randall Schulz 在评论中指出的那样,这种咒语对读者来说并不那么明显。另一方面,您的原始版本立即清晰。