0

If I were splitting a string, I would be able to do

"123,456,789".split(",") 

to get Seq("123","456","789")

Thinking of a string as a sequence of characters, how could this be generalized to other sequences of objects?

val x = Seq(One(),Two(),Three(),Comma(),Five(),Six(),Comma(),Seven(),Eight(),Nine())
x.split(
  number=>{
    case _:Comma => true
    case _ => false
  }
)

split in this case doesn't exist, but it reminds me of span, partition, groupby, but only span seems close, but it doesn't handle leading/ending comma's gracefully.

3 Answers 3

1
implicit class SplitSeq[T](seq: Seq[T]){
  import scala.collection.mutable.ListBuffer
  def split(sep: T): Seq[Seq[T]] = {
    val buffer = ListBuffer(ListBuffer.empty[T])
    seq.foreach {
      case `sep` => buffer += ListBuffer.empty
      case elem => buffer.last += elem
    }; buffer.filter(_.nonEmpty)
  }
}

It can be then used like x.split(Comma()).

Sign up to request clarification or add additional context in comments.

1 Comment

Accepted this over Meghana's as it seems more readable to me + it doesn't need multiple tuple2 creation.
1

The following is 'a' solution, not the most elegant -

def split[A](x: Seq[A], edge: A => Boolean): Seq[Seq[A]] = { 

  val init = (Seq[Seq[A]](), Seq[A]())

  val (result, last) = x.foldLeft(init) { (cum, n) =>
    val (total, prev) = cum

    if (edge(n)) {
        (total :+ prev, Seq.empty)
    } else {
        (total, prev :+ n)
    }
  }

  result :+ last
}

Example result -

scala> split(Seq(1,2,3,0,4,5,0,6,7), (_:Int) == 0)
res53: Seq[Seq[Int]] = List(List(1, 2, 3), List(4, 5), List(6, 7))

Comments

0

This is how I've solved it in the past, but I suspect there is a better / more elegant way.

  def break[A](xs:Seq[A], p:A => Boolean): (Seq[A], Seq[A]) = {
    if (p(xs.head)) {
      xs.span(p)
    }
    else {
      xs.span(a => !p(a))
    }
  }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.