【问题标题】:Function taking an array and a function on an element array函数采用数组和元素数组上的函数
【发布时间】:2013-03-11 08:25:25
【问题描述】:

我开始学习 Scala,在为不耐烦的人阅读 Scala 时,对其中一个练习找到了以下解决方案:

//No function
def positivesThenZerosAndNegatives(values: Array[Int]) = {
    Array.concat(for (value <- values if value > 0) yield value,
        for (value <- values if value == 0) yield value,
        for (value <- values if value < 0) yield value)
}

但现在我试图将在每个综合应用上应用过滤器的函数作为参数传递:

//Trying to use a function (filter)
def positivesThenZerosAndNegatives2(values: Array[Int]) = {
    Array.concat(filter(values, _ > 0), filter(values, _ == 0), filter(values, _ < 0))
}

def filter[T: Int](values: Array[T], f: (T) => Boolean) = {
    for (value <- values if f(value)) yield value
}

我还没有找到引用元素数组的正确方法。

【问题讨论】:

    标签: scala functional-programming


    【解决方案1】:

    您可以编写filter 方法,如下所示:

    import scala.reflect.ClassTag
    
    def filter[T: ClassTag](values: Array[T], f: T => Boolean): Array[T] = {
      for(value <- values; if f(value)) yield value
    }
    

    或者这样:

    def filter(values: Array[Int], f: Int => Boolean): Array[Int] = {
      for(value <- values; if f(value)) yield value
    }
    

    无论如何,您可以像这样简单地重写您的方法positivesThenZerosAndNegatives

    scala> def positivesThenZerosAndNegatives(values: Array[Int]) = {
         |   values.filter(0 <) ++ values.filter(0 ==) ++ values.filter(0 >)
         | }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-24
      • 2012-10-13
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2019-04-22
      • 2015-11-09
      相关资源
      最近更新 更多