Skip to content

Instantly share code, notes, and snippets.

@dholbrook
Created March 29, 2012 18:43
Show Gist options
  • Save dholbrook/2241836 to your computer and use it in GitHub Desktop.
Save dholbrook/2241836 to your computer and use it in GitHub Desktop.
S99 P19
/*
* S99 P19 http://aperiodic.net/phil/scala/s-99/
*
* (**) Rotate a list N places to the left.
*
* Examples:
*
* scala> rotate(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
* res0: List[Symbol] = List('d, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'a, 'b, 'c)
*
* scala> rotate(-2, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
* res1: List[Symbol] = List('j, 'k, 'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i)
*
* D. Holbrook
*/
object S9919 extends App {
def rotate[A](n: Int, l: List[A]) : List[A] = n match {
case n if n >= 0 => (l drop n) ::: (l take n)
case n => (l drop (l.size + n)) ::: (l take l.size + n)
}
val r1 = rotate(3, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
println(r1)
assert(r1 == List('d, 'e, 'f, 'g, 'h, 'i, 'j, 'k, 'a, 'b, 'c))
val r2 = rotate(-2, List('a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i, 'j, 'k))
println(r2)
assert(r2 == List('j, 'k, 'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, 'i))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment