val groups: List<Group> = +listOf(
Group("Boys", students.filter { it.name in boys }),
Group("Girls", students.filter { it.name in girls })
)
class Group(
val name: String,
val students: List<Student>,
){
override fun toString() = "$name $students"
}
[Boys [Sheldon, Leonard, Howard, Raj],
Girls [Penny, Amy, Bernadette]]
public inline fun <T> Iterable<T>.filter(
predicate: (T) -> Boolean
): List<T> {
return filterTo(ArrayList<T>(), predicate)
}
public inline fun <T, C : MutableCollection<in T>>
Iterable<T>.filterTo(
destination: C,
predicate: (T) -> Boolean): C {
for (element in this)
if (predicate(element))
destination.add(element)
return destination
}
val grades: List<Grade> = listOf(
"Sheldon" to 5,
"Leonard" to 4,
"Howard" to 4,
"Raj" to 3
).map { grade: Pair<String, Int> ->
Grade(students.find { it.name == grade.first }!!, grade.second)
}
class Grade(
val student: Student,
val value: Int
){
override fun toString() = "$student - $value"
}
public inline fun <T>
Iterable<T>.find(predicate: (T) -> Boolean): T? {
return firstOrNull(predicate)
}
public inline fun <T>
List<T>.findLast(predicate: (T) -> Boolean): T? {
return lastOrNull(predicate)
}
public inline fun <T>
Iterable<T>.first(predicate: (T) -> Boolean): T {
for (element in this)
if (predicate(element))
return element
throw NoSuchElementException("...")
}
public inline fun <T, R> Iterable<T>.fold(
initial: R,
operation: (acc: R, T) -> R
): R {
var accumulator = initial
for (element in this)
accumulator = operation(accumulator, element)
return accumulator
}
val averageGradeFold =
grades.fold(0) { acc, grade ->
acc + grade.value
} / grades.size
public inline fun <S, T : S> Iterable<T>.reduce(
operation: (acc: S, T) -> S
): S
public inline fun <T> Iterable<T>.all(
predicate: (T) -> Boolean
): Boolean {
if (this is Collection && isEmpty()) return true
for (element in this)
if (!predicate(element))
return false
return true
}
public inline fun <T> Iterable<T>.any(
predicate: (T) -> Boolean
): Boolean {
if (this is Collection && isEmpty()) return false
for (element in this)
if (predicate(element))
return true
return false
}
val sortedGrades = grades.sortedBy { it.value }
public inline fun <T, R : Comparable< R >>
Iterable<T>.sortedBy(
crossinline selector: (T) -> R?
): List<T> {
return sortedWith(compareBy(selector))
}
val minReduce = grades
.map { it.value }
.reduce { acc, grade ->
if (acc < grade)
acc
else
grade
}