0

I want to make a function in scala that uses "match ... case" to double the values of a list.

For example:

doubleList(List(2,1,4,5)) //> res0: List[Int] = List(4, 2, 8, 10) 

I wrote this function:

def doubleList(xs: List[Int]): List[Int] = xs match { case y :: ys => y * 2; doubleList(ys); case Nil => xs; } 

But I get an empty list as the result:

//> res0: List[Int] = List() 

Can anyone teel me what am I doing wrong?

2
  • Any reason, why you don't just use map(_ * 2)? Commented Apr 17, 2016 at 22:43
  • Yes, I am required to use specificly "match ... case". Commented Apr 17, 2016 at 22:44

1 Answer 1

3

The ; closes the statement and effectively throws away the result, use :: instead to create a new List with the result of y * 2 and doubleList(ys)

def doubleList(xs: List[Int]): List[Int] = xs match { case y :: ys => y * 2 :: doubleList(ys) case Nil => xs } 

P.S. you don't have to put a ; at the end of a line in scala.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I didn't know about that ; closes the statement. Thanks for your answer, worked just great.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.