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

Exact DSL draft #6

Merged
merged 2 commits into from
May 5, 2023
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
23 changes: 8 additions & 15 deletions build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
plugins {
kotlin("multiplatform") version "1.6.21" apply true
id("io.kotest.multiplatform") version "5.3.0" apply true
kotlin("multiplatform") version "1.8.21" apply true
id("io.kotest.multiplatform") version "5.6.0" apply true
}

group "org.example"
Expand All @@ -25,7 +25,6 @@ kotlin {

mingwX64()

iosArm32()
iosArm64()
iosSimulatorArm64()
iosX64()
Expand All @@ -38,33 +37,27 @@ kotlin {
watchosArm64()
watchosSimulatorArm64()
watchosX64()
watchosX86()

sourceSets {
commonMain {
dependencies {
implementation(kotlin("stdlib-common"))
implementation("io.arrow-kt:arrow-core:1.1.3-alpha.39")
implementation("io.arrow-kt:arrow-optics:1.1.3-alpha.39")
implementation("io.arrow-kt:arrow-fx-coroutines:1.1.3-alpha.39")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1")
implementation("io.arrow-kt:arrow-core:1.2.0-RC")
}
}

commonTest {
dependencies {
implementation("io.kotest:kotest-property:5.3.0")
implementation("io.kotest:kotest-framework-engine:5.3.0")
implementation("io.kotest:kotest-assertions-core:5.3.0")
implementation("io.kotest.extensions:kotest-assertions-arrow:1.2.5")
implementation("io.kotest.extensions:kotest-property-arrow:1.2.5") // optional
implementation("io.kotest.extensions:kotest-property-arrow-optics:1.2.5") // optional
implementation("io.kotest:kotest-property:5.6.1")
implementation("io.kotest:kotest-framework-engine:5.6.1")
implementation("io.kotest:kotest-assertions-core:5.6.1")
implementation("io.kotest.extensions:kotest-assertions-arrow:1.3.3")
}
}

val jvmTest by getting {
dependencies {
implementation("io.kotest:kotest-runner-junit5-jvm:5.3.0")
implementation("io.kotest:kotest-runner-junit5-jvm:5.6.1")
}
}
}
Expand Down
23 changes: 23 additions & 0 deletions src/commonMain/kotlin/arrow.exact/Exact.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package arrow.exact

import arrow.core.*

interface Exact<A, out B> {

fun from(value: A): Either<ExactError, B>

fun fromOrNull(value: A): B? {
return from(value).getOrNull()
}

fun fromOrThrow(value: A): B {
return when (val result = from(value)) {
is Either.Left -> throw ExactException(result.value.message)
is Either.Right -> result.value
}
}
}

open class ExactError(val message: String)
ILIYANGERMANOV marked this conversation as resolved.
Show resolved Hide resolved

class ExactException(message: String) : IllegalArgumentException(message)
30 changes: 30 additions & 0 deletions src/commonMain/kotlin/arrow.exact/ExactDsl.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package arrow.exact

import arrow.core.*

internal class AndExact<A, B, C>(
private val exact1: Exact<A, B>,
private val exact2: Exact<B, C>
) : Exact<A, C> {

override fun from(value: A): Either<ExactError, C> {
return exact1.from(value)
.flatMap { exact2.from(it) }
}
}

fun <A, B> exact(predicate: Predicate<A>, constructor: (A) -> B): Exact<A, B> {
Copy link
Collaborator

@ILIYANGERMANOV ILIYANGERMANOV May 3, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two things:

  1. I'd suggest switching the argument order like exact(constructor, predicate) so we can do:
companion object : Exact<Int, PositiveInt> by exact(::PositiveInt) { it > 0 }
  1. Do we want exact to work only with predicates? I'm thinking about overloading a version `fun exact(constr: (A) -> B, constraint: (A) -> Either<ExactError, B>)

The benefit of this is that we can define types like NotBlankTrimmedString with much less boilerplate.

companion object : Exact<String, NotBlankTrimmedString> by exact(::NotBlankTrimmedString) {
   it.trim().takeIf(String::isNotBlank) ?: raise(...)
}

On this, @ustits @nomisRev should we better use the new Raise API instead of Either for the method of Exact that must be implemented.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think having it Raise based makes sense. In that case I would go for:

fun exact(constr: (A) -> B, constraint: Raise<ExactError>.(A) -> B)

companion object : Exact<String, NotBlankTrimmedString> by exact(::NotBlankTrimmedString) {
   ensureNotNull(it.trim().takeIf(String::isNotBlank)) { ... }
}

but both should exclude each-other 🤔 They shouldn't conflict with each other if we use OverloadResolutionByLambdaReturnType.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ILIYANGERMANOV Unfortunately we can't implement it in such a way, kotlin compiler thinks that after { there must be a class body, not a lambda, so eventually there is no difference in arguments order. On the other hand exact can be used not only in delegation but also as regular method call:

fun main() {
  exact(::NotBlankString) {
    it.isNotBlank()
  }
}

But it is rather synthetic example, doesn't look like a real use case

@nomisRev I am not quite familiar with Raise api, can you tell me where to look for implementation examples?

Copy link
Collaborator

@ILIYANGERMANOV ILIYANGERMANOV May 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for the explanation @ustits! I did all the code examples from my Fold w/o an actual IDE/compiler - apologies for that! Regarding Raise - I'd recommend:

Raise TL;DR;

  • like throws but type-safe, in order to raise you need a Raise<A> context
  • to "catch" raise use recover
  • interoperable with Either
  • @nomisRev can give you a better explanation and details but that should be enough to get you started

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @ILIYANGERMANOV , can you tell me, am I moving in the right direction? As I understood I need to use recover on the constraint and map the result onto Either. Btw in such scenario probably we don't need a constructor as an argument:

fun <A, B> exact(constraint: Raise<ExactError>.(A) -> B): Exact<A, B> {
  return object : Exact<A, B> {
    override fun from(value: A): Either<ExactError, B> {
      return recover({
        constraint(value).right()
      }) {
        error -> error.left()
      }
    }
  }
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ustits yes, it looks good to me! Thank you for making the change :)
A valid example usage would look like this, right?

companion object : Exact<String, NotBlankTrimmedString> by exact({
   ensureNotNull(it.trim().takeIf(String::isNotBlank)?.let(::NotBlankTrimmedString)) { 
       ExactError("Cannot be blank!")
   }
})
companion object : Exact<Float, Percent> by exact({
   Percent(it.coerceIn(0f, 1f))
})

I like this API a lot! It's a lot simpler when we get rid of the constructor.
The constructor can be required only for the predicate exact case.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ustits instead of using recover with left and right you can also just use the either block. It works through Raise 😉. TL;DR Raise is a higher-level abstraction that can work over errors of E. So for Either it's just E, but for Option it's for example None or typealias Null = Nothing? for _nullable types`.

      return either { constraint(value) }

return object : Exact<A, B> {
override fun from(value: A): Either<ExactError, B> {
return if (predicate.invoke(value)) {
constructor.invoke(value).right()
} else {
ExactError("Value ($value) doesn't match the predicate").left()
}
}
}
}

infix fun <A, B, C> Exact<A, B>.and(other: Exact<B, C>): Exact<A, C> {
return AndExact(this, other)
}
37 changes: 0 additions & 37 deletions src/commonMain/kotlin/example.kt

This file was deleted.

73 changes: 0 additions & 73 deletions src/commonTest/kotlin/ExampleSpec.kt

This file was deleted.

37 changes: 37 additions & 0 deletions src/commonTest/kotlin/arrow/exact/ExactSpec.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package arrow.exact

import io.kotest.assertions.arrow.core.shouldBeRight
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNotBe

class ExactSpec : StringSpec({
"creates NotBlankTrimmedString" {
val notBlank = NotBlankTrimmedString.fromOrThrow(" test ")
notBlank.str shouldBe "test"
}

"throws exception on failed check" {
shouldThrow<ExactException> {
NotBlankTrimmedString.fromOrThrow(" ")
}
}

"returns not null" {
NotBlankTrimmedString.fromOrNull("test") shouldNotBe null
}

"returns null" {
NotBlankTrimmedString.fromOrNull(" ") shouldBe null
}

"returns right" {
val either = NotBlankTrimmedString.from(" test ")
either.map { it.str } shouldBeRight "test"
}

"returns left" {
NotBlankTrimmedString.from(" ").isLeft() shouldBe true
}
})
21 changes: 21 additions & 0 deletions src/commonTest/kotlin/arrow/exact/Strings.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package arrow.exact

import arrow.core.Either
import arrow.core.right

class NotBlankString private constructor(val str: String) {
companion object : Exact<String, NotBlankString> by exact(String::isNotBlank, ::NotBlankString)
}

class NotBlankTrimmedString private constructor(val str: String) {
ILIYANGERMANOV marked this conversation as resolved.
Show resolved Hide resolved

private object TrimmedString : Exact<NotBlankString, NotBlankTrimmedString> {

override fun from(value: NotBlankString): Either<ExactError, NotBlankTrimmedString> {
val trimmed = value.str.trim()
return NotBlankTrimmedString(trimmed).right()
}
}

companion object : Exact<String, NotBlankTrimmedString> by NotBlankString and TrimmedString
}