Created
December 26, 2013 00:00
-
-
Save ScalaWilliam/8128084 to your computer and use it in GitHub Desktop.
pairHeadingsParagraphs.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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