Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created April 7, 2019 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yasuabe/43b9e0e7c7d8a2f8e3da30b1ed815e4b to your computer and use it in GitHub Desktop.
Save yasuabe/43b9e0e7c7d8a2f8e3da30b1ed815e4b to your computer and use it in GitHub Desktop.
sample code for Cats MTL ApplicativeHandle
import cats.syntax.applicative._
import cats.Applicative
import cats.data.Validated
import cats.instances.string._
import cats.mtl.FunctorRaise
import cats.mtl.syntax.handle._
import cats.mtl.instances.handle._
import cats.syntax.traverse._
import cats.instances.list._
def parseNumber[F[_]: Applicative](in: String)(implicit F: FunctorRaise[F, String]): F[Double] =
if (in.matches("-?[0-9]+")) in.toDouble.pure[F]
else F.raise(in) // raise 構文
List("100", "abc", "200", "def") traverse parseNumber[Validated[String, ?]]
// Invalid(abcdef)
List("100", "abc", "200", "def") traverse { s =>
parseNumber[Validated[String, ?]](s).handle[String](_ => Double.NaN) // handle 構文。
}
// Valid(List(100.0, NaN, 200.0, NaN))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment