Currying

作者: 猴猴猪027 | 来源:发表于2018-08-30 14:26 被阅读0次

    介绍

    Methods may define multiple parameter lists. When a method is called with a fewer number of parameter lists, then this will yield a function taking the missing parameter lists as its arguments.
    定义的一个函数有多个参数,如果只传入了其中部分参数,那么它就变成了另一个函数,参数列表是,之前缺少的参数。

    举例

    object CurryTest extends App {
    
      def filter(xs: List[Int], p: Int => Boolean): List[Int] =
        if (xs.isEmpty) xs
        else if (p(xs.head)) xs.head :: filter(xs.tail, p)
        else filter(xs.tail, p)
    
      def modN(n: Int)(x: Int) = ((x % n) == 0)
    
      val nums = List(1, 2, 3, 4, 5, 6, 7, 8)
      println(filter(nums, modN(2)))
      println(filter(nums, modN(3)))
    }
    

    如上所示,modN需要两个参数,返回值是一个boolean型的;如最后两行所示,如果只传了一个参数,那么这个函数就变成了需要一个参数,返回boolean值。
    刚好符合filter的第二个参数的定义,入参是Int,结果是Boolean。

    相关文章

      网友评论

        本文标题:Currying

        本文链接:https://www.haomeiwen.com/subject/cdsrwftx.html