Skip to content

Instantly share code, notes, and snippets.

@arjanblokzijl
Created July 4, 2010 06:40
Show Gist options
  • Save arjanblokzijl/463225 to your computer and use it in GitHub Desktop.
Save arjanblokzijl/463225 to your computer and use it in GitHub Desktop.
//some nice but perhaps not so useful list operations
object ListOps {
//translated to Scala: http://www.haskell.org/pipermail/libraries/2010-July/013842.html
def select[T](l: List[T]): List[(T, List[T])] = l match {
case Nil => Nil
case x::xs => (x, xs) :: (for {(y, ys) <- select(xs)} yield (y, x::ys))
}
def separate[T](l: List[T]): List[(List[T], T, List[T])] = l match {
case Nil => Nil
case x::xs => (Nil, x, xs) :: (for {(us, y, ys) <- separate(xs)} yield (x::us, y, ys))
}
//http://stackoverflow.com/questions/2243812/functional-programming-implementing-scan-prefix-sum-using-fold
//'This, of course, is a horrible way to express scan but it is a fun exercise of jamming a square peg into a round hole'
//scanLeft does exactly the same thing, but anyway:
def prefixSum(l:List[Int]) = l.foldLeft(List(0)){(l,e) => l ::: List(e + l.last)}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment