Skip to content

Commit a7dc178

Browse files
authored
Inline NonEmpty maps (#3120)
1 parent 02215d4 commit a7dc178

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

arrow-libs/core/arrow-core/src/commonMain/kotlin/arrow/core/NonEmptyList.kt

+10-1
Original file line numberDiff line numberDiff line change
@@ -183,9 +183,18 @@ public class NonEmptyList<out A>(
183183
public override inline fun <B> map(transform: (A) -> B): NonEmptyList<B> =
184184
NonEmptyList(transform(head), tail.map(transform))
185185

186-
override fun <B> flatMap(transform: (A) -> NonEmptyCollection<B>): NonEmptyList<B> =
186+
@Suppress("OVERRIDE_BY_INLINE")
187+
public override inline fun <B> mapIndexed(transform: (index: Int, A) -> B): NonEmptyList<B> =
188+
NonEmptyList(transform(0, head), tail.mapIndexed { ix, e -> transform(ix + 1, e) })
189+
190+
@Suppress("OVERRIDE_BY_INLINE")
191+
public override inline fun <B> flatMap(transform: (A) -> NonEmptyCollection<B>): NonEmptyList<B> =
187192
transform(head).toNonEmptyList() + tail.flatMap(transform)
188193

194+
@Suppress("OVERRIDE_BY_INLINE")
195+
public override inline fun <K> distinctBy(selector: (A) -> K): NonEmptyList<A> =
196+
all.distinctBy(selector).toNonEmptyListOrNull()!!
197+
189198
public operator fun plus(l: NonEmptyList<@UnsafeVariance A>): NonEmptyList<A> =
190199
this + l.all
191200

arrow-libs/core/arrow-core/src/commonMain/kotlin/arrow/core/NonEmptySet.kt

+20-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import kotlin.jvm.JvmInline
44

55
@JvmInline
66
public value class NonEmptySet<out A> private constructor(
7-
private val elements: Set<A>
7+
@PublishedApi internal val elements: Set<A>
88
) : Set<A> by elements, NonEmptyCollection<A> {
99

1010
public constructor(first: A, rest: Set<A>) : this(setOf(first) + rest)
@@ -21,6 +21,25 @@ public value class NonEmptySet<out A> private constructor(
2121

2222
override fun lastOrNull(): A = elements.last()
2323

24+
@Suppress("OVERRIDE_BY_INLINE")
25+
public override inline fun <B> map(transform: (A) -> B): NonEmptyList<B> =
26+
elements.map(transform).toNonEmptyListOrNull()!!
27+
28+
@Suppress("OVERRIDE_BY_INLINE")
29+
public override inline fun <B> mapIndexed(transform: (index: Int, A) -> B): NonEmptyList<B> =
30+
elements.mapIndexed(transform).toNonEmptyListOrNull()!!
31+
32+
@Suppress("OVERRIDE_BY_INLINE")
33+
public override inline fun <B> flatMap(transform: (A) -> NonEmptyCollection<B>): NonEmptyList<B> =
34+
elements.flatMap(transform).toNonEmptyListOrNull()!!
35+
36+
override fun distinct(): NonEmptyList<A> =
37+
toNonEmptyList()
38+
39+
@Suppress("OVERRIDE_BY_INLINE")
40+
public override inline fun <K> distinctBy(selector: (A) -> K): NonEmptyList<A> =
41+
elements.distinctBy(selector).toNonEmptyListOrNull()!!
42+
2443
override fun toString(): String = "NonEmptySet(${this.joinToString()})"
2544

2645
@Suppress("RESERVED_MEMBER_INSIDE_VALUE_CLASS")

0 commit comments

Comments
 (0)