do this in java The following imperative method takes a list of integers and ret
ID: 3579639 • 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;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.