zoukankan      html  css  js  c++  java
  • Scala_方法、函数、柯里化

    方法、函数、柯里化

    方法

    • 声明方法:

    scala> def m1(x:Int,y:Int):Int = {
        | x + y
        | }
    m1: (x: Int, y: Int)Int
    scala> m1(3,5)
    res6: Int = 8

    函数

    • 函数声明

    scala> val f1 = (x: Int, y: Int) => x + y
    f1: (Int, Int) => Int = <function2> //2是指参数的个数
    scala> f1(3,5)
    res7: Int = 8
    //函数作为参数传入方法
    scala> def m2(f: (Int , Int) => Int , x: Int) = f(3,4)
    m2: (f: (Int, Int) => Int, x: Int)Int
    scala> def m2(f: (Int , Int) => Int , x: Int) = f(3,4) + x
    m2: (f: (Int, Int) => Int, x: Int)Int
    scala> val f1 = (x: Int, y: Int) => x + y
    f1: (Int, Int) => Int = <function2>
    scala> m2(f1,2)
    res8: Int = 9
    //方法转换为函数

    方法转换为函数

    scala> def m2(f: (Int , Int) => Int , x: Int) = f(3,4)
    m2: (f: (Int, Int) => Int, x: Int)Int

    scala>  def m1(x:Int,y:Int):Int = x + y
    m1: (x: Int, y: Int)Int

    scala> val f1 = m1 _  //方法m1转换为函数
    f1: (Int, Int) => Int = <function2>
    scala> m2(f1,2)
    res9: Int = 9
    scala> m2(m1,2) //m1隐式转换为函数了
    res10: Int = 9

    柯里化

    • 柯里化(Currying)是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术

    • 声明方法

    // 声明方式1
    scala> def currying(x: Int)(y:Int) = x*y
    currying: (x: Int)(y: Int)Int

    scala> currying(3)(4)
    res0: Int = 12

    scala> val curry = currying(3)_
    curry: Int => Int = <function1>

    scala> curry(2)
    res1: Int = 6

    scala> curry(9)
    res2: Int = 27

    // 声明方式2
    scala> def curry(x: Int) = (y: Int) => x * y
    curry: (x: Int)Int => Int

    scala> val fun = curry(2)
    fun: Int => Int = <function1>

    scala> fun(2)
    res10: Int = 4
    • 柯里化设置隐式的值

    scala> def m2(x: Int)(implicit y: Int = 5) = x * y
    m2: (x: Int)(implicit y: Int)Int

    scala> m2(5)
    res3: Int = 25

    scala> m2(4)(4)
    res4: Int = 16

    scala> implicit val a = 100
    a: Int = 100

    scala> m2(4)
    res5: Int = 400

    scala> m2(4)(10)
    res6: Int = 40

    scala> implicit val b = 200
    b: Int = 200

    scala> m2(4)
    <console>:11: error: ambiguous implicit values:
    both value a of type => Int
    and value b of type => Int
    match expected type Int
                 m2(4)
                   ^
  • 相关阅读:
    WinForm 下的 Wizard(向导) 控件, 提供设计时支持!
    关于安装VS2005或MSDN时遇到“Please insert the disk:XXXXXXX” 错误提示的解决方法!
    Welcome
    Latex 入门教程
    图形学 旋转与投影矩阵3
    图形学 旋转与投影矩阵—2
    算法希尔排序可视化
    图形学 旋转与投影矩阵—1
    BlinnPhong反射模型实践(web实现)
    贝塞尔曲线(面)二三维可视化(Three+d3)
  • 原文地址:https://www.cnblogs.com/zxbdboke/p/10466251.html
Copyright © 2011-2022 走看看