Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

do this in java The following imperative method takes a list of integers and ret

ID: 3577639 • Letter: D

Question

do this in java

The following imperative method takes a list of integers and returns a list consisting of all the even integers in the original list (in the original order).

def getEvens(input: List[Int]): List[Int] = {

var currentList = input

var resultList: List[Int] = List()

while (currentList.length != 0) {

if (currentList(0) % 2 == 0) {

resultList = currentList(0) :: resultList

}

currentList = currentList.tail

}

resultList.reverse

}

a) Rewrite this method in a purely functional style using list pattern matching and recursion.

b) Rewrite it a second time in a purely functional style using the filter higher order method.

Explanation / Answer

a) with recusrsion
public static int eNumRec(List<Integer> arr,int index){
       if(arr.size()==index)//stop recursion
           return 0;
      
       int result;
       if((arr.get(index)%2)==0){ //is even
           result=1;
       }
      
       else{ //is odd
           result=0;
       }
       return result+eNumRec(arr,index+1);
   }

b) with filter higher order method

public static int eNumHigh(List<Integer> arr){
       int even=0;
       for(int i=0;i<arr.size();i++){
           if(arr.get(i)%2==0)
               even++;
       }
      
       return even;
   }