val a = List(1, 2, 3, 4)
val b = 0 :: a
而不能寫成這樣
val a = List(1, 2, 3, 4)
val b = a :: 0
val b = 0 :: a
而不能寫成這樣
val a = List(1, 2, 3, 4)
val b = a :: 0
2017-11-06
另一種寫法:
def sum(f: Int => Int)(a: Int)(b: Int) = {
def loop(n: Int)(acc: Int): Int = {
if(n < a)
acc
else
loop(n-1)(acc+f(n))
}
loop(b)(0)
}
sum(x => x)(1)(5)
def sum(f: Int => Int)(a: Int)(b: Int) = {
def loop(n: Int)(acc: Int): Int = {
if(n < a)
acc
else
loop(n-1)(acc+f(n))
}
loop(b)(0)
}
sum(x => x)(1)(5)
var i = 1
//var s = " "
def main(args: Array[String]) {
i = jie(5,1)
println(i)
}
@annotation.tailrec
def jie (n:Int,m:Int): Int ={
if(n <= 0) m
else{
jie(n -1,m*n)
}
}
//var s = " "
def main(args: Array[String]) {
i = jie(5,1)
println(i)
}
@annotation.tailrec
def jie (n:Int,m:Int): Int ={
if(n <= 0) m
else{
jie(n -1,m*n)
}
}
2017-10-12
e.g.快速排序
def qSort(x: List[Int]):List[Int] = {
if (x.length<=1) x
else
qSort(x.filter(_ < x.head)) ++
x.filter(_ == x.head) ++
qSort(x.filter(_ > x.head))
}
def qSort(x: List[Int]):List[Int] = {
if (x.length<=1) x
else
qSort(x.filter(_ < x.head)) ++
x.filter(_ == x.head) ++
qSort(x.filter(_ > x.head))
}
2017-09-27
缺失部分
例子1: (x: Int) => x*x
例子2: (x: Int,y: Int) => x+y
例子3:
var add = (x: Int,y: Int)=> x+y //add是一個(gè)具有函數(shù)類型的變量
add(1,2) //返回值:Int=3
def greeting() = (name:String) => {s"Hello $name"}
greeting()("World")
def greeting(age: Int) = (name:String) => {s"Hello $name,your age is $age"}
greeting(23)("Flygar")
例子1: (x: Int) => x*x
例子2: (x: Int,y: Int) => x+y
例子3:
var add = (x: Int,y: Int)=> x+y //add是一個(gè)具有函數(shù)類型的變量
add(1,2) //返回值:Int=3
def greeting() = (name:String) => {s"Hello $name"}
greeting()("World")
def greeting(age: Int) = (name:String) => {s"Hello $name,your age is $age"}
greeting(23)("Flygar")
2017-09-27