2
\$\begingroup\$
 def toPairs[A](xs : Seq[A]) : Seq[Tuple2[A,A]] = {
 @tailrec
 def accumulator(as : Seq[A], accum: Seq[Tuple2[A,A]]) : Seq[Tuple2[A,A]] = as match {
 case Nil => accum
 case x :: tail => tail match {
 case Nil => accum
 case _ => accumulator(as.tail, accum :+ (x,tail.head))
 }
 }
 accumulator(xs, Seq.empty[Tuple2[A,A]])
 }

I use this code for the following use case: for a Seq[A] i.e. List(1,2,3) I want a Seq of Tuples of A i.e. List((1,2)(2,3)). Is this the most optimal, idiomatic way in Scala, what could be improved?

For the record: the order of the elements is important and is expected to be congruent with the example in the preceding paragraph.

asked Nov 12, 2015 at 22:46
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

I find the way you go back and forth between as and x a bit annoying. You should be able to collapse the nested match into one match that covers three cases.

The :+ operator, which appends an element to a sequence, should be avoided at all costs, because it involves traversing to the end of the sequence. That makes your algorithm O(n2), when it should ideally be O(n).

Anyway, the solution can be much simpler than that.

def toPairs[A](xs: Seq[A]): Seq[(A,A)] = xs.zip(xs.tail)
answered Nov 13, 2015 at 7:27
\$\endgroup\$
1
  • \$\begingroup\$ Awesome, esp. the short syntax of Tuple typeargs: (A,A) vs Tuple2[A,A]! \$\endgroup\$ Commented Nov 13, 2015 at 18:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.