美文网首页
scala-笔记1

scala-笔记1

作者: JupiterChou | 来源:发表于2018-10-21 23:17 被阅读0次

       一直想写些技术性的笔记,以便自己加深印象以及方便其他人阅读。奈于对自己的文字功底实在不敢恭维,甚至一直舍不得花时间投入这种输出性的写作事项,一直拖到现在。希望自己能坚持下去!


    ```python

    import tensorflow as tfprint(tf.version)

    ```

    `

    val a = List(1,2,3)

    `

    1:两个filter函数合并

    ```

    defdirectedMoreThanOneFilm(numberOfFilms: Int):Seq[String] =

    directors.filter(_.films.size >1).map(_.lastName)defbornBefore(year:

    Int):Seq[String] =   directors.filter(_.yearOfBirth >

    year).map(_.lastName)

    ```

    ```scala

    def and[A](f: A => Boolean, g: A => Boolean): A => Boolean = a => f(a) && g(a)

    ```

    通过上述函数声明,我们可以将其上的两个filter函数进行合并如下:

    ```scala

    defdirectedMoreThanOneFilm:Director=>Boolean= _.films.size >1defbornBefore(year:Int):Director=>Boolean= _.yearOfBirth > yeardefresult=directors.filter(and(directedMoreThanOneFilm, bornBefore(2018))).map(_.lastName)

    ```

    2:将序列类型中的对象分组

    ```scala

    case class Person(val age:Int, val name:String) {

    override def toString = {

    "P = " + age.toString +" / " + name +"; "

      }

    }

    object Person {

    def main(args:Array[String]):Unit = {

    val persons:Seq[Person] =Seq(Person(25, "a"), Person(35, "b"), Person(27, "c"))

    val m = mutable.Map[Int, Seq[Person]]()

    val result =persons.map { person =>

    val ageGroup = person.age /10

          ageGroup -> person

    }

    //print each element in map    method1

    //    result.foreach { case (bracket, person) =>

    //      m(bracket) = m.getOrElse(bracket, Seq[Person]()) :+ person

    //    }

        m.foreach(println)//Having a mutable datastructure outside a function is generally frowned upon.

    //method2

        val resultMap:Map[Int, Seq[Person]] =result.foldLeft(mutable.Map[Int, Seq[Person]]()) {case (map, (ageGroup, person)) =>

    val result2 =m.getOrElse(ageGroup, Seq[Person]()) :+person

          m(ageGroup) =result2

          map(ageGroup) =result2

    map

        }.toMap

    resultMap.foreach(println)// by foldLeft

    //method3

        val mapGourpBy:Map[Int, Seq[Person]] =persons.groupBy(person => math.floor(person.age /10).toInt)

    mapGourpBy.foreach(println)//by GroupBy

      }

    }

    ````

    3:集合自动转换为函数

    ```scala

    val myMap: Map[String, Int] = Map(

        "one" -> 1,

        "two" -> 2,

        "three" -> 3,

        "four" -> 4,

        "five" -> 5,

      )

      val mySet = Set("one", "two", "three")

      println(myMap.filterKeys(mySet)) // Why `Set[String]` could be treated as `[String] => Bool`

    Set extends Function1

    and it's apply is containment

    remember lists do that too

    @ (0 to 5).map(('a' to 'z').toList)

    res9: collection.immutable.IndexedSeq[Char] = Vector('a', 'b', 'c', 'd', 'e', 'f')

    ```

    相关文章

      网友评论

          本文标题:scala-笔记1

          本文链接:https://www.haomeiwen.com/subject/gozbzftx.html