progs/expr.scala
author Christian Urban <christian.urban@kcl.ac.uk>
Thu, 03 Nov 2022 09:55:11 +0000
changeset 431 ef68136b9a96
parent 360 e45d2890749d
permissions -rw-r--r--
updated jars

// Scala is about expressions
//
//

1 + 2

val r1 = 1 + 2
val r2 = r1 * r1

val new_list = 
  for (n <- (1 to 10).toList) yield n * n


def my_not_equal(x: Int, y: Int) : Boolean = {
 !(x == y)
}


// why return is not needed in Scala

def sum_even(ls: List[Int]): Int = {
  val aux = for (x <- ls) yield {
    if (x % 2 == 0) x else 0
  }
  aux.sum
}

sum_even(List(1,2,3,4,5,6))

def sum_return(ls: List[Int]): Int = {
  val aux = for (x <- ls) yield {
    if (x % 2 == 0) (return x) else (return 0)
  }
  aux.sum[Int]
}

sum_return(List(2,3,4,5,6))


// replace subexpressions should not 
// change the meaning, but with return it does:

def sq1(n: Int): Int = n * n
def sq2(n: Int): Int = return n * n

def sum_squares(ls: List[Int]): Int = {  
  (for (n <- ls) yield (return n * n)).sum[Int]
}

sum_squares(List(1,2,3,4,5,6))