From 4f5edc754bc7a28f731c57d991b262233fcbc974 Mon Sep 17 00:00:00 2001 From: yoshinorin Date: Sun, 3 Dec 2023 21:12:38 +0900 Subject: [PATCH] refactor(syntax): more abstraction, use `HKT` instead of `IO` --- .../net/yoshinorin/qualtet/syntax/io.scala | 17 ----------------- .../net/yoshinorin/qualtet/syntax/monad.scala | 18 ++++++++++++++++++ .../net/yoshinorin/qualtet/syntax/syntax.scala | 2 +- .../yoshinorin/qualtet/syntax/throwable.scala | 1 + 4 files changed, 20 insertions(+), 18 deletions(-) delete mode 100644 src/main/scala/net/yoshinorin/qualtet/syntax/io.scala create mode 100644 src/main/scala/net/yoshinorin/qualtet/syntax/monad.scala diff --git a/src/main/scala/net/yoshinorin/qualtet/syntax/io.scala b/src/main/scala/net/yoshinorin/qualtet/syntax/io.scala deleted file mode 100644 index 2de99bae..00000000 --- a/src/main/scala/net/yoshinorin/qualtet/syntax/io.scala +++ /dev/null @@ -1,17 +0,0 @@ -package net.yoshinorin.qualtet.syntax - -import cats.effect.IO -import scala.reflect.ClassTag - -trait io { - - extension [A: ClassTag](io: IO[Option[A]]) { - def throwIfNone[F <: Throwable](t: F): IO[A] = { - io.flatMap { - case Some(a: A) => IO(a) - case _ => IO.raiseError(t) - } - } - } - -} diff --git a/src/main/scala/net/yoshinorin/qualtet/syntax/monad.scala b/src/main/scala/net/yoshinorin/qualtet/syntax/monad.scala new file mode 100644 index 00000000..de74b6a1 --- /dev/null +++ b/src/main/scala/net/yoshinorin/qualtet/syntax/monad.scala @@ -0,0 +1,18 @@ +package net.yoshinorin.qualtet.syntax + +import cats.{Monad, MonadError} +import scala.reflect.ClassTag +import cats.syntax.flatMap.toFlatMapOps + +trait monad { + + extension [F[_]: Monad, A: ClassTag](monad: F[Option[A]]) { + def throwIfNone[T <: Throwable](t: T)(implicit me: MonadError[F, Throwable]): F[A] = { + monad.flatMap { + case Some(a: A) => Monad[F].pure(a) + case _ => MonadError[F, Throwable].raiseError(t) + } + } + } + +} diff --git a/src/main/scala/net/yoshinorin/qualtet/syntax/syntax.scala b/src/main/scala/net/yoshinorin/qualtet/syntax/syntax.scala index 3b4f8656..a27e2f34 100644 --- a/src/main/scala/net/yoshinorin/qualtet/syntax/syntax.scala +++ b/src/main/scala/net/yoshinorin/qualtet/syntax/syntax.scala @@ -1,3 +1,3 @@ package net.yoshinorin.qualtet -package object syntax extends string with eitherT with tuple with validator with io with option with json with http with throwable with points +package object syntax extends string with eitherT with tuple with validator with monad with option with json with http with throwable with points diff --git a/src/main/scala/net/yoshinorin/qualtet/syntax/throwable.scala b/src/main/scala/net/yoshinorin/qualtet/syntax/throwable.scala index 0472d1bd..82289423 100644 --- a/src/main/scala/net/yoshinorin/qualtet/syntax/throwable.scala +++ b/src/main/scala/net/yoshinorin/qualtet/syntax/throwable.scala @@ -19,4 +19,5 @@ trait throwable { IO(e) } } + }