CS 245 - Programming Languages

Lab 9

Kotlin List Programs

In this lab you will write, three small programs in Kotlin.

In all of the programs below you may NOT use

  1. any variable declared to be a var (either explicitly or implicitly)
  2. Any loop construct
Do this one last
Write two versions of a program which flattens lists of unlimited depth. (in homework3 you dealt with Lists of lists, ie depth 2.) Specifically, consider a list. The elements in the list are items which may be either integers or lists. The contained lists abide by the same rule as the top level list. For example, the following is a legal list:
        (12, 6, (1, (2)),(3,4))
        
In kotlin, the following will create such a list:
        val lst: List<Any?> = listOf(12,6,listOf(1,listOf(2)), listOf(3,4))
    
Your program should "flatten" the provided list and return the flattened list. Items in the flattened list my be in any order. For instance, for the first example above, the following is an acceptable result:
        (6,12,3,4,1,2)
    
I have no idea why you program would produce such a result, but it would be OK. (My programs always preserve order.)

Some thoughts:

What to hand in

Work no more than 80 minutes on the above programs. If you did not complete everything, send what you have.

Part 2

The starter code contains a data class for Student. Implement the function registerStudents(names: List<String>, startId: Int = 0) to produce a List<Student>. Assign different ids to students starting from starting from an optionally provided number.
    data class Student(val id: Int, val name: String)

fun main() {
  val students = listOf("Alice", "Bob")
  registerStudents(students) 

  registerStudents(students, startId = 10) 
}

Implement two versions of registerStudents. In the first, just write you own recursive function. For the second, look up the mapIndexed function of Kotlin and use that.

Send email to gtowell245@cs.brynmawr.edu with all three programs. Along with the first and third program should be a main function that contains tests which should your program in operation.

Part 3

Look up the definition and usage of the function mapIndexedNotNull. Use this function to do the following.
  1. return a list that is composed of only the even numbered items in a list
  2. Given a list of strings, return a list that is composed of only those strings in every third position AND that have a length greater than 5. Use both mapIndexedNotNull and filter to do so.