Skip to content

Instantly share code, notes, and snippets.

@SethTisue
Created May 6, 2011 23:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SethTisue/960008 to your computer and use it in GitHub Desktop.
Save SethTisue/960008 to your computer and use it in GitHub Desktop.
The Seasoned Schemer, chapter 19, page 176
// page 176
// recursive non-consing solution with var
def hasTwoInARow[T](lists: List[Any]) = {
var previous: Option[Any] = None
def recurse(rest: Any): Boolean =
rest match {
case xs: List[_] =>
xs.exists(recurse)
case _ =>
previous.exists(_ == rest) ||
{ previous = Some(rest); false }
}
recurse(lists)
}
// recursive pure-functional lazy consing solution
def flatten[T](xs: Stream[Any]): Stream[Any] =
xs flatMap {
case x: Stream[_] => flatten(x)
case x => Stream(x)
}
def hasTwoInARow[T](xs: Stream[Any]) =
flatten(xs).sliding(2).exists(pair => pair(0) == pair(1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment