Skip to content

Instantly share code, notes, and snippets.

@juanjovazquez
Created March 29, 2016 15:43
Show Gist options
  • Save juanjovazquez/c957c888b1de14071ebe to your computer and use it in GitHub Desktop.
Save juanjovazquez/c957c888b1de14071ebe to your computer and use it in GitHub Desktop.
Translation of Raul Raja's article `FP for the average Joe - I - ScalaZ Validation` for using cats library instead of scalaz. @see http://bit.ly/1UzKBEW
/**
Translation of Raul Raja's article
`FP for the average Joe - I - ScalaZ Validation`
for using cats library instead of scalaz.
@see http://bit.ly/1UzKBEW
*/
package joe
object Validation_1 {
def toInts(maybeInts: List[String]): List[Int] =
maybeInts map (_.toInt)
}
object Validation_2 {
import scala.util.Try
def toInts(maybeInts: List[String]): Try[List[Int]] =
Try(maybeInts map (_.toInt))
}
object Validation_3 {
import cats.data.{ValidatedNel, Validated}
import cats.std.list._
def toInts(maybeInts: List[String]): ValidatedNel[Throwable, List[Int]] = {
val validationList = maybeInts map { s =>
Validated.catchNonFatal(s.toInt :: Nil).toValidatedNel
}
validationList reduce (_ combine _)
}
}
object Validation_4 {
import cats._
import cats.implicits._
import cats.data.{ValidatedNel, Validated}
import scala.language.higherKinds
def validate[F[_]: Foldable, A, B: Monoid]
(in: F[A])
(out: A => B): ValidatedNel[Throwable, B] =
in foldMap (a => Validated.catchNonFatal(out(a)).toValidatedNel)
def toInts(maybeInts: List[String]): ValidatedNel[Throwable, List[Int]] =
validate(maybeInts)(_.toInt :: Nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment