Solve in Standard Meta Language of New Jersey (SML) and use only recursive defin
ID: 3748315 • Letter: S
Question
Solve in Standard Meta Language of New Jersey (SML) and use only recursive definitions built up from the basic built-in functions!
These functions takes a 2-tuple (e.g. (N,L)) where the first element is an integer (N) and the second is a list (L). The idea is to produce a result in which the elements of the original list have been collected into lists each containing n elements (where N is the integer argument). The leftover elements (if there is any) are included as a tuple with less than N elements. Thus the type of each of these is: int * 'a list -> 'a list list.
The difference between the two functions is how they handle the left-over elements of the list when the integer doesn't divide the length of the list evenly. pairNleft treats the initial elements of the list as the extras, thus the result starts with a list of between 1 and N elements and all the remaining elements of the result list contain N elements. pairNright does the opposite: the final group contains between 1 and N elements and all the rest contain N elements. Note: these functions are not required to be tail-recursive. Examples:
> pairNleft (2,[1, 2, 3, 4, 5])
[[1], [2, 3], [4, 5]]
> pairNright (2,[1, 2, 3, 4, 5])
[[1, 2], [3, 4], [5]]
> pairNleft (3,[1, 2, 3, 4, 5])
[[1, 2], [3, 4, 5]]
> pairNright (3,[1, 2, 3, 4, 5])
[[1, 2, 3], [4, 5]]]
> pairNright (3,[]) (*this may give a warning since the type can’t be inferred*)
[[]]
Explanation / Answer
fun pairNLeft(n, List) =
let
(*creates a rightward sub list of size N to store the remaining list into*)
fun rightSubList(n,[]) = []
| rightSubList(n, List) =
if (((length List) - n) > 0)
then rightSubList(n,(tl List))
else List
fun nLeft(n,[]) = [[]]
| nLeft(0,List) = [List]
| nLeft(n,List) =
if (length List > n)
then rightSubList(n,List)::nLeft(n, getFirstN(((length List) - n), List))
else List::[];
in
reverseList(nLeft(n,List))
end;
fun PairNLeftTests() =
let
fun myTest_pairNleft(n, List, output) =
if pairNLeft(n, List) = output then true else false
val PairNLeftT1 = myTest_pairNleft(2, [1, 2, 3, 4, 5], [[1], [2, 3], [4, 5]])
val PairNLeftT2 = myTest_pairNleft(3, [1, 2, 3, 4, 5], [[1, 2], [3, 4, 5]])
in
print(" [Starting PairNLeft Tests] " ^
"Test1: " ^ Bool.toString(PairNLeftT1) ^ " " ^
"Test2: " ^ Bool.toString(PairNLeftT2) ^ " " ^
"[Ending PairNLeft Tests] ")
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.