Skip to content

Commit

Permalink
withDefault overload
Browse files Browse the repository at this point in the history
  • Loading branch information
sksamuel committed Dec 30, 2023
1 parent 1b9106f commit b87879b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import arrow.core.sequence
import com.sksamuel.tribune.core.Parser

/**
* Lifts an existing [Parser] to support lists of the input types supported by
* Lifts an existing [Parser] to support sets of the input types supported by
* the underlying parser.
*
* In other words, given a parser from I to A, returns a parser from List<I> to List<A>.
* In other words, given a parser from I to A, returns a parser from Set<I> to Set<A>.
*
* @return a parser that accepts lists
* @return a [Parser] that produces sets
*/
fun <I, A, E> Parser<I, A, E>.asSet(): Parser<Collection<I>, Set<A>, E> {
return Parser { input ->
Expand Down
10 changes: 8 additions & 2 deletions tribune-core/src/main/kotlin/com/sksamuel/tribune/core/nulls.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,14 @@ fun <I, A, E> Parser<I, A?, E>.withDefault(ifNull: () -> A): Parser<I, A, E> =
/**
* Maps an existing non-nullable [Parser] I => A to accept null inputs I? => A?
*/
fun <I, A, E> Parser<I, A, E>.allowNulls(): Parser<I?, A?, E> =
Parser { input -> if (input == null) Either.Right(null) else this@allowNulls.parse(input) }
@Deprecated("use nullable()", ReplaceWith("nullable()"))
fun <I, A, E> Parser<I, A, E>.allowNulls(): Parser<I?, A?, E> = nullable()

/**
* Maps an existing non-nullable [Parser] I => A to accept null inputs I? => A?
*/
fun <I, A, E> Parser<I, A, E>.nullable(): Parser<I?, A?, E> =
Parser { input -> if (input == null) Either.Right(null) else this@nullable.parse(input) }

/**
* Maps a nullable producing [Parser] to return an error if the output is null, or
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,26 @@ package com.sksamuel.tribune.core
import arrow.core.Either
import arrow.core.leftNel
import arrow.core.right
import com.sksamuel.tribune.core.strings.nullIf
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe

class NullTest : FunSpec() {
init {

test("default") {
test("withDefault on I -> A?") {
val p = Parser<String>().nullIf { true }.withDefault { "wibble" }
p.parse("abc") shouldBe "wibble".right()
}

test("withDefault on I? -> A?") {
val p = Parser<String?>().withDefault { "wibble" }
p.parse("abc") shouldBe "abc".right()
p.parse(null) shouldBe "wibble".right()
}

test("nullable") {
val p = Parser<String>().allowNulls()
val p = Parser<String>().nullable()
p.parse("abc") shouldBe "abc".right()
p.parse(null) shouldBe null.right()
}
Expand Down

0 comments on commit b87879b

Please sign in to comment.