class MyOperation(arr: Array[Int]) {

  def foreach(f: (Int) => Unit): Unit = {
    for (num <- arr) {
      f(num)
    }
  }

  def filter(f: (Int) => Boolean): Array[Int] = {
    var res = Array[Int]()
    for (num <- arr if f(num)) yield num
  }

  def map(f: (Int) => (Int)): Array[Int] = {
    for (elem <- arr) yield f(elem)
  }

  def reduce(f: (Int, Int) => (Int)): Int = {
    var res = arr(0)
    for (idx <- 1 until arr.length) {
      res = f(res, arr(idx))
    }
    res
  }
}

object MyOperation {
  def apply(arr: Array[Int]): MyOperation = new MyOperation(arr)
}

// 测试
object Test {
  def main(args: Array[String]): Unit = {
    val arr: Array[Int] = Array[Int](1, 2, 3, 4, 5)
    val myOperation: MyOperation = MyOperation(arr)

    // test foreach
    myOperation.foreach(println)

    print("\n----------------------\n")
    // test filter
    val arr2 = myOperation.filter(x => x % 2 == 0)
    println(arr2.mkString(", "))

    print("\n----------------------\n")


    // test map
    val arr3 = myOperation.map(2 * _)
    println(arr3.mkString(", "))

    print("\n----------------------\n")

    // test reduce
    val num1 = myOperation.reduce(_ + _)
    val num2 = myOperation.reduce(_ * _)
    println(s"num1:$num1, nums2:$num2")
  }
}