Skip to content

Instantly share code, notes, and snippets.

@non
Created January 19, 2012 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save non/1643619 to your computer and use it in GitHub Desktop.
Save non/1643619 to your computer and use it in GitHub Desktop.
@tailrec
def collapse[A](as:List[A])(f:(A, A) => A):Option[A] = as match {
case Nil => None
case a :: Nil => Some(a)
case as => collapse(pairwise(as, Nil)(f))(f)
}
@tailrec
def pairwise[A](as:List[A], sofar:List[A])(f:(A, A) => A):List[A] = {
as match {
case a1 :: a2 :: as => pairwise(as, f(a1, a2) :: sofar)(f)
case a :: Nil => a :: sofar
case Nil => sofar
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment