Fahad/CodeSamples/SequenceComprehensions.scala
author Chengsong
Fri, 26 May 2023 08:09:30 +0100
changeset 646 56057198e4f5
parent 46 79336e47e14d
permissions -rw-r--r--
intro


case class Twice(i: Int) {                              
  def apply(x: Int, y: Int): Int = x * y
  //def unapply(z: Int): Option[Int] = if (z % 2 == 0) Some(z/2) else None
}

Twice(21) match {
  case Twice(n) => println(n)
}

Twice(21, 3) match {
  case Twice(n) => println(n)
}


package Main

object ComprehensionsTest extends App {
  def even(from: Int, to: Int): List[Int] =
    for (i <- List.range(from, to) if i % 2 == 0) yield i

  Console.println(even(0, 20))
}

object ComprehensionsTest2 extends App {
  def foo(n: Int, v: Int) =
    for (
      i <- 0 until n;
      j <- i + 1 until n if i + j == v
    ) yield Pair(i, j);

  foo(20, 32) foreach {
    case (i, j) =>
      println("(" + i + "," + j + ")")
  }
}

object ComprehensionTest3 extends App {
  for (
    i <- Iterator.range(0, 20);
    j <- Iterator.range(i + 1, 20) if i + j == 32
  ) println("(" + i + ", " + j + ")")
}