5

I have the following code:

var x = Array(1,3,4,4,1,1,3)
var m = Int.MaxValue
x.foreach((x)=>(m = m min x))

I tried to simplify last sentence to:

x.foreach((m = _ min m))

But the interpreter says:

scala>  x.foreach((m = _ min m))     
<console>:8: error: missing parameter type for expanded function ((x$1) => x$1.min(m))
    x.foreach((m = _ min m))
                   ^

I tried to be more explicit about the type:

scala>  x.foreach((m = (_:Int) min m))
<console>:8: error: type mismatch;
found   : (Int) => Int
required: Int
    x.foreach((m = (_:Int) min m))
                           ^

The compiler and I don't understand each other :(

Best regards,

Stan

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
Stan
  • 73
  • 1
  • 4
  • It seems `=` is delimiting the expression. I didn't expect that to happen... And I _did_ test the code, but it's obviously not working, so I removed my answer. – Daniel C. Sobral May 12 '11 at 23:29

1 Answers1

4

First, note that

val m = x.min

does what you want, as does

val m = (Int.MaxValue /: x)(_ min _)

I will leave it to you to read more about these things (the min method on collections, and folds; note that these are not quite as fast as what you wrote).

The problem is that the compiler is getting lost with what you mean and with what valid types might be when you write the underscore, and when you add the type information it thinks that you're trying to write a function right there and assign it to m. But of course m is an Int, not a function, so it complains.

Just write it explicitly. It's only a few extra characters:

x.foreach(i => m = m min i)
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
  • Thank you Rex! I was trying to understand the details of simplifying expressions using underscore, more than calculating the minimum. Your solution: val m = (Int.MaxValue /: x)(_ min _), is very neat! Cheers! – Stan May 12 '11 at 18:02