Created
May 6, 2011 23:39
-
-
Save SethTisue/960008 to your computer and use it in GitHub Desktop.
The Seasoned Schemer, chapter 19, page 176
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
// 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