A Kotlin program should be written to check if a list is sorted or not using a generic checkSorting() function that accepts the list and a comparison function. The function should work for any Number subtype lists. It should return True if sorted based on the comparison condition, else False. checkSorting() needs to be pure, recursive and use an internal helper function. The program should be tested using at least two Number subtype calls from main. Extension functions like tail() and head() are required to compare list elements by accessing the first and remaining elements.
Seal of Good Local Governance (SGLG) 2024Final.pptx
Write a Kotlin program with a checkSorting generic functio.pdf
1. Write a Kotlin program with a checkSorting() generic function. The checkSorting()
function accepts two arguments: an input list and a function that determines the
comparison condition. The function should be able to accept any list belonging to the
Number supertype. The user should be able to specify through the function argument the
condition using which a list will be considered sorted. For example, a list (1,2,3,4,5) is
considered sorted if we are using a comparison condition where each (n-1)th element
should be less than each nth element, otherwise it is considered unsorted. The function
checkSorting() returns True of a list is sorted, otherwise it returns false.
Please note that checkSorting should be written as a pure function, therefore, it should be
recursive and use an internal helper function. Test your program by at least two calls to this
function from main using any two distinct number subtypes of your choice.
Hint: To compare elements of an array, you will need to write two extension functions. An
extension function allows you to add helpful behavior for a type or instance. To declare an
extension function, prefix its name with the type of the data to which you would like to add
the behavior. The following is an example of an extension function show() that we would like
to apply to an Int to show the Ints value.
fun Int.show(): String = "The value of this Int is $this"
1.show()
res1: kotlin.String = The value of this Int is 1
The two extension function you will require are tail() and head(). tail() uses the drop method
for lists which returns a list containing all elements except the first n elements. head() uses
the first method for lists which returns the first element on the list. For more information,
please refer to the following links:
Extension functions: http://developer.android.com
drop(): https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/drop.html
first(): https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/first.html