6. Consider the following Scala methods. Analyze their code and their behavior o
ID: 3888149 • Letter: 6
Question
6. Consider the following Scala methods. Analyze their code and their behavior on a few input examples to gure out what they do. For m assume that both input lists are ordered increasingly.
def m(l1:List[Int], l2:List[Int]):List[Int] =
(l1, l2) match
{
case (Nil, _) => l2
case (_, Nil) => l1
case (h1 :: t1, h2 :: t2) =>
{
if (h1 < h2)
h1 :: m(t1, l2)
else
h2 :: m(l1, t2)
}
}
def s(l:List[Int]) =
{
def s_aux(l0:List[Int], l1:List[Int], l2:List[Int]):(List[Int], List[Int]) =
l0 match
{
case Nil => (l1, l2)
case x :: Nil => (x :: l1, l2)
case x1 :: x2 :: t => s_aux(t, x1 :: l1, x2 :: l2)
}
s_aux(l, Nil, Nil)
}
For each method write in a Scala comment a concise description in English of its functionality, along the lines of the descriptions provided for the methods in the previous problems (given this and that, it returns so and so). Just describe the input-output behavior of the method, not the internal algorithm.
Explanation / Answer
Please find my answer:
This function merging the two sorted list.
So, input consition: list should be sorted
Output: Sorted list that contains all elements from list1 and list2
def m(l1:List[Int], l2:List[Int]):List[Int] =
(l1, l2) match
{
// if l1 is null, then return l2
case (Nil, _) => l2
// if l2 is null, then return l1
case (_, Nil) => l1
// merging two list
case (h1 :: t1, h2 :: t2) =>
{
// if first element of l1 is smaller than
// the first element of l2 then calling function recursivey
// and appending first element of l1 to the result of recursive call
if (h1 < h2)
h1 :: m(t1, l2)
// if first element of l2 is smaller than
// the first element of l2 then calling function recursivey
// and appending first element of l2 to the result of recursive call
else
h2 :: m(l1, t2)
}
}
Example:
Output: List(1, 1, 3, 3, 4, 5)
#########
This function takes three list and output two list.
It appends alternate element of l0 to l1 and l2.
def s(l:List[Int]) =
{
def s_aux(l0:List[Int], l1:List[Int], l2:List[Int]):(List[Int], List[Int]) =
l0 match
{
// if list l0 is null then return l1 and l2
case Nil => (l1, l2)
// if list l0 have only one element then append that element to l1 and return l1 and l2
case x :: Nil => (x :: l1, l2)
// if l0 have more than one element then append first element of l0 to l1 and second element
// of l0 to l2 and recursively call function
case x1 :: x2 :: t => s_aux(t, x1 :: l1, x2 :: l2)
}
// this fucntion return appended value of l1 and l2
s_aux(l, Nil, Nil)
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.