Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ApplicativeError laws #236

Merged
merged 6 commits into from
Sep 2, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import io.kotlintest.properties.Gen
import io.kotlintest.properties.forAll

object AsyncLaws {
inline fun <reified F> laws(AC: AsyncContext<F> = asyncContext(), M: MonadError<F, Throwable> = monadError<F, Throwable>(), EQ: Eq<HK<F, Int>>, EQERR: Eq<HK<F, Int>> = EQ): List<Law> =
MonadErrorLaws.laws(M, EQERR, EQ) + listOf(
inline fun <reified F> laws(AC: AsyncContext<F> = asyncContext(), M: MonadError<F, Throwable> = monadError<F, Throwable>(), EQ: Eq<HK<F, Int>>, EQ_EITHER: Eq<HK<F, Either<Throwable, Int>>>, EQERR: Eq<HK<F, Int>> = EQ): List<Law> =
MonadErrorLaws.laws(M, EQERR, EQ_EITHER, EQ) + listOf(
Law("Async Laws: success equivalence", { asyncSuccess(AC, M, EQ) }),
Law("Async Laws: error equivalence", { asyncError(AC, M, EQERR) }),
Law("Async bind: binding blocks", { asyncBind(AC, M, EQ) }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import org.junit.runner.RunWith

@RunWith(KTestJUnitRunner::class)
class IOTest : UnitSpec() {
val EQ: Eq<HK<IOHK, Int>> = object : Eq<HK<IOHK, Int>> {
override fun eqv(a: HK<IOHK, Int>, b: HK<IOHK, Int>): Boolean =
fun <A> EQ(): Eq<HK<IOHK, A>> = object : Eq<HK<IOHK, A>> {
override fun eqv(a: HK<IOHK, A>, b: HK<IOHK, A>): Boolean =
a.ev().attempt().unsafeRunSync() == b.ev().attempt().unsafeRunSync()
}

init {
testLaws(AsyncLaws.laws(IO.asyncContext(), IO.monadError(), EQ, EQ))
testLaws(AsyncLaws.laws(IO.asyncContext(), IO.monadError(), EQ(), EQ()))

"should defer evaluation until run" {
var run = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,20 @@ import java.util.concurrent.atomic.AtomicReference
import kotlin.coroutines.experimental.EmptyCoroutineContext

@RunWith(KTestJUnitRunner::class)
class JobKWTest : UnitSpec() {
val EQ: Eq<HK<JobKWHK, Int>> = object : Eq<HK<JobKWHK, Int>> {
override fun eqv(a: HK<JobKWHK, Int>, b: HK<JobKWHK, Int>): Boolean =
class JobWTest : UnitSpec() {
private fun <A> EQ(): Eq<HK<JobKWHK, A>> = object : Eq<HK<JobKWHK, A>> {
override fun eqv(a: HK<JobKWHK, A>, b: HK<JobKWHK, A>): Boolean =
runBlocking {
val resultA = AtomicInteger(Int.MIN_VALUE)
val resultB = AtomicInteger(Int.MAX_VALUE)
val resultA = AtomicReference<A>()
val resultB = AtomicReference<A>()
val success = AtomicBoolean(true)
a.runJob {
it.fold({ success.set(false) }, { resultA.set(it) })
}.join()
b.runJob({
it.fold({ success.set(false) }, { resultB.set(it) })
}).join()
success.get() && resultA.get() == resultB.get()
success.get() && resultA.get() != null && resultA.get() == resultB.get()
}
}

Expand All @@ -40,6 +40,6 @@ class JobKWTest : UnitSpec() {
}

init {
testLaws(AsyncLaws.laws(JobKW.asyncContext(EmptyCoroutineContext), JobKW.monadError(EmptyCoroutineContext), EQ, EQ_ERR))
testLaws(AsyncLaws.laws(JobKW.asyncContext(EmptyCoroutineContext), JobKW.monadError(EmptyCoroutineContext), EQ(), EQ(), EQ_ERR))
}
}
29 changes: 26 additions & 3 deletions kategory-test/src/main/kotlin/kategory/generators/Generators.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@ package kategory

import io.kotlintest.properties.Gen

fun <F> genEqAnyLogged() = object : Eq<F> {
val any = Eq.any()

override fun eqv(a: F, b: F): Boolean {
val result = any.eqv(a, b)
if (!result) {
println("$a <---> $b")
}
return result
}
}

inline fun <reified F, A> genApplicative(valueGen: Gen<A>, AP: Applicative<F> = applicative<F>()): Gen<HK<F, A>> =
object : Gen<HK<F, A>> {
override fun generate(): HK<F, A> =
Expand Down Expand Up @@ -59,7 +71,18 @@ fun genIntPredicate(): Gen<(Int) -> Boolean> =
fun <B> genOption(genB: Gen<B>): Gen<Option<B>> =
object : Gen<Option<B>> {
val random = genIntSmall()
override fun generate(): Option<B> {
return if (random.generate() % 20 == 0) Option.None else Option.pure(genB.generate())
}
override fun generate(): Option<B> =
if (random.generate() % 20 == 0) Option.None else Option.pure(genB.generate())
}

inline fun <reified E, reified A> genEither(genE: Gen<E>, genA: Gen<A>): Gen<Either<E, A>> =
object : Gen<Either<E, A>> {
override fun generate(): Either<E, A> =
Gen.oneOf(genE, genA).generate().let {
when (it) {
is E -> Either.Left(it)
is A -> Either.Right(it)
else -> throw IllegalStateException("genEither incorrect value $it")
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package kategory

import io.kotlintest.properties.Gen
import io.kotlintest.properties.forAll

object ApplicativeErrorLaws {

inline fun <reified F> laws(AP: ApplicativeError<F, Throwable> = applicativeError<F, Throwable>(), EQERR: Eq<HK<F, Int>>, EQ_EITHER: Eq<HK<F, Either<Throwable, Int>>>, EQ: Eq<HK<F, Int>> = EQERR): List<Law> =
ApplicativeLaws.laws(AP, EQ) + listOf(
Law("Applicative Error Laws: handle", { applicativeErrorHandle(AP, EQERR) }),
Law("Applicative Error Laws: handle with for error", { applicativeErrorHandleWith(AP, EQERR) }),
Law("Applicative Error Laws: handle with for success", { applicativeErrorHandleWithPure(AP, EQERR) }),
Law("Applicative Error Laws: attempt for error", { applicativeErrorAttemptError(AP, EQ_EITHER) }),
Law("Applicative Error Laws: attempt for success", { applicativeErrorAttemptSuccess(AP, EQ_EITHER) }),
Law("Applicative Error Laws: attempt fromEither consistent with pure", { applicativeErrorAttemptFromEitherConsistentWithPure(AP, EQ_EITHER) }),
Law("Applicative Error Laws: catch captures errors", { applicativeErrorCatch(AP, EQERR) })
)

inline fun <reified F> applicativeErrorHandle(AP: ApplicativeError<F, Throwable> = applicativeError<F, Throwable>(), EQ: Eq<HK<F, Int>>): Unit =
forAll(genFunctionAToB<Throwable, Int>(Gen.int()), genThrowable(), { f: (Throwable) -> Int, e: Throwable ->
AP.handleError(AP.raiseError<Int>(e), f).equalUnderTheLaw(AP.pure(f(e)), EQ)
})

inline fun <reified F> applicativeErrorHandleWith(AP: ApplicativeError<F, Throwable> = applicativeError<F, Throwable>(), EQ: Eq<HK<F, Int>>): Unit =
forAll(genFunctionAToB<Throwable, HK<F, Int>>(genApplicative(Gen.int(), AP)), genThrowable(), { f: (Throwable) -> HK<F, Int>, e: Throwable ->
AP.handleErrorWith(AP.raiseError<Int>(e), f).equalUnderTheLaw(f(e), EQ)
})

inline fun <reified F> applicativeErrorHandleWithPure(AP: ApplicativeError<F, Throwable> = applicativeError<F, Throwable>(), EQ: Eq<HK<F, Int>>): Unit =
forAll(genFunctionAToB<Throwable, HK<F, Int>>(genApplicative(Gen.int(), AP)), Gen.int(), { f: (Throwable) -> HK<F, Int>, a: Int ->
AP.handleErrorWith(AP.pure(a), f).equalUnderTheLaw(AP.pure(a), EQ)
})

inline fun <reified F> applicativeErrorAttemptError(AP: ApplicativeError<F, Throwable> = applicativeError<F, Throwable>(), EQ: Eq<HK<F, Either<Throwable, Int>>>): Unit =
forAll(genThrowable(), { e: Throwable ->
AP.attempt(AP.raiseError<Int>(e)).equalUnderTheLaw(AP.pure(e.left()), EQ)
})

inline fun <reified F> applicativeErrorAttemptSuccess(AP: ApplicativeError<F, Throwable> = applicativeError<F, Throwable>(), EQ: Eq<HK<F, Either<Throwable, Int>>>): Unit =
forAll(Gen.int(), { a: Int ->
AP.attempt(AP.pure(a)).equalUnderTheLaw(AP.pure(a.right()), EQ)
})

inline fun <reified F> applicativeErrorAttemptFromEitherConsistentWithPure(AP: ApplicativeError<F, Throwable> = applicativeError<F, Throwable>(), EQ: Eq<HK<F, Either<Throwable, Int>>>): Unit =
forAll(genEither(genThrowable(), Gen.int()), { either: Either<Throwable, Int> ->
AP.attempt(AP.fromEither(either)).equalUnderTheLaw(AP.pure(either), EQ)
})

inline fun <reified F> applicativeErrorCatch(AP: ApplicativeError<F, Throwable> = applicativeError<F, Throwable>(), EQ: Eq<HK<F, Int>>): Unit =
forAll(genEither(genThrowable(), Gen.int()), { either: Either<Throwable, Int> ->
AP.catch({ either.fold({ throw it }, { it }) }).equalUnderTheLaw(either.fold({ AP.raiseError<Int>(it) }, { AP.pure(it) }), EQ)
})

}
4 changes: 2 additions & 2 deletions kategory-test/src/main/kotlin/kategory/laws/MonadErrorLaws.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import io.kotlintest.properties.forAll

object MonadErrorLaws {

inline fun <reified F> laws(M: MonadError<F, Throwable> = monadError<F, Throwable>(), EQERR: Eq<HK<F, Int>>, EQ: Eq<HK<F, Int>> = EQERR): List<Law> =
MonadLaws.laws(M, EQ) + listOf(
inline fun <reified F> laws(M: MonadError<F, Throwable> = monadError<F, Throwable>(), EQERR: Eq<HK<F, Int>>, EQ_EITHER: Eq<HK<F, Either<Throwable, Int>>>, EQ: Eq<HK<F, Int>> = EQERR): List<Law> =
MonadLaws.laws(M, EQ) + ApplicativeErrorLaws.laws(M, EQERR, EQ_EITHER, EQ) + listOf(
Law("Monad Error Laws: left zero", { monadErrorLeftZero(M, EQERR) }),
Law("Monad Error Laws: ensure consistency", { monadErrorEnsureConsistency(M, EQERR) })
)
Expand Down
2 changes: 1 addition & 1 deletion kategory/src/main/kotlin/kategory/data/Option.kt
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ fun <B> Option<B>.getOrElse(default: () -> B): B = fold({ default() }, { it })
*
* @param default the default option if this is empty.
*/
fun <A, B : A> Option<B>.orElse(alternative: () -> Option<B>): Option<B> = if (isEmpty) alternative() else this
fun <A, B : A> OptionKind<B>.orElse(alternative: () -> Option<B>): Option<B> = if (ev().isEmpty) alternative() else ev()

fun <A> A.some(): Option<A> = Option.Some(this)

Expand Down
2 changes: 1 addition & 1 deletion kategory/src/test/kotlin/kategory/data/EitherTTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import org.junit.runner.RunWith
class EitherTTest : UnitSpec() {
init {

testLaws(MonadErrorLaws.laws(EitherT.monadError<IdHK, Throwable>(Id.monad()), Eq.any()))
testLaws(MonadErrorLaws.laws(EitherT.monadError<IdHK, Throwable>(Id.monad()), Eq.any(), Eq.any()))
testLaws(TraverseLaws.laws(EitherT.traverse<IdHK, Int>(), EitherT.applicative(), { EitherT(Id(Either.Right(it))) }, Eq.any()))
testLaws(SemigroupKLaws.laws<EitherTKindPartial<IdHK, Int>>(
EitherT.semigroupK(Id.monad()),
Expand Down
2 changes: 1 addition & 1 deletion kategory/src/test/kotlin/kategory/data/EitherTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import org.junit.runner.RunWith
class EitherTest : UnitSpec() {
init {

testLaws(MonadErrorLaws.laws(Either.monadError(), Eq.any()))
testLaws(MonadErrorLaws.laws(Either.monadError(), Eq.any(), Eq.any()))
testLaws(TraverseLaws.laws(Either.traverse<Throwable>(), Either.applicative(), { it.right() }, Eq.any()))
testLaws(SemigroupKLaws.laws(
Either.semigroupK(),
Expand Down
15 changes: 8 additions & 7 deletions kategory/src/test/kotlin/kategory/data/KleisliTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@ import org.junit.runner.RunWith

@RunWith(KTestJUnitRunner::class)
class KleisliTest : UnitSpec() {
init {

val me = Kleisli.monadError<TryHK, Int, Throwable>(Try.monadError())
private fun <A> EQ(): Eq<KleisliKind<TryHK, Int, A>> {
return object : Eq<KleisliKind<TryHK, Int, A>> {
override fun eqv(a: KleisliKind<TryHK, Int, A>, b: KleisliKind<TryHK, Int, A>): Boolean =
a.ev().run(1) == b.ev().run(1)

testLaws(MonadErrorLaws.laws(me, object : Eq<KleisliKind<TryHK, Int, Int>> {
override fun eqv(a: KleisliKind<TryHK, Int, Int>, b: KleisliKind<TryHK, Int, Int>): Boolean =
a.ev().run(1) == b.ev().run(1)
}
}

}))
init {
testLaws(MonadErrorLaws.laws(Kleisli.monadError<TryHK, Int, Throwable>(Try.monadError()), EQ(), EQ()))

"andThen should continue sequence" {
val kleisli: Kleisli<IdHK, Int, Int> = Kleisli({ a: Int -> Id(a) })
Expand Down
17 changes: 16 additions & 1 deletion kategory/src/test/kotlin/kategory/data/OptionTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,23 @@ class OptionTest : UnitSpec() {
object OptionError : RuntimeException()

init {
val EQ_EITHER: Eq<HK<OptionHK, Either<Throwable, Int>>> = object : Eq<HK<OptionHK, Either<Throwable, Int>>> {
override fun eqv(a: HK<OptionHK, Either<Throwable, Int>>, b: HK<OptionHK, Either<Throwable, Int>>): Boolean =
a.ev().fold(
{ b.ev().fold({ true }, { false }) },
{ eitherA: Either<Throwable, Int> ->
b.ev().fold(
{ false },
{ eitherB: Either<Throwable, Int> ->
eitherA.fold(
{ eitherB.fold({ true /* Ignore the error kind */ }, { false }) },
{ ia -> eitherB.fold({ false }, { ia == it }) })
})
})
}


testLaws(MonadErrorLaws.laws(Option.monadError<Throwable>(OptionError), Eq.any()))
testLaws(MonadErrorLaws.laws(Option.monadError<Throwable>(OptionError), Eq.any(), EQ_EITHER))
testLaws(TraverseLaws.laws(Option.traverse(), Option.monad(), ::Some, Eq.any()))

"fromNullable should work for both null and non-null values of nullable types" {
Expand Down
2 changes: 1 addition & 1 deletion kategory/src/test/kotlin/kategory/data/TryTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class TryTest : UnitSpec() {

init {

testLaws(MonadErrorLaws.laws(Try.monadError(), Eq.any()))
testLaws(MonadErrorLaws.laws(Try.monadError(), Eq.any(), Eq.any()))
testLaws(TraverseLaws.laws(Try.traverse(), Try.functor(), ::Success, Eq.any()))

"invoke of any should be success" {
Expand Down