scala 编程思想 --数据

package com.test2

import scala.util.Try

object Zipper {
  def main(args: Array[String]): Unit = {
    //zip进行数据压缩
    val left = Vector("a","b","c","d")
    val right = Vector("q","r","s","t")
    println(left.zip(right))
    println(left.zip(Range(0,4)))
    println(left.zipWithIndex)
    //zipMap
    case class Person(name:String,ID:Int)
    val names = Vector("Bob","Jill","Jim")
    val IDs = Vector(1731,9234,8378)
    names.zip(IDs).map{case(n,id)=>Person(n,id)}

    //scala中case的用法
    val bools = List(true,false)
    for(bool<-bools){
      bool match {
        case true=>println("heads")
        case false=>println("tails")
        case _=>println("somthing other than heads of tails yikes")
      }
    }

    import scala.util.Random
    val randomInt = new Random().nextInt(10)
    randomInt match {
      case 7 =>println("lucky seven!")
      case otherNumber =>println("boo,go boring ol "+otherNumber)
    }

    //根据顺序匹配
    val willWork = List(1,3,24,90)
    val willNotWork = List(4,28,52)
    val empty = List()
    for(l<-List(willWork,willNotWork,empty)){
      l match {
        case List(_,3,_,3)=>println("four elements,with the 2nd being '3'")
        case List(_*) => println("any other list with 0 or more elements.")
      }
    }

    //case 里面用guard的数组匹配
    val tupA = ("Good","Morning!")
    val tupB = ("Gute","Tag!")
    for(tup<-List(tupA,tupB)){
      tup match{
        case (_1,_2) if _1 == "Good"=>{println("A two tuple starting with good")}
        case (_1,_2) =>println(_1,_2)
      }
    }

    case class Person1(name:String,age:Int)
    val alice = Person1("Alice",24)
    val bob = Person1("Bob",32)
    val chalie = Person1("Chalie",32)
    for(person<-List(alice,bob,chalie)){
      person match {
        case Person1("Alice",25)=>println("Hi Alice")
        case Person1("Bob",25)=>println("Hi Bob!")
        case Person1(name,age)=>println("who are you,"+age+"year -lold"+name +"?")
      }
    }
    //正则表达式匹配
    def yielding4(v:Vector[Int])={
      for{
        n<-v
        if n <10
        if(n%2 != 0 )
      }yield {
        for(u<-Range(0,n))
        yield u
      }
    }
    println(yielding4(Vector(0,1,2,3,4,5,6,7,8,9,10)))

    //
    def yielding3(v:Vector[Int]):Vector[Int]={
      for{
        n<-v
        if n < 10
        if(n%2 != 0)
      }yield {
        val u = n * 10
        u + 2
      }
    }

    val v = Vector(1,2,3,4,5,6,7,8,9,10,11,12,17)
    println(yielding3(v))

    Try(
      println("daffas".toInt)
    )

  }
}
发布了131 篇原创文章 · 获赞 27 · 访问量 32万+

猜你喜欢

转载自blog.csdn.net/wangjunji34478/article/details/104145342