Skip to content

Instantly share code, notes, and snippets.

@mikegehard
Last active October 7, 2016 23:05
Show Gist options
  • Save mikegehard/a7dc8eb2126446cfe1827d62e856c4f6 to your computer and use it in GitHub Desktop.
Save mikegehard/a7dc8eb2126446cfe1827d62e856c4f6 to your computer and use it in GitHub Desktop.
enum class EducationLevel {
HIGH_SCHOOL, BACHELORS, MASTERS, PHD
}
data class Person(val age: Int, val smoker: Boolean, val income: Int, val education: EducationLevel)
val people = listOf(
Person(19, false, 10000, EducationLevel.HIGH_SCHOOL),
Person(49, true, 120000, EducationLevel.BACHELORS),
Person(55, false, 400000, EducationLevel.MASTERS),
Person(23, true, 10000, EducationLevel.BACHELORS),
Person(70, false, 70000, EducationLevel.PHD),
Person(34, false, 90000, EducationLevel.MASTERS),
Person(90, true, 0, EducationLevel.HIGH_SCHOOL)
)
fun income_by_smoking(people: List<Person>) =
people
.exclude_incomes_under(10000).
separate_people_by { it.smoker }.
average_income()
fun List<Person>.exclude_incomes_under(amount: Int): List<Person> =
this.filter { it.income > amount }
fun <K> List<Person>.separate_people_by(selector: (Person) -> K): Map<K, List<Person>> =
this.groupBy { selector(it) }
fun Map<out Any, List<Person>>.average_income(): Map<out Any, Int> =
this.mapValues { it.value.sumBy { it.income } }
fun main(args: Array<String>) {
val message = """
Result: ${income_by_smoking(people)}
"""
println(message)
}
enum class EducationLevel {
HIGH_SCHOOL, BACHELORS, MASTERS, PHD
}
data class Person(val age: Int, val smoker: Boolean, val income: Int, val education: EducationLevel)
val people = listOf(
Person(19, false, 10000, EducationLevel.HIGH_SCHOOL),
Person(49, true, 120000, EducationLevel.BACHELORS),
Person(55, false, 400000, EducationLevel.MASTERS),
Person(23, true, 10000, EducationLevel.BACHELORS),
Person(70, false, 70000, EducationLevel.PHD),
Person(34, false, 90000, EducationLevel.MASTERS),
Person(90, true, 0, EducationLevel.HIGH_SCHOOL)
)
fun income_by_smoking(people: List<Person>) =
people
.exclude_incomes_under(10000).
separate_people_by { it.smoker }.
average_income()
fun List<Person>.exclude_incomes_under(amount: Int) =
this.filter { it.income > amount }
fun <K> List<Person>.separate_people_by(selector: (Person) -> K) =
this.groupBy { selector(it) }
fun Map<out Any, List<Person>>.average_income() =
this.mapValues { it.value.sumBy { it.income } }
fun main(args: Array<String>) {
val message = """
Result: ${income_by_smoking(people)}
"""
println(message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment