【问题标题】:Passing a function to another function as statement将一个函数作为语句传递给另一个函数
【发布时间】:2018-06-12 18:15:03
【问题描述】:

我想编写一个函数,如果给定一个偶数作为参数,它将返回 true,否则返回 false。另外,编写一个函数来过滤仅返回偶数的数字列表。全部使用 Scala 函数式编程完成。这就是我所拥有的:

def isEven(n:Int): Boolean = n % 2 == 0
    println(isEven(4))

val filterEven  =  ( xs :List[Int] )  => {
    for(  x <- xs;   if x % 2 == 0  )  yield x
}
println(filterEven(List(3,2,4,5,6,22,91)))

我的问题是,如何将第一个函数“isEven”传递给“filterEven”函数以替换“if-statement”?

问候。

【问题讨论】:

    标签: scala functional-programming user-defined-functions scala-collections


    【解决方案1】:

    您可以将 isEven 作为参数传递给xs.filter

    def filterEven(xs: List[Int]) = xs.filter(isEven)

    这在功能上等同于:

    def filterEven(xs: List[Int]) = for { x &lt;- xs if isEven(x) } yield x

    【讨论】:

      【解决方案2】:

      首先你在传入的时候给它一个名字。

      val filterEven = (xs :List[Int], filterFunc: Int => Boolean)  => {
      

      然后你用它的新名字调用它。

        for(x <- xs; if filterFunc(x)) yield x
      

      请注意,现在filterEven 不是您的函数的好名称。以filterFunc 形式传入的参数将决定您过滤偶数、奇数、小于100 还是.....

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-28
        • 2019-07-25
        • 2013-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多