Skip to content

Commit

Permalink
feat(boundaries): add a either boundary
Browse files Browse the repository at this point in the history
  • Loading branch information
tassiluca committed Jan 4, 2024
1 parent 835ceee commit 06e21bd
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 2 deletions.
14 changes: 14 additions & 0 deletions src/main/scala/io/github/tassiLuca/boundaries/either.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package io.github.tassiLuca.boundaries

import scala.util.boundary
import scala.util.boundary.{Label, break}

object either:

inline def apply[L, R](inline body: Label[Left[L, Nothing]] ?=> R): Either[L, R] =
boundary(Right(body))

extension [L, R](e: Either[L, R])
inline def ?(using Label[Left[L, Nothing]]): R = e match
case Right(value) => value
case Left(value) => break(Left(value))
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,7 @@ object BoundaryExamples extends App:
def firstColumn[T](xss: List[List[T]]): Option[List[T]] =
optional:
xss.map(_.headOption.?)

def firstColumn2[T](xss: List[List[T]]): Option[List[T]] =
val firstElements = xss.map(_.headOption)
if firstElements.forall(_.isDefined) then Some(firstElements.flatten) else None
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package io.github.tassiLuca.boundaries.examples
import scala.util.boundary
import scala.util.boundary.{Label, break}

trait EitherExamples:
trait EitherRawExamples:

type User
type UserId
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package io.github.tassiLuca.boundaries.examples

import io.github.tassiLuca.boundaries.examples.BoundaryExamples.{firstColumn, firstIndex}
import io.github.tassiLuca.boundaries.examples.BoundaryExamples.{firstColumn, firstColumn2, firstIndex}
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers.shouldBe

Expand All @@ -14,3 +14,8 @@ class BoundaryExamplesTest extends AnyFlatSpec:
firstColumn(List(List(1, 2, 3), List(3))) shouldBe Some(List(1, 3))
firstColumn(List(List(), List(1))) shouldBe None
}

"BoundaryExamples.firstColumn2" should "return a List with the first element of each List given in input" in {
firstColumn2(List(List(1, 2, 3), List(3))) shouldBe Some(List(1, 3))
firstColumn2(List(List(), List(1))) shouldBe None
}

0 comments on commit 06e21bd

Please sign in to comment.