From ed6ffe34fa75a9790459b313c63a31d4cc463f79 Mon Sep 17 00:00:00 2001 From: James Strachan Date: Sat, 17 Mar 2012 09:35:35 +0000 Subject: [PATCH] added an experiment of compositional map/filter style functions on nullables to mimick Scala's Option behaviour without any wrapper classes --- libraries/stdlib/src/Nullables.kt | 184 ++++++++++++++++++ .../stdlib/test/language/scala/OptionTest.kt | 36 ++-- 2 files changed, 202 insertions(+), 18 deletions(-) create mode 100644 libraries/stdlib/src/Nullables.kt diff --git a/libraries/stdlib/src/Nullables.kt b/libraries/stdlib/src/Nullables.kt new file mode 100644 index 00000000000..2ba85f933ff --- /dev/null +++ b/libraries/stdlib/src/Nullables.kt @@ -0,0 +1,184 @@ +package kotlin.nullable + +import java.util.* +import kotlin.util.getOrPut + +/** Returns true if the element is not null and matches the given predicate */ +inline fun T?.any(predicate: (T)-> Boolean): Boolean { + return this != null && predicate(this) +} + +/** Returns true if the element is not null and matches the given predicate */ +inline fun T?.all(predicate: (T)-> Boolean): Boolean { + return this != null && predicate(this) +} + +/** Returns the 1 if the element is not null else 0 */ +inline fun T?.count(predicate: (T)-> Boolean): Int { + return if (this != null) 1 else 0 +} + +/** Returns the first item which matches the predicate if this element is not null else null */ +inline fun T?.find(predicate: (T)-> Boolean): T? { + return if (this != null && predicate(this)) this else null +} + +/** Returns a new List containing all elements in this collection which match the given predicate */ +inline fun T?.filter(predicate: (T)-> Boolean): T? = find(predicate) + +/** Filters all elements in this collection which match the given predicate into the given result collection */ +inline fun > T?.filterTo(result: C, predicate: (T)-> Boolean): C { + if (this != null && predicate(this)) + result.add(this) + return result +} + +/** Returns a List containing all the non null elements in this collection */ +inline fun T?.filterNotNull(): Collection = filterNotNullTo(java.util.ArrayList()) + +/** Filters all the null elements in this collection winto the given result collection */ +inline fun > T?.filterNotNullTo(result: C): C { + if (this != null) { + result.add(this) + } + return result +} + +/** Returns a new collection containing all elements in this collection which do not match the given predicate */ +inline fun T?.filterNot(predicate: (T)-> Boolean): Collection = filterNotTo(ArrayList(), predicate) + +/** Returns a new collection containing all elements in this collection which do not match the given predicate */ +inline fun > T?.filterNotTo(result: C, predicate: (T)-> Boolean): C { + if (this != null && !predicate(this)) { + result.add(this) + } + return result +} + +/** + * Returns the result of transforming each item in the collection to a one or more values which + * are concatenated together into a single collection + */ +inline fun T?.flatMap(transform: (T)-> Collection): Collection { + return flatMapTo(ArrayList(), transform) +} + +/** + * Returns the result of transforming each item in the collection to a one or more values which + * are concatenated together into a single collection + */ +inline fun T?.flatMapTo(result: Collection, transform: (T)-> Collection): Collection { + if (this != null) { + val coll = transform(this) + if (coll != null) { + for (r in coll) { + result.add(r) + } + } + } + return result +} + +/** Performs the given operation on each element inside the collection */ +inline fun T?.forEach(operation: (element: T) -> Unit) { + if (this != null) { + operation(this) + } +} + +/** + * Folds all the values from from left to right with the initial value to perform the operation on sequential pairs of values + * + * For example to sum together all numeric values in a collection of numbers it would be + * {code}val total = numbers.fold(0){(a, b) -> a + b}{code} + */ +inline fun T?.fold(initial: T, operation: (it: T, it2: T) -> T): T { + return if (this != null) { + operation(initial, this) + } else { + initial + } +} + +/** + * Folds all the values from right to left with the initial value to perform the operation on sequential pairs of values + */ +inline fun T?.foldRight(initial: T, operation: (it: T, it2: T) -> T): T { + // maximum size is 1 so it makes no difference :) + return fold(initial, operation) +} + +/** + * Iterates through the collection performing the transformation on each element and using the result + * as the key in a map to group elements by the result + */ +inline fun T?.groupBy(result: Map> = HashMap>(), toKey: (T)-> K): Map> { + if (this != null) { + val key = toKey(this) + val list = result.getOrPut(key){ ArrayList() } + list.add(this) + } + return result +} + + +/** Creates a String from the nullable or item with the given prefix and postfix if supplied */ +inline fun T?.join(separator: String, prefix: String = "", postfix: String = ""): String { + val buffer = StringBuilder(prefix) + var first = true + if (this != null) { + buffer.append(this) + } + buffer.append(postfix) + return buffer.toString().sure() +} + + +/** Returns the nullable result of transforming this with the given transformation function */ +inline fun T?.map(transform : (T) -> R) : R? { + return if (this != null) { + transform(this) + } else { + null + } +} + +/** Transforms each element of this collection with the given function then adds the results to the given collection */ +inline fun > T?.mapTo(result: C, transform : (T) -> R) : C { + if (this != null) { + result.add(transform(this)) + } + return result +} + +/** Returns itself since it can't be reversed as it can contain at most one item */ +inline fun T?.reverse(): T? { + return this +} + +/** Copies the collection into the given collection */ +inline fun > T?.to(result: C): C { + if (this != null) + result.add(this) + return result +} + +/** Converts the collection into a LinkedList */ +inline fun T?.toLinkedList(): LinkedList = this.to(LinkedList()) + +/** Converts the collection into a List */ +inline fun T?.toList(): List = this.to(ArrayList()) + +/** Converts the collection into a Set */ +inline fun T?.toSet(): Set = this.to(HashSet()) + +/** Converts the collection into a SortedSet */ +inline fun T?.toSortedSet(): SortedSet = this.to(TreeSet()) +/** + TODO figure out necessary variance/generics ninja stuff... :) +inline fun T?.toSortedList(transform: fun(T) : java.lang.Comparable<*>) : List { + val answer = this.toList() + answer.sort(transform) + return answer +} +*/ diff --git a/libraries/stdlib/test/language/scala/OptionTest.kt b/libraries/stdlib/test/language/scala/OptionTest.kt index 65eb2d8090e..b437015c96e 100644 --- a/libraries/stdlib/test/language/scala/OptionTest.kt +++ b/libraries/stdlib/test/language/scala/OptionTest.kt @@ -1,5 +1,7 @@ package language.scala +import kotlin.nullable.* + import junit.framework.TestCase import kotlin.test.assertEquals @@ -94,32 +96,30 @@ class OptionTest: TestCase() { fun testFunctionComposition() { + assertEquals("", foo3(Request(null))) + assertEquals("", foo3(Request(" "))) + assertEquals("BAR", foo3(Request(" bar "))) + } + + fun foo3(request: Request): String { /* Scala: val name:Option[String] = request.getParameter("name") val upper = name map { _.trim } filter { _.length != 0 } map { _.toUpperCase } println(upper.getOrElse("")) - */ - /** TODO - The following would work if we implemented the filter/map methods on T? + val name = request.getParameter("name") + val upper = name.map{ it.trim() }.filter{ it.length != 0 }.map{ it.toUpperCase() } + return upper ?: "" - fun foo(name: String?): String { - val upper = name.map{ it.trim() }.filter{ it.length != 0 }.map { it.toUpperCase() } - return upper ?: "" - } - - assertEquals("", foo(null)) - assertEquals("", foo(" ")) - assertEquals("BAR", foo(" bar ")) - */ - - // TODO... + // TODO when http://youtrack.jetbrains.com/issue/KT-1145 is fixed + // we can get rid of the unnecessary on map } + fun testCompositionWithFor() { - fun foo3(request: Request): String { + fun foo4(request: Request): String { /* Scala: val upper = for { @@ -143,8 +143,8 @@ class OptionTest: TestCase() { return "" } - assertEquals("", foo3(Request(null))) - assertEquals("", foo3(Request(""))) - assertEquals("BAR", foo3(Request(" bar "))) + assertEquals("", foo4(Request(null))) + assertEquals("", foo4(Request(""))) + assertEquals("BAR", foo4(Request(" bar "))) } } \ No newline at end of file