Question: We defined lists in the class. Write a recursive procedure to get the nth element of the list or throw an IllegalArgumentException if n <0n

We defined lists in the class. Write a recursive procedure to get the nth element of the list or throw an IllegalArgumentException if n<0n<0 or n>=lengthoflistn>=lengthoflist. Assume n=0n=0 obtains the very first element and n=lengthoflist1n=lengthoflist1 yields very last element.

sealed trait NumList case object Nil extends NumList case class Cons(n: Int, l: NumList) extends NumList

def getNthElement(lst: NumList, n: Int): Int = { // YOUR CODE HERE }

val l1 = Nil val l2 = Cons(1, Cons(-1, Nil)) val l3 = Cons(1, Cons(2, l2)) val l4 = Cons(0, Cons(4, Cons(8, l3)))

val test1 = try { getNthElement(Nil, 3); assert(false, "Test 1 : getNthElement(Nil, 3) should raise an IllegalArgumentException. Your code did not.") } catch { case e: IllegalArgumentException => "OK" }

assert(getNthElement(l2, 0) == 1, "Test2: getNthElement(l2, 0) failed (expected answer = 1)") assert(getNthElement(l3, 3) == -1, "Test3: getNthElement(l3, 3) failed (expected answer = -1)") assert(getNthElement(l4, 2) == 8, "Test4: getNthElement(l4, 2) failed (expected answer = 8)")

val test2 = try { getNthElement(l4, 8); assert(false, "Test 5 : getNthElement(l4, 8) should raise an IllegalArgumentException. Your code did not.") } catch { case e: IllegalArgumentException => "OK" }

passed(5)

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!