Skip to content

Instantly share code, notes, and snippets.

@dholbrook
Created March 8, 2012 17:56
Show Gist options
  • Save dholbrook/2002351 to your computer and use it in GitHub Desktop.
Save dholbrook/2002351 to your computer and use it in GitHub Desktop.
S99 Problem 16
/*
* S99 P16 http://aperiodic.net/phil/scala/s-99/
* (**) Drop every Nth element from a list.
*
* Example:
*
* scala> drop(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
* res0: List[Symbol] = List('a, 'b, 'd, 'e, 'g, 'h, 'j, 'k)
*
*/
object S9916 extends App {
def drop[A](n: Int, lst: List[A]): List[A] = {
lst.foldLeft((1, List[A]())) {
case ((aidx, alst), e) if aidx % n != 0 => (aidx + 1, e :: alst)
case ((aidx, alst), _) => (aidx + 1, alst)
}._2.reverse
}
val r = drop(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
println(r)
assert( r == List('a, 'b, 'd, 'e, 'g, 'h, 'j, 'k) )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment