第1节 Scala基础语法:scala中的方法源码分析

val list=List(1,2,3,4)
list.reduce((x:Int,y:Int)=>x+y)--->list.reduceLeft((x:Int,y:Int)=>x+y)

var first = true
var acc:Int = 0
op=(x:Int,y:Int)=>x+y

for循环
第一次循环:acc=1 first = false
第二次循环:acc=op(1,2)=1+2=3
第三次循环:acc=op(3,3)=3+3=6
第四次循环:acc=op(6,4)=6+4=10
======================================================================
val list=List(1,2,3,4)
list.reduceRight((x:Int,y:Int)=>x-y)

op(head, tail.reduceRight(op))---》op(1,List(2,3,4).reduceRight(op)---->op(2,List(3,4).reduceRight(op)-->op(3,List(4).reduceRight(op)=4)=3-4=-1)=2-(-1)=3)=1-3=-2

========================================================================
val list=List(1,2,3,4)
list.foldRight(0)(_-_) --->reverse.foldLeft(z)((right, left) => op(left, right))

List(4,3,2,1).foldLeft(z)((right, left) => op(left, right))


var acc = 0
var these = List(4,3,2,1)
while (!these.isEmpty) {
acc = op(acc, these.head)
these = these.tail
}

while循环
第一次while: acc=op(0,4)=>op(4,0)=4-0=4 these=List(3,2,1)
第二次while: acc=op(4,3)=>op(3,4)=3-4=-1 these=List(2,1)
第三次while: acc=op(-1,2)=>op(2,-1)=2-(-1)=3 these=List(1)
第四次while: acc=op(3,1)=>op(1,3)=1-3=-2 these=List()

=========================================================================
val array=Array(1,2,3,4)------>其本质是调用了Array这个object的apply方法

def apply(x: Int, xs: Int*): Array[Int] = {
//构建了一个跟目标数组长度一致的空的数组
val array = new Array[Int](xs.length + 1)
//把参数中的第一个元素赋值给空的数组的0下标
array(0) = x
var i = 1
for (x <- xs.iterator) { array(i) = x; i += 1 }
// array(1)=2 i=2
// array(2)=3 i=3
// array(3)=4 i=4
array--->Array(1,2,3,4)
}

import scala.collection.mutable._
Array(1,2,3,4).map(_+_)

import scala.collection.mutable.A
import scala.collection.mutable.B
import scala.collection.mutable.C
import scala.collection.mutable.D

转载于:https://www.cnblogs.com/mediocreWorld/p/11361164.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值