scala> def test(m: Int, s: String) { | val A = new Array[Int](3) | val S = new Array[String](3) | val m1 = m + 27 | A(0) = m - 1 | A(1) = m | A(2) = m + 1 | for (i <- 0 until 3) | S(i) = s + A(i) | } test: (m: Int,s: String)Unit
Draw a picture of the heap and of the activation record (stack frame) of the method call test(13, "Hi ") at the time just before the function returns. Draw all objects on the heap referenced directly or indirectly from the activation record.
scala> val A = Array(1, 2, 3, 4) A: Array[Int] = Array(1, 2, 3, 4) scala> val B = Array(1, 2, 3, 4) B: Array[Int] = Array(1, 2, 3, 4) scala> println(A == B) false scala> val C = A C: Array[Int] = Array(1, 2, 3, 4) scala> println(A == C) trueExplain the output. What does the == operator do for two arrays?
scala> class Class1(val x: Int, t: String) { | val s: String = t | } defined class Class1 scala> class Class2(val n: Int, m: Int) { | val t = new Array[Int](m) | } defined class Class2 scala> class Class3(var x: Int) { | val y: Int = 17 | } defined class Class3
Write a function removeThird(A: Stack[Int]): Int that removes and returns the third-from-top element from the pure stack A. For example, if A contains
23 <- top 45 56 78then removeThird(A) returns 56 and leaves A in this state:
23 <- top 45 78
def display(L: List[Int]) { L match { case Nil => Thread.dumpStack() case x :: xs => print(x + " "); display(xs) } } val l = (1 to 5).toList display(l)When I run this script, an exception occurs, with the following error message:
$ scala recurse.scala 1 2 3 4 5 java.lang.Exception: Stack trace at java.lang.Thread.dumpStack(Thread.java:1266) at Main$$anon$1.display(hw3.scala:4) at Main$$anon$1.<init>(hw3.scala:10) at Main$.main(hw3.scala:1) at Main.main(hw3.scala)This surprised me, because it seems that the function display was called only once. I had expected it to look like this:
$ scala recurse.scala 1 2 3 4 5 java.lang.Exception: Stack trace at java.lang.Thread.dumpStack(Thread.java:1266) at Main$$anon$1.display(hw3.scala:4) at Main$$anon$1.display(hw3.scala:5) at Main$$anon$1.display(hw3.scala:5) at Main$$anon$1.display(hw3.scala:5) at Main$$anon$1.display(hw3.scala:5) at Main$$anon$1.display(hw3.scala:5) at Main$$anon$1.<init>(hw3.scala:10) at Main$.main(hw3.scala:1) at Main.main(hw3.scala)Explain why I do not see this output, but the one above.
def find(L: List[String], x: String): List[String] = { var p = L while (p != Nil && p.head != x) p = p.tail p }Write a new method findLast(L: List[String], x: String) that returns the list starting with the last occurrence of \(x\).