Skip to content

Instantly share code, notes, and snippets.

@ScalaWilliam
Created December 26, 2013 00:00
Show Gist options
  • Save ScalaWilliam/8128084 to your computer and use it in GitHub Desktop.
Save ScalaWilliam/8128084 to your computer and use it in GitHub Desktop.
pairHeadingsParagraphs.scala
def packer[A](l: List[A])(f: A => Boolean): List[(A, List[A])] = {
if ( l.isEmpty ) List()
else if ( !f(l.head) ) List()
else {
val heading :: rest = l
val (paragraphs, nextBunch) = rest span (false == f(_))
(heading, paragraphs) :: packer(nextBunch)(f)
}
}
case class Heading(title: String)
case class Paragraph(text: String)
type PS = Product with Serializable
type HP = List[(PS, List[PS])]
val haveOutput: HP = packer(List(
Heading("Hello!"),
Paragraph("hey"),
Heading("Bang"),
Heading("Tr"),
Paragraph("OK"),
Paragraph("OK")
))(_.isInstanceOf[Heading])
val expectedOutput: HP = List(
(Heading("Hello!"), List(Paragraph("hey"))),
(Heading("Bang"), Nil),
(Heading("Tr"), List(Paragraph("OK"), Paragraph("OK")))
)
assert(haveOutput.toString == expectedOutput.toString, "Should match.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment