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

      

  • 相关阅读:
    项目冲刺之任务场景分析
    一位数组的最大子数组(debug版)
    软件工程课堂五(地铁项目的优化)
    人月神话阅读笔记02
    软件工程第七周总结
    人月神话阅读笔记01
    软件工程第六周总结
    构建之法阅读笔记03
    软件工程第五周总结
    软件工程课堂四(合作开发项目-地铁线路查询)
  • 原文地址:https://www.cnblogs.com/zidafone/p/5785298.html
Copyright © 2011-2022 走看看