-2

Trying to write a simple scala program that takes user inputs as ints, stores them in a tuple, then selects the max number from the tuple. I'm not sure as to why my code is not working.

import scala.io.StdIn._
println("Please enter four numbers.")
val one = readInt()
val two = readInt()
val three = readInt()
val four = readInt()
val numbers = (one, two, three, four)
println(math.max(numbers))

Error I'm getting:

C:\Users\Tyler\Documents\School\CSC10101\Mimir Assignments\max.scala:8: error: overloaded method value max with alternatives:
  (x: Double,y: Double)Double <and>
  (x: Float,y: Float)Float <and>
  (x: Long,y: Long)Long <and>
  (x: Int,y: Int)Int
 cannot be applied to ((Int, Int, Int, Int))
println(math.max(numbers))
             ^
one error found

Any help is greatly appreciated!

Tyler
  • 67
  • 2
  • 9
  • 2
    `println(List(one, two, three, four).max)` – jwvh Feb 19 '18 at 23:03
  • Just in case that you want to generalize it to operations for which no `List`-built-ins are provided: `println(List(one, two, three, four).reduce(math.max))`. It's just that `List.max`, `List.min`, `List.sum` always seemed so unnatural to me... – Andrey Tyukin Feb 19 '18 at 23:09

2 Answers2

2

math.max can only be applied to 2 arguments - you have 4. If you have four numbers what you can do is:

math.max(math.max(math.max(one, two), three), four)

To go with the suggestion @Javier made in the comment below, if your numbers are collected in a Seq or some other collection, you can apply the reduce higher ordered function:

List(one, two, three, four).reduce(math.max)

Or even better:

List(one, two, three, four).max
Tanjin
  • 2,442
  • 1
  • 13
  • 20
  • 2
    This would be a good place to use reduce: https://stackoverflow.com/questions/17408880/reduce-fold-or-scan-left-right#17408881 – Javier Feb 19 '18 at 23:02
  • Tanjin, thanks for the response that did the trick. Any chane you know why you couldn't use a tuple for this? – Tyler Feb 19 '18 at 23:06
  • @Tyler, in answer to your question: Unlike collections, each tuple configuration is its own separate type. If `Math.max()` were to take tuples there would have to be a separate/different definition for each of `(Int,Int)`, `(Int,Int,Int)`, `(Int,Int,Int,Int)`, etc., as well as `(Long,Long)`, `(Long,Long,Long)`, etc., as well as `(Float,Float)`, etc. etc. – jwvh Feb 20 '18 at 03:27
0

Sample code for your question.

import scala.io.StdIn._
val numbers = for (_ <- 0 until 4) yield readInt()
val maxNumber = numbers.reduce(math.max)
println(maxNumber)
Rumesh Krishnan
  • 443
  • 4
  • 16