progs/expr.scala
changeset 360 e45d2890749d
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/progs/expr.scala	Sat Nov 14 00:40:47 2020 +0000
@@ -0,0 +1,50 @@
+// 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))
\ No newline at end of file