Dinesh Babu Dinesh Babu - 2 months ago 6
Scala Question

How do I generate a List using tabulate who's entries are squared in Scala?

I'm new to Scala and I'm trying to generate a List using the

tabulate()
method.

I see that it's used this way and it works perfectly fine,

val myList = List.tabulate(10)(_ * 2)


but this doesn't

val myList = List.tabulate(10)(_ * _)


whereas, I got what I wanted by,

val myList = List.tabulate(10)(n => n * n)


Can I know why didn't the second example work?

m-z m-z
Answer

An anonymous function represented with underscores is expected to have the same number of arguments as underscores. The particular overload of List.tabulate you are using (for one-dimension) expects a function with only argument, but you provide a function with two.

In other words _ * _ expands to (a, b) => a * b and it is not possible to represent a => a * a with just underscores.

Alternatively, you could use math.pow(_, 2) as your squaring function, but it returns Double instead of Int.

scala> List.tabulate(10)(math.pow(_, 2))
res0: List[Double] = List(0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0)