Creating a function in Ocaml that takes a derivative of a list of integers. Show
ID: 3888165 • Letter: C
Question
Creating a function in Ocaml that takes a derivative of a list of integers. Shown below is the actual question given:
list_deriv : int list -> int list: the list_deriv function takes the "derivative" of a list of integers by taking n integers ad returning the list of n-1 differences between the consecutive integers, so list_deriv [ 0; 8; 14; 3 ] evaluates to [8; 6; -11] and list_deriv [ 0; 1; 1; 2; 3; 5; 8 ] evaluates to [1; 0; 1; 1; 2; 3]. You might find it cleanest to use a nested helper function to deal with the core logic while an outer match takes care of the two special cases that could arise.
Explanation / Answer
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
//Class ListDerivation definition
public class ListDerivation
{
//Method to accept integer data and add it to the list
List acceptData(List<Integer> l)
{
//Creates Scanner class object
Scanner sc = new Scanner(System.in);
//Creates a list of type integer
List<Integer> result = new ArrayList<Integer>();
//Accepts the size of the list
System.out.println(" Enter the size of the list: ");
int no = sc.nextInt();
//Accepts numbers for the list
System.out.printf(" Enter %d numbers: ", no);
//Loops till size
for(int counter = 0; counter < no; counter++)
//Accept an integer data form console and add it to list
result.add(sc.nextInt());
//Returns the result list
return result;
}//End of method
//Returning the list of n-1 differences between the consecutive integers
List list_deriv(List<Integer> l)
{
//Creates a list of type integer
List<Integer> result = new ArrayList<Integer>();
//Loops till size minus one
for(int counter = 0; counter < l.size()-1; counter++)
{
//Extracts next counter position and current position from the list
//Subtracts current position valur from the next positioin value
//Adds the result to the list
result.add((l.get(counter+1) - l.get(counter)));
}//End of for loop
//Returns the result list
return result;
}//End of method
//Main method definition
public static void main(String[] args)
{
//Creates a list of type integer
List<Integer> list = new ArrayList<Integer>();
List<Integer> res;
//Creates ListDerivation class object
ListDerivation ld = new ListDerivation();
//Calls the method to add number to the list
res = ld.acceptData(list);
System.out.println("Before: " + res);
//Calculates the difference
res = ld.list_deriv(res);
//Displays the result
System.out.println("After: " + res);
}//End of main method
}//End of class
Sample Run 1:
Enter the size of the list: 7
Enter 7 numbers:
0
1
1
2
3
5
8
Before: [0, 1, 1, 2, 3, 5, 8]
After: [1, 0, 1, 1, 2, 3]
Sample Run 2:
Enter the size of the list: 4
Enter 4 numbers:
0
8
14
3
Before: [0, 8, 14, 3]
After: [8, 6, -11]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.