设为首页 加入收藏

TOP

scala-currying化
2017-10-10 12:12:35 】 浏览:7930
Tags:scala-currying

scala的加里化(currying)纠结了很久。通过Scala Worksheet 可以打印很多调试信息,所以用它写了一些测试代码,帮助自己理解。

  

object test {
     //一个参数列表,3个参数
  def sum(a: Int, b: Int, c: Int) = a + b + c     //> sum: (a: Int, b: Int, c: Int)Int
  
  //将一个参数列表,拆分成三个参数列表
  def sum4(a: Int)(b: Int)(c: Int) =  a + b + c   //> sum4: (a: Int)(b: Int)(c: Int)Int
  
  //sum4的偏应用函数
  val fn4 = sum4 _                                //> fn4  : Int => (Int => (Int => Int)) = <function1>
    
    //根据偏应用函数,便可定义出如下函数:
  def sum44(a: Int) = {
    (b: Int) =>
      {
        (c: Int) =>
          {
            a + b + c
          }
      }
  }                                               //> sum44: (a: Int)Int => (Int => Int)

  //自定义函数的偏应用函数
  val fn44 = sum44 _                              //> fn44  : Int => (Int => (Int => Int)) = <function1>

  sum(1, 2, 3)                                    //> res0: Int = 6
  sum4(1)(2)(3)                                   //> res1: Int = 6
  sum44(1)(2)(3)                                  //> res2: Int = 6
  
  //将2,3分别偏应用到第一个,第二个参数上
  val fn44_2 = sum44(2)(3)(_:Int)                 //> fn44_2  : Int => Int = <function1>
  fn44_2(4)                                       //> res3: Int = 9
  fn44_2.apply(4)                                 //> res4: Int = 9

}

 

  • 偏函数应用是找一个函数,固定其中的几个参数值,从而得到一个新的函数。
  • 函数加里化是一种使用匿名单参数函数来实现多参数函数的方法。
  • 函数加里化能够让你轻松的实现某些偏函数应用。

 

参考: 

闭包的定义    https://en.wikipedia.org/wiki/Closure_(computer_programming)  

加里化的定义 https://en.wikipedia.org/wiki/Currying

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇scala学习手记21 - 传递变长参数 下一篇Scalaz(49)- scalaz-stream: ..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目