Scala基礎語法

/*
學慕課網上《Scala程序設計》課程跟着敲的代碼
做爲代碼參考也是很好的
在scala_ide.org上下載eclipse IDE,新建一個worksheet,就能夠像在xcode的playground那樣玩了,
就是以下所示,寫變量直接在右邊顯示結果
連接:scala集合文檔http://docs.scala-lang.org/zh-cn/overviews/collections/introduction

函數式編程,核心是狀態不變
*/

var x = 1                                       //> x  : Int = 1
val y = 2                                       //> y  : Int = 2
lazy val z = x + y                              //> z: => Int

//Byte Short Int Long Float Double Boolean Char Unit
val b:Byte = 10                                 //> b  : Byte = 10
var u:Unit = ()                                 //> u  : Unit = ()

//類型體系很別緻
//Any -> AnyVal, AnyRef
//AnyVal基本類型
//AnyRef引用類型
//Null/Nothing做爲最後子類

def foo = throw new Exception("")               //> foo: => Nothing

var name = "123"                                //> name  : String = 123
var name2 = s"456 ${name}"                      //> name2  : String = 456 123

//定義函數
def function(param:Int):Int = {
    1
}                                               //> function: (param: Int)Int
def function2(param:Int) = {
    1
}                                               //> function2: (param: Int)Int
//調用函數
function2(1)                                    //> res0: Int = 1
//能省略就省略的方法定義
def func = 1                                    //> func: => Int

if(true) 1 else 2                               //> res1: Int = 1

//循環
var l = List("a", "b", "c")                     //> l  : List[String] = List(a, b, c)
for{
    s <- l
    s1 = s.toUpperCase()
    if(s1.length == 1)//filter
}yield(s1)                                      //> res2: List[String] = List(A, B, C)

//try..catch..finally
try{
    Integer.parseInt("dog")
}catch{
    case _ => 0
}finally{
    println("oo")
}                                               //> oo
                                                //| res3: Int = 0

//match 相似 switch
val i = 1                                       //> i  : Int = 1
i match {
    case 1 => "one"
    case 2 => "two"
    case _ => "others"
}                                               //> res4: String = one

//Call By Value || Call By Name
//先肯定參數的值,再執行函數
//仍是直接把參數傳入函數,在函數中肯定參數的值
def test1(x:Int) = x                            //> test1: (x: Int)Int
def test2(x: => Int) = x                        //> test2: (x: => Int)Int

//高階函數
def operate(f: (Int,Int)=>Int)={
    f(4,4)
}                                               //> operate: (f: (Int, Int) => Int)Int

//返回值是函數
def greeting() = (name:String) => {"hello " + name}
                                                //> greeting: ()String => String

//柯里化
def add(a: Int)(b:Int) = a + b                  //> add: (a: Int)(b: Int)Int
add(2)(2)                                       //> res5: Int = 4

var add3 = add(3)_                              //> add3  : Int => Int = <function1>

add3(5)                                         //> res6: Int = 8



/*
  如下都是經常使用的集合
*/
val lista = List(1, 2, 3, 4)                    //> lista  : List[Int] = List(1, 2, 3, 4)
val listb = 0 :: lista                          //> listb  : List[Int] = List(0, 1, 2, 3, 4)
val listc = "x" :: "y" :: "z" :: Nil            //> listc  : List[String] = List(x, y, z)

val listd = lista ::: listc                     //> listd  : List[Any] = List(1, 2, 3, 4, x, y, z)
lista.head                                      //> res7: Int = 1
listc.tail                                      //> res8: List[String] = List(y, z)
lista.isEmpty                                   //> res9: Boolean = false

//編寫遞歸函數處理list
def deallist(l: List[Int]): String = {
    if(l.isEmpty) ""
    else l.head.toString + " " + deallist(l.tail)
}                                               //> deallist: (l: List[Int])String
deallist(lista)                                 //> res10: String = "1 2 3 4 "
//對list應用filter
lista.filter(x=>x%2==1)                         //> res11: List[Int] = List(1, 3)
lista.filter(_%2==1)                            //> res12: List[Int] = List(1, 3)

"99 Red Balloons".toList.filter(x=>Character.isDigit(x))
                                                //> res13: List[Char] = List(9, 9)
//一直取直到..
"99 Red Balloons".toList.takeWhile(x=>x!='B')   //> res14: List[Char] = List(9, 9,  , R, e, d,  )

//對list應用map
listc.map(x=>x.toUpperCase)                     //> res15: List[String] = List(X, Y, Z)
listc.map(_.toUpperCase)                        //> res16: List[String] = List(X, Y, Z)

//二維數組
val liste = List(lista, List(4,5,6))            //> liste  : List[List[Int]] = List(List(1, 2, 3, 4), List(4, 5, 6))
//把二維數組轉爲一維
liste.flatMap(_.filter(_%2==0))                 //> res17: List[Int] = List(2, 4, 4, 6)

//reduce,參數爲一個函數,該函數有兩個參數,倆參數與一個返回值這三者的類型都相同
lista.reduceLeft(_ + _)                         //> res18: Int = 10

//fold
//不斷把值加上去
lista.foldLeft(0)(_ + _)                        //> res19: Int = 10
//不斷把值乘上去
lista.foldLeft(1)(_ * _)                        //> res20: Int = 24
//不斷把值連到字符串上
lista.foldLeft("")(_ + _)                       //> res21: String = 1234

//range,用to或until(右閉或右開)
1 to 10                                         //> res22: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6,
                                                //|  7, 8, 9, 10)
1 until 10 by 2                                 //> res23: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)

//stream 惰性求值
val s = (1 to 10000).toStream                   //> s  : scala.collection.immutable.Stream[Int] = Stream(1, ?)
s.head                                          //> res24: Int = 1
s.tail                                          //> res25: scala.collection.immutable.Stream[Int] = Stream(2, ?)

//tuple
(1,2)                                           //> res26: (Int, Int) = (1,2)
//相似數據庫裏的一行記錄,能夠做爲函數的返回值,打包返回多個值
val alice = (1, "Alice", "Math", 95.5)          //> alice  : (Int, String, String, Double) = (1,Alice,Math,95.5)
alice._1                                        //> res27: Int = 1

def sumSq(in : List[Int]):(Int,Int,Int)=
    in.foldLeft((0,0,0))((t,v)=>(t._1+1, t._2+v, t._3+v*v))
                                                //> sumSq: (in: List[Int])(Int, Int, Int)

sumSq(lista)                                    //> res28: (Int, Int, Int) = (4,10,30)


//map
val map = Map(1 -> "David", 9->"Beckham")       //> map  : scala.collection.immutable.Map[Int,String] = Map(1 -> David, 9 -> Be
                                                //| ckham)
map(1)                                          //> res29: String = David
map.contains(1)                                 //> res30: Boolean = true
map.keys                                        //> res31: Iterable[Int] = Set(1, 9)
map.values                                      //> res32: Iterable[String] = MapLike(David, Beckham)
map + (10 -> "Zidane")                          //> res33: scala.collection.immutable.Map[Int,String] = Map(1 -> David, 9 -> Be
                                                //| ckham, 10 -> Zidane)
map - 1                                         //> res34: scala.collection.immutable.Map[Int,String] = Map(9 -> Beckham)
map ++ List(7 -> "Ronaldo", 9 -> "Raul")        //> res35: scala.collection.immutable.Map[Int,String] = Map(1 -> David, 9 -> Ra
                                                //| ul, 7 -> Ronaldo)
map -- List(1,9,2)                              //> res36: scala.collection.immutable.Map[Int,String] = Map()


/*快速排序,好短!*/
def sort(a:List[Int]):List[Int] =
if(a.length < 2) a
else
sort(a.filter(_<a.head)) ++ a.filter(_==a.head) ++ sort(a.filter(_>a.head))
                                                //> sort: (a: List[Int])List[Int]

sort(List(3,1,2,5,2,7))                         //> res37: List[Int] = List(1, 2, 2, 3, 5, 7)
相關文章
相關標籤/搜索