zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    vue整合富文本编辑器
    node.js快速入门
    springboot启动项目加载配置文件中的常量
    hihocoder1712 字符串排序(思维)
    大数运算
    hihocoder1323 回文字符串(区间dp)
    hdu6026 Deleting Edges(Dijkstra+思路)
    poj3087 Shuffle'm Up(bfs)
    hdu6024 Building Shops(区间dp)
    poj1651 Multiplication Puzzle(区间dp)
  • 原文地址:https://www.cnblogs.com/mataszhang/p/5683654.html
Copyright © 2011-2022 走看看