1

I am trying to solve the following problem from Scala for the impatient. The question is as follows:

Using pattern matching, write a function swap that swaps the first two elements of an array provided its length is at least two.

My solution is:

def swap(sArr:Array[Int]) = sArr.splitAt(2) match { 
                               case (Array(x,y),Array(z)) => Array(y,x,z)
                               case (Array(x,y),Array()) => Array(y,x)
                               case _ => sArr
                            }

My problem is with the first case statement. I think it would pattern-match something like (Array(1,2),Array(3)) whereas I intend it to pattern-match (Array(1,2),Array(3,4,5.....))

Can somebody point out how that would be possible.

Thanks

1 Answer 1

9

The problem with your code is that Array(z) means "match a one-element array". What you want is for z to be the whole array, no matter how many elements:

def swap(sArr: Array[Int]) = 
  sArr.splitAt(2) match { 
    case (Array(x, y), z) => Array(y, x) ++ z
    case _ => sArr
}

However, I would write it with the sequence-matching syntax _* so that you don't have to manually split the array:

def f(a: Array[Int]) = 
  a match {
    case Array(x, y, z @ _*) => Array(y, x) ++ z
    case _ => a
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I guess the @ _* denotes the zero or more here for c?

Your Answer

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.