⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 patmatnew.scala

📁 JAVA 语言的函数式编程扩展
💻 SCALA
📖 第 1 页 / 共 2 页
字号:
trait Treez { self: Shmeez =>  abstract class Tree  case class Beez(i:Int) extends Tree  case object HagbardCeline extends Tree}trait Shmeez extends AnyRef with Treez {  val tree: Tree  def foo = tree match {    case Beez(2) => 1    case HagbardCeline => 0  }}import scala.testing.SUnit._object Test extends TestConsoleMain {  //just compilation  def zipFun[a,b](xs:List[a], ys:List[b]):List[Pair[a,b]] = (Pair(xs,ys): @unchecked) match {    // !!! case Pair(List(), _), Pair(_, List()) => List()    case Pair(x :: xs1, y :: ys1) => Pair(x, y) :: zipFun(xs1, ys1)  }  def suite = new TestSuite(      new TestSimpleIntSwitch,      new SimpleUnapply,      SeqUnapply,      applyFromJcl,      new Test717,      TestGuards,      TestEqualsPatternOpt,      TestSequence01,      TestSequence02,      TestSequence03,      TestSequence04,      TestSequence05,      TestSequence06,      TestSequence07,      TestSequence08,      TestStream,      new Test903,      new Test1163_Order,      new TestUnbox,      Bug457,      Bug508,      Bug789,      Bug995,      Bug1093,      Bug1094,      ClassDefInGuard,      Ticket2,      Ticket11,      Ticket37,      Ticket44,      Ticket346    )  class Foo(j:Int) {    case class Bar(i:Int)  }  class SimpleUnapply extends TestCase("simpleUnapply") {    override def runTest() { // from sortedmap, old version      List((1,2)).head match {        case kv @ Pair(key, _) => kv.toString + " " + key.toString      }    }  }  object SeqUnapply extends TestCase("seqUnapply") {    case class SFB(i:int,xs:List[Int])    override def runTest() {       List(1,2) match {        case List(1) => assert(false, "wrong case")        case List(1,2,xs @ _*) => assert(xs.isEmpty, "not empty")        case Nil => assert(false, "wrong case")      }      SFB(1,List(1)) match {        case SFB(_,List(x)) => assert(x==1)        case SFB(_,_) => assert(false)      }    }  }  object applyFromJcl extends TestCase("applyFromJcl") {    override def runTest {      val p = (1,2)        Some(2) match {          case Some(p._2) =>         ;          case _ => assert(false) ;        }    }  }  class TestSimpleIntSwitch extends TestCase("SimpleIntSwitch") {    override def runTest() = {      assertEquals("s1", 1, 1 match {        case 3 => 3        case 2 => 2        case 1 => 1        case 0 => 0      })      assertEquals("s2", 1, 1 match {        case 1 => 1         case _ => 0      })      assertEquals("s2boxed", 1, (1:Any) match {        case 1 => 1         case _ => 0      })      assertEquals("s3", 1, ("hello") match {        case s:String => 1        //case _        => 0 // unreachable!      })      val xyz: (int, String, boolean) = (1, "abc", true);      assertEquals("s4", 1, xyz._1 match {        case 1 => 1        case _ => 0      })    }  }  class Test717 extends TestCase("#717 test path of case classes") {    val foo1 = new Foo(1)    val foo2 = new Foo(2)    override def runTest() = {      val res = (foo1.Bar(2):Any) match {       case foo2.Bar(2) => false       case foo1.Bar(2) => true      }      assertTrue("ok", res);    }  }  object TestGuards extends TestCase("multiple guards for same pattern") with Shmeez {    val tree:Tree = Beez(2)    override def runTest = {      val res = tree match {        case Beez(x) if x == 3 => false        case Beez(x) if x == 2 => true      }      assertTrue("ok", res);      val ret = (Beez(3):Tree) match {        case Beez(x) if x == 3 => true        case Beez(x) if x == 2 => false      }      assertTrue("ok", ret);    }  }  object TestEqualsPatternOpt extends TestCase("test EqualsPatternClass in combination with MixTypes opt, bug #1276") {    val NoContext = new Object    override def runTest {      assertEquals(1,((NoContext:Any) match {        case that : AnyRef if this eq that => 0        case NoContext => 1        case _ => 2      }))    }  }  object TestSequence01 extends TestCase("uno (all ignoring patterns on List)") {    def doMatch(xs: List[String]): String = xs match {      case List(_*) => "ok"    }    def doMatch2(xs: List[String]): List[String] = xs match {      case List(_, rest @ _*) => rest.toList    }    override def runTest() {      val list1 = List()      assertEquals(doMatch(list1), "ok")      val list2 = List("1","2","3")      assertEquals(doMatch(list2), "ok")      val list3 = List("1","2","3")      assertEquals(doMatch2(list3), List("2","3"))    }  }  object TestSequence02 extends TestCase("due (all ignoring patterns on Seq)") {    def doMatch(l: Seq[String]): String = l match {      case Seq(_*) => "ok"    }    override def runTest() {      val list1 = List()      assertEquals(doMatch(list1), "ok")      val list2 = List("1", "2", "3")      assertEquals(doMatch(list2), "ok")      val array3 = Array[String]()      assertEquals(doMatch(array3), "ok")      val array4 = Array[String]("ga", "gu")      assertEquals(doMatch(array4), "ok")    }  }  object TestSequence03 extends TestCase("tre (right-ignoring patterns on List, defaults)") {    def doMatch(xs: List[String]): String = xs match {      case List(_,_,_,_*) => "ok"      case _ => "not ok"    }    override def runTest() {      val list1 = List()      assertEquals(doMatch(list1), "not ok")      val list2 = List("1","2","3")      assertEquals(doMatch(list2), "ok")      val list3 = List("1","2","3","4")      assertEquals(doMatch(list3), "ok")    }  }  object TestSequence04 extends TestCase("quattro (all- and right-ignoring pattern on case class w/ seq param)") {    case class Foo(i: Int, chars: Char*)    override def runTest() = {      val a = Foo(0, 'a') match {        case Foo(i, c, chars @ _*) => c        case _ => null      }      assertEquals(a, 'a')      val b = Foo(0, 'a') match {        case Foo(i, chars @ _*) => 'b'        case _ => null      }      assertEquals(b, 'b')    }  }  object TestSequence05 extends TestCase("cinque (sealed case class with ignoring seq patterns)") {    sealed abstract class Con;    case class Foo() extends Con    case class Bar(xs:Con*) extends Con        override def runTest() {      val res = (Bar(Foo()):Con) match {        case Bar(xs@_*) => xs // this should be optimized away to a pattern Bar(xs)        case _ => Nil      }      assertEquals("res instance"+res.isInstanceOf[Seq[Con] forSome { type Con }]+" res(0)="+res(0), true, res.isInstanceOf[Seq[Foo] forSome { type Foo}] && res(0) == Foo() )    }  }  object TestSequence06 extends TestCase("sei (not regular) fancy guards / bug#644 ") {        case class A(i: Any)         def doMatch(x: Any, bla: int) = x match {      case x:A if (bla==1) => 0      case A(1) => 1      case A(A(1)) => 2    }    override def runTest() {      assertEquals(doMatch(A(null),1), 0)      assertEquals(doMatch(A(1),2), 1)      assertEquals(doMatch(A(A(1)),2), 2)    }  }  object TestSequence07 extends TestCase("sette List of chars") {    def doMatch1(xs: List[char]) = xs match {      case List(x, y, _*) => x::y::Nil    }    def doMatch2(xs:List[char]) = xs match {      case List(x, y, z, w) => List(z,w)    }    //def doMatch3(xs:List[char]) = xs match {    //  case List(_*, z, w) => w::Nil    //}    def doMatch4(xs:Seq[Char]) = xs match {      case Seq(x, y, _*) => x::y::Nil      case Seq(x, y, z, w) => List(z,w) // redundant!    }    def doMatch5(xs:Seq[Char]) = xs match {      case Seq(x, y, 'c', w @ _*) => x::y::Nil      case Seq(x, y, z @ _*)    => z    }    def doMatch6(xs:Seq[Char]) = xs match {      case Seq(x, 'b')            => x::'b'::Nil      case Seq(x, y, z @ _*)    => z.toList    }    override def runTest() {      assertEquals(List('a','b'), doMatch1(List('a','b','c','d')))      assertEquals(List('c','d'), doMatch2(List('a','b','c','d')))      //assertEquals(doMatch3(List('a','b','c','d')), List('d'))      assertEquals(List('a','b'), doMatch4(List('a','b','c','d')))      assertEquals(List('a','b'), doMatch5(List('a','b','c','d')))      assertEquals(List('c','d'), doMatch6(List('a','b','c','d')))    }  }   object TestSequence08 extends TestCase("backquoted identifiers in pattern") {     override def runTest() {      val xs = List(2, 3)      val ys = List(1, 2, 3) match {        case x :: `xs` => xs        case _ => Nil      }      assertEquals(xs, ys)    }  }  object TestStream extends TestCase("unapply for Streams") {    def sum(stream: Stream[int]): int =      stream match {        case Stream.empty => 0        case Stream.cons(hd, tl) => hd + sum(tl)      }        val str: Stream[int] = Stream.fromIterator(List(1,2,3).elements)    def runTest() = assertEquals(sum(str), 6)  }    class Test1163_Order extends TestCase("bug#1163 order of temps must be preserved") {    abstract class Function    case class Var(n: String) extends Function    case class Const(v: double) extends Function        def f(): (Function, Function) = {      (Var("x"): Function, Var("y"): Function) match {        case (Const(v), Const(w)) => throw new Error        case (leftOne, Var("z")) => throw new Error        case (leftTwo, rightTwo) => (leftTwo, rightTwo) // was giving "y","x"      }    }        def flips(l: List[int]): int = (l: @unchecked) match {       case 1 :: ls => 0      case n :: ls => flips((l take n reverse) ::: (l drop n)) + 1    }    def runTest() =  assertEquals("both", (Var("x"),Var("y")), f)   }  class TestUnbox extends TestCase("unbox") {    override def runTest() {      val xyz: (int, String, boolean) = (1, "abc", true)      xyz._1 match {        case 1 => "OK"        case 2 => assert(false); "KO"        case 3 => assert(false); "KO"      }    }  }  class Test806_818 { // #806, #811 compile only -- type of bind    // bug811    trait Core {      trait NodeImpl;      trait OtherImpl extends NodeImpl;      trait DoubleQuoteImpl extends NodeImpl;      def asDQ(node : OtherImpl) = node match {	case dq : DoubleQuoteImpl => dq;      }    }        trait IfElseMatcher {       type Node <: NodeImpl;      trait NodeImpl;      trait IfImpl;       private def coerceIf(node : Node) = node match {        case node : IfImpl => node; // var node is of type Node with IfImpl!        case _ => null;      }    }      }  class Person(_name : String, _father : Person) {    def name = _name    def father = _father  }  object PersonFather {    def unapply(p : Person) : Option[Person]  =       if (p.father == null)        None      else  	    Some(p.father)  }  class Test903 extends TestCase("bug903") {  override def runTest = {    val p1 = new Person("p1",null)    val p2 = new Person("p2",p1)    assertEquals((p2.name, p1.name), p2 match {      case aPerson@PersonFather(f) => (aPerson.name,f.name)      case _ => "No father"    })  }  }  object Test1253  { // compile-only    def foo(t : (Int, String)) = t match {      case (1, "") => throw new Exception      case (r, _) => throw new Exception(r.toString)    }  }  object Foo1258 {    case object baz    def foo(bar : AnyRef) = {      val Baz = baz      bar match {        case Baz => ()      }    }  }  object Foo1 {    class Bar1(val x : String)    def p(b : Bar1) = Console.println(b.x)        def unapply(s : String) : Option[Bar1] =      Some(new Bar1(s))  }    object bug881 extends TestCase("881") {    override def runTest = {      "baz" match {        case Foo1(x) =>          Foo1.p(x)      }    }  }  // these are exhaustive matches  //   should not generate any warnings  def f[A](z:(Option[A],Option[A])) = z match {    case Pair(None,Some(x)) => 1    case Pair(Some(x),None ) => 2    case Pair(Some(x),Some(y)) => 3    case _ => 4  }    def g1[A](z:Option[List[A]]) = z match {    case Some(Nil) => true        case Some(x::Nil) => true      case _ => true  }    def g2[A](z:Option[List[A]]) = z match {    case Some(x::Nil) => true      case Some(_) => false    case _ => true  }    def h[A](x: (Option[A],Option[A])) = x match {    case Pair(None,_:Some[_]) => 1    case Pair(_:Some[_],None ) => 2    case Pair(_:Some[_],_:Some[_]) => 3    case _ => 4  }  def j = (List[Int](), List[Int](1)) match {    case (Nil, _) => 'a'

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -