In: Computer Science
a. Define a function less of type (String, List) -> List so that less(e, L) is a list of all the strings in L that are shorter than e.
b. Define a function more of type (String, List) -> List so that more(e, L) is a list of all the strings in L that are longer than e.
c. Replace the above functions with a function compare of type (String, List, (String, String) -> Boolean) such that depending on the lambda passed it could perform both as less or more. Kindly note that solutions are expected to use single value variables and no iteration.
Part a is done!
fun less(e:String, L:List<String>):
List<String>
{
if (L.isEmpty()) return listOf()
if (L[0].length < e.length) return (listOf(L[0]) +
less(e,L.subList(1,L.size)))
else return (less(e,L.subList(1,L.size)))
}
less("no", listOf("not","yes","a","hello"))
Answer In Kotlin Please.
fun less(e:String, L:List<String>): List<String> { if (L.isEmpty()) return listOf() return if (L[0].length < e.length) (listOf(L[0]) + less(e,L.subList(1,L.size))) else (less(e,L.subList(1,L.size))) } fun more(e:String, L:List<String>): List<String> { if (L.isEmpty()) return listOf() return if (L[0].length > e.length) (listOf(L[0]) + more(e,L.subList(1,L.size))) else (more(e,L.subList(1,L.size))) } fun compare(e:String, L: List<String>, f: (String, String) -> Boolean):List<String>{ if (L.isEmpty()) return listOf() return if (f(e,L[0])) (listOf(L[0]) + compare(e,L.subList(1,L.size),f)) else (compare(e,L.subList(1,L.size),f)) }