给我数组中最小和最大数字的 Scala 程序

Scala program that gives me smallest and largest number from an Array

我正在寻找一个 scala 代码,该代码可以为我提供包含 myArr 中最小和最大数字的新数组。

我会写下面的代码。我如何在单个函数中编写它

scala> val myArr = Array(1,5,3)
 myArr: Array[Int] = Array(1, 5, 3)

 scala> myArr.reduce((a,b) => if(a>b)a else b)
 res0: Int = 5

 scala> myArr.reduce((a,b) => if(a<b)a else b)
 res1: Int = 1

预期输出:Array(1,5)

val myArr = Array(1,5,3)

val result = myArr.foldLeft(List.empty[Int]){
 case (min :: max :: _, value) if value < min => List(value, max) // lower than the minimun
 case (min :: max :: _, value) if value > max => List(min, value) // greater than the maximun
 case (Nil, value) => List(value, value) // first value
 case (l, _) => l // the final list doesn't need to be updated
}

你可以在这里查看https://scastie.scala-lang.org/XLE8VAKTRhWbl0JFrjGgnw 它使用列表进行更好的模式匹配。