Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/ivan-moto/30-seconds-of-kotlin

Kotlin snippets that you can understand quickly, using only stdlib functionality.
https://github.com/ivan-moto/30-seconds-of-kotlin

30-seconds-of-code kotlin snippets snippets-collection snippets-library

Last synced: about 2 months ago
JSON representation

Kotlin snippets that you can understand quickly, using only stdlib functionality.

Awesome Lists containing this project

README

        

Kotlin

# 30 seconds of Kotlin

> Curated collection of useful Kotlin 1.3 snippets that you can understand quickly, using only stdlib functionality.

*Snippets are optimized for readability and comprehension, sometimes at the expense of performance.*

**Note:** This project is inspired by, but in no way affiliated with, [30 Seconds of Code](https://github.com/30-seconds/30-seconds-of-code).

## Table of Contents

### List

`Functions operating on the most fundamental data structure: List.`

View contents

* [`all`](#all)
* [`allEqual`](#allequal)
* [`any`](#any)
* [`bifurcate`](#bifurcate)
* [`bifurcateBy`](#bifurcateby)
* [`chunk`](#chunk)
* [`compact`](#compact)
* [`countBy`](#countby)
* [`countOccurrences`](#countoccurrences)
* [`concat`](#concat)
* [`corresponds`](#corresponds)
* [`crossProduct`](#crossproduct)
* [`cycle`](#cycle)
* [`difference`](#difference)
* [`differenceBy`](#differenceby)
* [`differenceWith`](#differencewith)
* [`distinct`](#distinct)
* [`drop`](#drop)
* [`dropRight`](#dropright)
* [`dropRightWhile`](#droprightwhile)
* [`dropWhile`](#dropwhile)
* [`endsWith`](#endsWith)
* [`everyNth`](#everynth)
* [`existsUnique`](#existsunique)
* [`filterNonUnique`](#filternonunique)
* [`filterNonUniqueBy`](#filternonuniqueby)
* [`findLast`](#findlast)
* [`findLastIndex`](#findlastindex)
* [`forEachRight`](#foreachright)
* [`groupBy`](#groupby)
* [`hasDuplicates`](#hasDuplicates)
* [`hasSubList`](#hassubList)
* [`head`](#head)
* [`indexOfAll`](#indexofall)
* [`initial`](#initial)
* [`initialize2DList`](#initialize2dlist)
* [`initializeListWithRange`](#initializelistwithrange)
* [`initializeListWithValue`](#initializelistwithvalue)
* [`intersection`](#intersection)
* [`intersectionBy`](#intersectionby)
* [`intersectionWith`](#intersectionwith)
* [`intersperse`](#intersperse)
* [`join`](#join)
* [`last`](#last)
* [`longest`](#longest)
* [`mapObject`](#mapobject)
* [`maxN`](#maxn)
* [`minN`](#minn)
* [`none`](#none)
* [`nthElement`](#nthelement)
* [`partition`](#partition)
* [`partitioningBy`](#partitioningBy)
* [`permutations`](#permutations)
* [`product`](#product)
* [`pull`](#pull)
* [`pullAtIndex`](#pullatindex)
* [`pullAtValue`](#pullatvalue)
* [`reduceSuccessive`](#reducesuccessive)
* [`reject`](#reject)
* [`remove`](#remove)
* [`rotateLeft`](#rotateleft)
* [`rotateRight`](#rotateright)
* [`sample`](#sample)
* [`sampleSize`](#samplesize)
* [`segmentLength`](#segmentLength)
* [`shank`](#shank)
* [`shuffle`](#shuffle)
* [`slideBy`](#slideby)
* [`sortOrder`](#sortorder)
* [`span`](#span)
* [`splitAt`](#splitat)
* [`startsWith`](#startswith)
* [`symmetricDifference`](#symmetricdifference)
* [`symmetricDifferenceBy`](#symmetricdifferenceby)
* [`symmetricDifferenceWith`](#symmetricdifferencewith)
* [`tail`](#tail)
* [`take`](#take)
* [`takeRight`](#takeright)
* [`takeRightWhile`](#takerightwhile)
* [`takeWhile`](#takewhile)
* [`union`](#union)
* [`unionBy`](#unionby)
* [`unionWith`](#unionwith)
* [`unzip`](#unzip)
* [`without`](#without)
* [`zip`](#zip)
* [`zipAll`](#zipall)
* [`zipKeysValues`](#zipkeysvalues)
* [`zipWith`](#zipwith)
* [`zipWithIndex`](#zipwithindex)
* [`zipWithNext`](#zipwithnext)

### Function

`Kotlin's first class functions make it easy to manipulate functions.`

View contents

* [`allOf`](#allof)
* [`andThen`](#andthen)
* [`anyOf`](#anyof)
* [`applyFirst`](#applyfirst)
* [`applySecond`](#applysecond)
* [`compose`](#compose)
* [`constant`](#constant)
* [`curry`](#curry)
* [`diverge`](#diverge)
* [`identity`](#identity)
* [`isIn`](#isIn)
* [`lift`](#lift)
* [`memoize`](#memoize)
* [`noneOf`](#noneof)
* [`retry`](#retry)
* [`sequence`](#sequence)
* [`swapArgs`](#swapargs)
* [`time`](#time)
* [`uncurry`](#uncurry)
* [`unlift`](#unlift)

### Lazy

`Functions operating on Kotlin's built in Lazy type.`

View contents

* [`asSequence`](#assequence)
* [`filter`](#filter)
* [`flatMap`](#flatmap)
* [`forever`](#forever)
* [`getOrDefault`](#getordefault)
* [`lift`](#lift)
* [`map`](#map)
* [`map2`](#map2)
* [`sequence`](#sequence)
* [`sequenceCatching`](#sequencecatching)
* [`test`](#test)

### Map

`Functions operating on Maps.`

View contents

* [`merge`](#merge)
* [`pick`](#pick)
* [`split`](#split)
* [`toEnumMap`](#toenummap)

#### Related projects

* [30 Seconds of Code (JavaScript)](https://github.com/30-seconds/30-seconds-of-code)
* [30 Seconds of Knowledge](https://github.com/petrovicstefanrs/30_seconds_of_knowledge)
* [30 Seconds of Java](https://github.com/shekhargulati/30-seconds-of-java)
* [30 Seconds of React](https://github.com/30-seconds/30-seconds-of-react)
* [30 Seconds of Python](https://github.com/kriadmin/30-seconds-of-python-code)
* [30 Seconds of PHP](https://github.com/appzcoder/30-seconds-of-php-code)

---

## List

### all

Returns `true` if the provided predicate function returns `true` for all elements in a list, `false` otherwise.

```kotlin
fun all(list: List, predicate: (T) -> Boolean): Boolean =
list.all(predicate)
```

## allEqual

Checks if all elements in a list are equal.

```kotlin
fun allEqual(list: List): Boolean =
if (list.isEmpty()) false else list.all { it == list[0] }
```

### any

Returns `true` if the provided predicate function returns `true` for at least one element in a list, `false` otherwise.

```kotlin
fun any(list: List, predicate: (T) -> Boolean): Boolean =
list.any(predicate)
```

### bifurcate

Splits list into two groups. For every element in a list, if the corresponding boolean in another list is true, add the element to the first group; otherwise, add it to the second group.

```kotlin
// For example:
bifurcate(listOf("beep", "boop", "foo", "bar"), listOf(true, true, false, true)) // [[beep, boop, bar], [foo]]
```

```kotlin
fun bifurcate(list: List, filter: List): Pair, List> {
require(list.size == filter.size)
return list.zip(filter).partition { it.second }
.let { (list1, list2) -> list1.map { it.first } to list2.map { it.first } }
}
```

### bifurcateBy

Splits values into two groups according to a predicate function, which specifies which group an element in the input list belongs to. If the predicate function returns true, the list element belongs to the first group; otherwise, it belongs to the second group.

```kotlin
fun bifurcateBy(list: List, predicate: (T) -> Boolean): Pair, List> =
list.partition(predicate)
```

### chunk

Chunks a list into smaller lists of a specified size. The last list in the resulting list may have less elements than the given size.

```kotlin
// For example:
chunk(listOf(1, 2, 3, 4, 5), 2) // [[1 ,2], [3, 4], [5]]
```

```kotlin
fun chunk(list: List, size: Int): List> =
list.chunked(size)
```

### compact

Removes "falsey" values from a list.

Kotlin doesn't distinguish falsey values but they are (`false`, `null`, `0`, `""`, `[]`, and `NaN`).

```kotlin
fun compact(list: List): List {
fun isTruthy(t: T?): Boolean = when(t) {
null -> false
is Boolean -> t
is Double -> t != Double.NaN
is Number -> t.toInt() != 0
is String -> !t.isEmpty()
is Array<*> -> t.size != 0
is Collection<*> -> !t.isEmpty()
else -> true
}
@Suppress("UNCHECKED_CAST")
return list.filter(::isTruthy) as List
}
```

### countBy

Groups the elements of a list based on the given function and returns the count of elements in each group.

```kotlin
// For example:
countBy(listOf(6.1, 4.2, 6.3)) { floor(it) } // {4.0: 1, 6.0: 2}
countBy(listOf("one", "two", "three")) { it.length } // {3: 2, 5: 1}
```

```kotlin
fun countBy(list: List, function: (T) -> K): Map =
list.groupingBy(function).eachCount()
```

### countOccurrences

Counts the occurrences of a value in a list, using a provided equality function.

```kotlin
fun countOccurrences(list: List, target: T, equals: (T, T) -> Boolean = Objects::equals): Int =
list.count { equals(target, it) }
```

### concat

Concatenates multiple lists into a single list, preserving the order of the passed in elements.

```kotlin
fun concat(first: List, vararg others: List): List =
first.asSequence().plus(others.asSequence().flatten()).toList()
```

### corresponds

Tests whether every element of the first list relates to the corresponding element in the second list by satisfying the given predicate.

```kotlin
// For example:
corresponds(listOf(1, 2, 3), listOf(2, 3, 4)) { i1, i2 -> i1 == i2 - 1 } // true
```
```kotlin
fun corresponds(first: List, second: List, predicate: (T, U) -> Boolean): Boolean =
(first.size == second.size) && (first.zip(second).all { (t, u) -> predicate(t, u) })
```

### crossProduct

Creates a cross product: forming a pair from each value in the first list to each value in the second list.

```kotlin
// For example:
crossProduct(listOf(1, 2), listOf('a', 'b')) // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
```

```kotlin
fun crossProduct(first: List, second: List): List> =
first.flatMap { a -> second.map { b -> a to b } }
```

### cycle

Produces a `Sequence` which cycles indefinitely through the given list.

```kotlin
// For example:
cycle(listOf(1, 2, 3)) // 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3...
```

```kotlin
fun cycle(list: List): Sequence =
generateSequence(if (list.isNotEmpty()) 0 else null) { (it + 1) % list.size }
.map { list[it] }
```

### difference

Returns a list of elements contained in the first list that are not present in the second list.

```kotlin
// For example:
difference(listOf(1, 2, 3), listOf(1, 2, 4)) // [3]
```

```kotlin
fun difference(first: List, second: List): List =
(first subtract second).toList()
```

### differenceBy

Returns a list of elements contained in the first list that are not present in the second list, after applying the provided function to each list element of both.

```kotlin
fun differenceBy(first: List, second: List, function: (T) -> R): List =
with(second.toSet().map(function)) {
first.filterNot { contains(function(it)) }
}
```

### differenceWith

Filters out all elements from the first list for which the comparator function does not return `true` for that element *and* every element in the second list.

```kotlin
fun differenceWith(first: List, second: List, function: (T, T) -> Boolean): List =
first.filter { a -> second.none { b -> function(a, b) } }
```

### distinct

Returns all distinct elements.

```kotlin
fun distinct(list: List): List =
list.distinct()
```

### drop

Returns a new list with `n` elements removed from the left.

```kotlin
fun drop(list: List, n: Int): List =
list.drop(n)
```

### dropRight

Returns a new list with `n` elements removed from the right.

```kotlin
fun dropRight(list: List, n: Int): List =
list.dropLast(n)
```

### dropRightWhile

Removes elements from the end of a list until the passed function returns `true`. Returns the remaining elements in the list.

```kotlin
fun dropRightWhile(list: List, predicate: (T) -> Boolean): List =
list.dropLastWhile(predicate)
```

### dropWhile

Removes elements from the beginning of a list until the passed function returns `true`. Returns the remaining elements in the list.

```kotlin
fun dropWhile(list: List, predicate: (T) -> Boolean): List =
list.dropWhile(predicate)
```

### endsWith

Checks whether the given list ends with the given sublist.

```kotlin
fun endsWith(list: List, subList: List): Boolean =
list.takeLast(subList.size) == subList
```

### everyNth

Returns every nth element in a list.

```kotlin
// For example:
everyNth(listOf(1, 2, 3, 4, 5, 6), 2) // [ 2, 4, 6 ]
```

```kotlin
fun everyNth(list: List, nth: Int): List =
list.windowed(nth, nth, partialWindows = false).map { it.last() }
```

### existsUnique

Checks if a unique element exists such that the predicate holds.

```kotlin
// For example:
existsUnique(listOf(1, 2, 3, 4, 5, 3)) { it == 3 } // false
```

```kotlin
fun existsUnique(list: List, predicate: (T) -> Boolean): Boolean {
var exists = false
for (t in list) {
if (predicate(t)) {
if (exists) {
return false
} else {
exists = true
}
}
}
return exists
}
```

### filterNonUnique

Filters out the non-unique values in a list.

```kotlin
fun filterNonUnique(list: List): List =
list.distinct()
```

### filterNonUniqueBy

Filters out the non-unique values in an list, after applying the given function.

```kotlin
// For example:
filterNonUniqueBy(listOf('a', 'b', 'c')) { 1 } // [a]
```

```kotlin
fun filterNonUniqueBy(list: List, function: (T) -> K): List =
list.distinctBy(function)
```

### findLast

Returns the last element for which the provided function returns true, or null if none is found.

```kotlin
fun findLast(list: List, predicate: (T) -> Boolean): T? =
list.findLast(predicate)
```

### findLastIndex

Returns the index of the last element for which the provided function returns true, or -1 if none is found.

```kotlin
fun findLastIndex(list: List, predicate: (T) -> Boolean): Int =
list.indexOfLast(predicate)
```

### forEachRight

Executes a provided function once for each list element, starting from the list's last element.

```kotlin
fun forEachRight(list: List, action: (T) -> Unit): Unit =
list.reversed().forEach(action)
```

### groupBy

Groups the elements of a list based on the given function.

```kotlin
// For example:
groupBy(listOf(6.1, 4.2, 6.3)) { floor(it) } // {4.0: [4.2], 6.0: [6.1, 6.3]}
groupBy(listOf("one", "two", "three")) { it.length } // {3: [one, two], 5: [three]}

```

```kotlin
fun groupBy(list: List, function: (T) -> K): Map> =
list.groupBy(function)
```

### hasDuplicates

Returns true if duplicate values exist in the list, false otherwise.

```kotlin
fun hasDuplicates(list: List): Boolean =
list.toSet().size != list.size
```

### hasSubList

Checks whether the given list contains the given sublist.

```kotlin
tailrec fun hasSubList(list: List, subList: List): Boolean =
when {
subList.isEmpty() -> true
list.isEmpty() -> subList.isEmpty()
list.take(subList.size) == subList -> true
else -> hasSubList(list.drop(1), subList)
}
```

### head

Returns the head of a list.

```kotlin
fun head(list: List): T =
list.first()
```
### indexOfAll

Returns all indices in a list where a given value is present.
If the value never occurs, returns an empty list.

```kotlin
// For example:
indexOfAll(listOf(1, 2, 3, 1, 2, 3), 1) // [0, 3]
indexOfAll(listOf(1, 2, 3), 4) // []
```

```kotlin
fun indexOfAll(list: List, target: T): List =
list.withIndex().filter { it.value == target }.map { it.index }
```

### initial

Returns all the elements of an array except the last one.

```kotlin
fun initial(list: List): List =
list.dropLast(1)
```

### initialize2DList

Initializes a 2D list of given width and height and value.

```kotlin
// For exmaple:
initialize2DList(2, 2, 0) // [[0, 0], [0, 0]]
```

```kotlin
fun initialize2DList(width: Int, height: Int, value: T): List> =
List(height) { List(width) { value } }
```

### initializeListWithRange

Initializes a list containing the numbers in the specified range, where `start` and `stop` are inclusive with their common difference `step`.

```kotlin
// For example:
initializeListWithRange(0, 9, 2) // [0, 2, 4, 6, 8]
```

```kotlin
fun initializeListWithRange(start: Int, stop: Int, step: Int): List =
(start..stop step step).toList()
```

### initializeListWithValue

Initializes and fills a list with the specified value.

```kotlin
// For example:
initializeListWithValue(5, 2) // [2, 2, 2, 2, 2]
```

```kotlin
fun initializeListWithValue(size: Int, value: T): List =
List(size) { value }
```

### intersection

Returns a list of elements that exist in both lists.

```kotlin
// For example:
intersection(listOf(1, 2, 3), listOf(4, 3, 2)) // [2, 3]
```

```kotlin
fun intersection(first: List, second: List): List =
(first intersect second).toList()
```

### intersectionBy

Returns a list of elements that exist in both lists, after applying the provided function to each element of both.

```kotlin
// For example:
intersectionBy(listOf(2.1, 1.2), listOf(2.3, 3.4)) { floor(it) } // [2.1]
```

```kotlin
fun intersectionBy(first: List, second: List, function: (T) -> R): List =
with(second.toSet().map(function)) {
first.filter { contains(function(it)) }
}
```

### intersectionWith

Returns a list of elements that exist in both lists, using a provided comparator function.

```kotlin
// For example:
intersectionWith(listOf(1.0, 1.2, 1.5, 3.0, 0.0), listOf(1.9, 3.0, 0.0, 3.9)) { a, b -> round(a) == round(b) } // [1.5, 3.0, 0.0]
```

```kotlin
fun intersectionWith(first: List, second: List, function: (T, T) -> Boolean): List =
first.filter { a -> second.any { b -> function(a, b) } }
```

### intersperse

Inserts an element between all elements of the given list.

```kotlin
// For example:
intersperse(listOf('a', 'b', 'c', 'd'), '0') // [a, 0, b, 0, c, 0, d]
```

```kotlin
fun intersperse(list: List, element: T): List =
List(list.size) { index -> listOf(list[index], element) }.flatten().dropLast(1)
```

### join

Joins all elements of a list into a string.

```kotlin
fun join(list: List, separator: String = ", "): String =
list.joinToString(separator)
```

### last

Returns the last element of a list.

```kotlin
fun last(list: List): T =
list.last()
```

### longest

Returns the longest collection in the list, or null if the list has no collections.
If multiple collections have the same size, the first one will be returned.

```kotlin
fun longest(list: List>): Collection? =
list.maxBy { it.size }
```

### mapObject

Maps the elements of a list to the result of applying a function to that element.

```kotlin
// For example:
mapObject(listOf(1, 2, 3)) { it * it } // { 1: 1, 2: 4, 3: 9 }
```

```kotlin
fun mapObject(list: List, function: (T) -> R): Map =
list.associateWith(function)
```

### maxN

Returns the `n` maximum elements from the provided list.
If `n` is greater than or equal to the provided list's length, then return the original list (sorted in descending order).

```kotlin
fun > maxN(list: List, n: Int): List =
list.sortedDescending().take(n)
```

### minN

Returns the `n` minimum elements from the provided list.
If `n` is greater than or equal to the provided list's length, then return the original list (sorted in ascending order).

```kotlin
fun > minN(list: List, n: Int): List =
list.sorted().take(n)
```

### none

Returns `true` if the provided predicate function returns `false` for all elements in a list, `false` otherwise.

```kotlin
// For example:
none(listOf(0, 1, 3, 0)) { it == 2} // true
none(listOf(-1, 1, 2)) { it <= 0 } // false
```

```kotlin
fun none(list: List, predicate: (T) -> Boolean): Boolean =
list.none(predicate)
```

### nthElement

Returns the nth element of a list.
If the index is out of bounds, throws `IndexOutOfBoundsException`.

```kotlin
fun nthElement(list: List, n: Int): T =
list[n]
```

### partition

Groups the elements into two lists, the first containing all elements for which the predicate evaluated to true, and the second containing all other elements.

```kotlin
fun partition(list: List, predicate: (T) -> Boolean): Pair, List> =
list.partition(predicate)
```

### partitioningBy

Partitions the input elements according to a predicate and organizes them into a `Map`.
Inspired by the JDK's `Collectors::partitioningBy`.

```kotlin
fun partitioningBy(list: List, predicate: (T) -> Boolean): Map> =
list.groupBy(predicate)
```

### permutations

Computes all the permutations of the given list. List elements are treated unique based on their index, so a list with equal elements will return duplicate lists.

> Note: this implementation uses non stack safe recursion

``kotlin
// For example:
permutations(listOf(1, 2, 3)) // [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
``

```kotlin
fun permutations(list: List): List> {
fun List.removeAtIndex(index: Int): List = take(index) + drop(index + 1)
fun List.prepend(element: T): List = listOf(element) + this
return when {
list.isEmpty() -> emptyList()
list.size == 1 -> listOf(list)
else -> list.foldIndexed(mutableListOf()) { index, acc, t ->
acc.apply {
addAll(permutations(list.removeAtIndex(index)).map { it.prepend(t) })
}
}
}
}
```

### product

Creates a cross product: applying the provided function to each value in the first list along with each value in the second list

```kotlin
fun product(first: List, second: List, function: (T, U) -> R): List =
first.flatMap { t -> second.map { u -> function(t, u) } }
```

### pull

Filters out the elements specified.

```kotlin
// For example:
pull(listOf('a', 'b', 'c', 'a', 'b', 'c'), 'a', 'c') // [b, b]
```

```kotlin
fun pull(list: List, vararg elements: T): List =
with(elements.toSet()) {
list.filterNot { contains(it) }
}
```

### pullAtIndex

Filters out the indices specified.

```kotlin
// For example:
pullAtIndex(listOf('a', 'b', 'c', 'd'), 1, 2) // [a, d]
```

```kotlin
fun pullAtIndex(list: List, vararg indices: Int): List =
with(indices.toSet()) {
list.filterIndexed { index, _ -> !contains(index) }
}
```

### pullAtValue

Filters out the elements specified and returns them.

```kotlin
// For example:
pullAtValue(listOf('a', 'b', 'c', 'd'), 'b', 'd', 'e') // [b, d]
```

```kotlin
fun pullAtValue(list: List, vararg elements: T): List =
with(elements.toSet()) {
list.filter { contains(it) }
}
```

### reduceSuccessive

This function is also commonly known as `scan`.
Applies a function against an accumulator and each element in the list (from left to right), returning a new list of successively calculated values.

```kotlin
// For example:
reduceSuccessive(listOf(1, 2, 3, 4, 5, 6), 0) { acc, int -> acc + int } // [1, 3, 6, 10, 15, 21]
```

```kotlin
fun reduceSuccessive(list: List, identity: R, function: (R, T) -> R): List {
fun List.lastOrElse(t: T): T = lastOrNull() ?: t
return list.fold(emptyList()) { acc, t -> acc + function(acc.lastOrElse(identity), t) }
}
```

### reject

Return a new list which removes elements from the list for which the given predicate returns `true`.

```kotlin
// For example:
reject(listOf(1, 2, 3, 4, 5)) { it % 2 == 0 } // [1, 3, 5]
reject(listOf("Apple", "Pear", "Kiwi", "Banana")) { it.length > 4 } // [Pear, Kiwi]
```

```kotlin
fun reject(list: List, predicate: (T) -> Boolean): List =
list.filterNot(predicate)
```

### remove

Returns a new list which removes elements from the list for which the given predicate returns `false`.

```kotlin
// For example:
remove(listOf(1, 2, 3, 4)) { it % 2 == 0 } // [2, 4]
```

```kotlin
fun remove(list: List, predicate: (T) -> Boolean): List =
list.filter(predicate)
```

### rotateLeft

Returns a new list which circular rotates the elements by the specified distance to the left direction.
This implementation throws an exception when n is negative, though in reality a negative rotation to the left
can be considered a positive rotation to the right.

```kotlin
// For example:
rotateLeft(listOf(1, 2, 3, 4, 5), 2) // [3, 4, 5, 1, 2]
```

```kotlin
fun rotateLeft(list: List, n: Int): List =
list.slice(n until list.size) + list.slice(0 until n)
```

### rotateRight

Returns a new list which circular rotates the elements by the specified distance to the right direction.
This implementation throws an exception when n is negative, though in reality a negative rotation to the right
can be considered a positive rotation to the left.

```
// For example:
rotateRight(listOf(1, 2, 3, 4, 5), 2) // [4, 5, 1, 2, 3]
```

```kotlin
fun rotateRight(list: List, n: Int): List =
list.takeLast(n % list.size) + list.dropLast(n % list.size)
```

### sample

Returns a random element from a list.

```kotlin
fun sample(list: List): T =
list.random()
```

### sampleSize

Gets `n` random elements from a list, up to the size of the list.

```kotlin
fun sampleSize(list: List, n: Int): List =
list.shuffled().take(n)
```

### segmentLength

Computes length of longest segment within the given list whose elements all satisfy some predicate.

```kotlin
// For example:
segmentLength(listOf('d', 'e', 'f', 'a', 'b', 'c', 'd')) { char -> char == 'a' || char == 'b' || char == 'c' } // 3
```

```kotlin
fun segmentLength(list: List, predicate: (T) -> Boolean): Int =
list.fold(0 to 0) { (longest, current), t -> if (predicate(t)) longest to current + 1 else max(longest, current) to 0 }.first
```

### shank

Returns a new list with changes in the contents of this list, removing or replacing existing elements and/or adding new elements.

```kotlin
// For example:
val names = listOf("alpha", "bravo", "charlie")
shank(names, 1, 0, "delta") // [alpha, delta, bravo, charlie]
shank(names, 1, 1) // [alpha, charlie]
```

`start` - Index at which to start changing the list
`deleteCount` - the number of list elements to remove, beginning from `start`
`elements` - the elements to add to the list, beginning from `start`

```kotlin
fun shank(list: List, start: Int = 0, deleteCount: Int = 0, vararg elements: T): List =
list.slice(0 until start) + elements + list.drop(start + deleteCount)
```

### shuffle

Returns a new list with the elements of this list randomly shuffled.

```kotlin
fun shuffle(list: List): List =
list.shuffled()
```

### slideBy

Slides a non-overlapping window of a variable size over the given list.

Each window contains elements that are equal according to the given classifier function.

```kotlin
// For example:
slideBy(listOf(1, 2, 3, 3, 3, 4, 5)) { it } // [[1], [2], [3, 3, 3], [4], [5]]
slideBy(listOf(1, 2, 3, 10, 12, 5, 7, 20, 29)) { it / 10 } // [[1, 2, 3], [10, 12], [5, 7], [20, 29]]
```

```kotlin
fun slideBy(list: List, classifier: (T) -> R): List> {
tailrec fun slideBy_(list: List, acc: MutableList>): MutableList> =
if (list.isEmpty())
acc
else
slideBy_(list.dropWhile { classifier(it) == classifier(list.first()) }, acc.apply { add(list.takeWhile { classifier(it) == classifier(list.first()) } )} )
return slideBy_(list, mutableListOf())
}
```

### sortOrder

Returns `1` if the list is sorted in ascending order, `-1` if it is sorted in descending order or `0` if it is not sorted.
A list with all equal values is considered sorted ascending.

```kotlin
// For example:
isSorted(listOf(0, 1, 2, 2)) // 1
isSorted(listOf(4, 3, 2)) // -1
isSorted(listOf(4, 3, 5)) // 0
```

```kotlin
fun > sortOrder(list: List): Int =
with(list.sorted()) {
when {
this == list -> 1
this.asReversed() == list -> -1
else -> 0
}
}
```

### span

Returns a pair where the first element is the longest prefix of elements that satisfies the given predicate, and the second element is the remainder.

```kotlin
fun span(list: List, predicate: (T) -> Boolean): Pair, List> =
list.takeWhile(predicate) to list.dropWhile(predicate)
```

### splitAt

Splits the given list at the first element which satisfies the predicate.

```kotlin
// For example:
splitAt(listOf(1, 2, 3, 4, 5)) { it == 3 } // [[1, 2], [3, 4, 5]]
```

```kotlin
fun splitAt(list: List, predicate: (T) -> Boolean): Pair, List> =
list.takeWhile { !predicate(it) } to list.dropWhile { !predicate(it) }
```

### startsWith

Checks whether the given list starts with the given sublist.

```kotlin
fun startsWith(list: List, subList: List): Boolean =
list.take(subList.size) == subList
```

### symmetricDifference

Returns the symmetric difference between two lists, without filtering out duplicate values.

```kotlin
// For example:
symmetricDifference(listOf(1, 2, 3), listOf(1, 2, 4)) // [3, 4]
symmetricDifference(listOf(1, 2, 2), listOf(1, 3, 1)) // [2, 2, 3]
```

```kotlin
fun symmetricDifference(first: List, second: List): List =
((first subtract second) + (second subtract first)).toList()
```

### symmetricDifferenceBy

Returns the symmetric difference between two lists, after applying the provided function to each element of both.

```kotlin
// For example:
symmetricDifferenceBy(listOf(2.1, 1.2), listOf(2.3, 3.4)) { floor(it) } // [1.2, 3.4]
```

```kotlin
fun symmetricDifferenceBy(first: List, second: List, function: (T) -> R): List {
val mapFirst = first.toSet().map(function)
val mapSecond = second.toSet().map(function)
return first.filterNot { mapSecond.contains(function(it)) } + second.filterNot { mapFirst.contains(function(it)) }
}
```

### symmetricDifferenceWith

Returns the symmetric difference between two lists, using a provided function as a comparator.

```kotlin
// For example:
symmetricDifferenceWith(
listOf(1.0, 1.2, 1.5, 3.0, 0.0),
listOf(1.9, 3.0, 0.0, 3.9),
{ a, b -> round(a) == round(b) }
) // [1.0, 1.2, 3.9]
```

```kotlin
fun symmetricDifferenceWith(first: List, second: List, function: (T, T) -> Boolean): List =
first.filter { a -> second.none { b -> function(a ,b) } } +
second.filter { b -> first.none { a -> function(a, b) } }
```

### tail

Returns all elements in a list except for the first one.

```kotlin
fun tail(list: List): List =
list.drop(1)
```

### take

Returns the first `n` elements.

Use `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the beginning.

```kotlin
fun take(list: List, n: Int): List =
list.take(n)
```

### takeRight

Returns the last `n` elements.

```kotlin
fun takeRight(list: List, n: Int): List =
list.takeLast(n)
```

### takeRightWhile

Returns the last `n` elements satisfying the given predicate.

```kotlin
// For example:
takeRightWhile(listOf(1, 2, 3, 4)) { it >= 3 } // [3, 4]
```

```kotlin
fun takeRightWhile(list: List, predicate: (T) -> Boolean): List =
list.takeLastWhile(predicate)
```

### takeWhile

Returns the first `n` elements satisfying the given predicate.

```kotlin
// For example:
takeWhile(listOf(1, 2, 3, 4)) { it < 3 } // [1, 2]
```

```kotlin
fun takeWhile(list: List, predicate: (T) -> Boolean): List =
list.takeWhile(predicate)
```

### union

Returns every element that exists in any of the two lists, removing duplicates.

```kotlin
// For example:
union(listOf(1, 2, 3), listOf(4, 3, 2)) // [1, 2, 3, 4]
```

```kotlin
fun union(first: List, second: List): List =
(first union second).toList()
```

### unionBy

Returns every element that exists in any of the two lists once, after applying the provided function to each element of both.

```kotlin
// For example:
unionBy(listOf(2.1), listOf(1.2, 2.3)) { floor(it) } // [2.1, 1.2]
```

```kotlin
fun unionBy(first: List