Skip to content

Instantly share code, notes, and snippets.

@psksvp
Last active April 4, 2021 01:36
Show Gist options
  • Save psksvp/9b6ade05ff6267d90d3fcad54586fc0c to your computer and use it in GitHub Desktop.
Save psksvp/9b6ade05ff6267d90d3fcad54586fc0c to your computer and use it in GitHub Desktop.
// pairup a seq
// psksvp@gmail.com
object Pairup
{
def main(args: Array[String]): Unit =
{
println("hello")
val a = List(1, 2, 3, 4, 5, 6) //even
val b = pairup(a)
val c = List(1, 2, 3) // odd
val d = pairup(c)
println(b)
println(b == List((1,2), (2,3), (3,4), (4,5), (5,6)))
println(d)
println(d == List((1, 2), (2, 3)))
println(pairup(List()) == List())
println(pairup(List(1)) == List())
}
def pairup[T](s: Seq[T]):Seq[(T, T)] = s match
{
case f :: s :: rest => Seq((f, s)) ++ pairup(s :: rest)
case f :: nil => Seq() // list with one element
case nil => Seq()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment