-
Notifications
You must be signed in to change notification settings - Fork 451
/
Copy pathNonEmptySet.kt
67 lines (46 loc) · 2.3 KB
/
NonEmptySet.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package arrow.core
import kotlin.jvm.JvmInline
@JvmInline
public value class NonEmptySet<out A> private constructor(
@PublishedApi internal val elements: Set<A>
) : Set<A> by elements, NonEmptyCollection<A> {
public constructor(first: A, rest: Set<A>) : this(setOf(first) + rest)
public override operator fun plus(elements: Iterable<@UnsafeVariance A>): NonEmptySet<A> =
NonEmptySet(this.elements + elements)
public override operator fun plus(element: @UnsafeVariance A): NonEmptySet<A> =
NonEmptySet(this.elements + element)
override fun isEmpty(): Boolean = false
override val head: A get() = elements.first()
override fun lastOrNull(): A = elements.last()
@Suppress("OVERRIDE_BY_INLINE")
public override inline fun <B> map(transform: (A) -> B): NonEmptyList<B> =
elements.map(transform).toNonEmptyListOrNull()!!
@Suppress("OVERRIDE_BY_INLINE")
public override inline fun <B> mapIndexed(transform: (index: Int, A) -> B): NonEmptyList<B> =
elements.mapIndexed(transform).toNonEmptyListOrNull()!!
@Suppress("OVERRIDE_BY_INLINE")
public override inline fun <B> flatMap(transform: (A) -> NonEmptyCollection<B>): NonEmptyList<B> =
elements.flatMap(transform).toNonEmptyListOrNull()!!
override fun distinct(): NonEmptyList<A> =
toNonEmptyList()
@Suppress("OVERRIDE_BY_INLINE")
public override inline fun <K> distinctBy(selector: (A) -> K): NonEmptyList<A> =
elements.distinctBy(selector).toNonEmptyListOrNull()!!
override fun toString(): String = "NonEmptySet(${this.joinToString()})"
@Suppress("RESERVED_MEMBER_INSIDE_VALUE_CLASS")
override fun equals(other: Any?): Boolean =
elements == other
@Suppress("RESERVED_MEMBER_INSIDE_VALUE_CLASS")
override fun hashCode(): Int =
elements.hashCode()
}
public fun <A> nonEmptySetOf(first: A, vararg rest: A): NonEmptySet<A> =
NonEmptySet(first, rest.toSet())
public fun <A> Iterable<A>.toNonEmptySetOrNull(): NonEmptySet<A>? =
firstOrNull()?.let { NonEmptySet(it, minus(it).toSet()) }
public fun <A> Iterable<A>.toNonEmptySetOrNone(): Option<NonEmptySet<A>> =
toNonEmptySetOrNull().toOption()
public fun <A> Set<A>.toNonEmptySetOrNull(): NonEmptySet<A>? =
firstOrNull()?.let { NonEmptySet(it, minus(it)) }
public fun <A> Set<A>.toNonEmptySetOrNone(): Option<NonEmptySet<A>> =
toNonEmptySetOrNull().toOption()