Question: IN SCALA 1a. Write a function countZeros that inputs a list of numbers lst and counts how many elements of lst are equal to zero.

IN SCALA

1a. Write a function countZeros that inputs a list of numbers lst and counts how many elements of lst are equal to zero.

Restrictions:

Your function must be recursive (not necessary that it be tail recursive).

You cannot use loops (for-loops, while loops etc..), and no mutables (var).

You cannot use return statement in your function.

List Operations allowed:

list.length - length of a list;

list.head - extract the first element of a list;

list.tail - extract the sublist from the second element to last element of list.

No other list API functions or API functions of any other data structure allowed. E.g., do not look to convert your list into an array and use some Array API function.

1b.

Write a tail recursive version of the countZero function described in Problem 1. Call your tail recursive function countZeroTail. Place a @tailrec decorator in front of your function. Some Scala versions (Scala < 2.12?) may require you to declare your function with the final keyword in front.

final def countZeroTail(lst:List[Int],....): Int = { ... }

Restrictions:

Same restrictions as Problem 1a.

Your function must be tail recursive.

Calling countZero from inside your countZeroTail function is not allowed. In fact, it won't be a tail recursion if you are doing so.

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!