Skip to content

Instantly share code, notes, and snippets.

@mathhun
Created August 16, 2016 09:08
Show Gist options
  • Save mathhun/5349ffb1a8e1a928c4f8d1a5e9aeab4a to your computer and use it in GitHub Desktop.
Save mathhun/5349ffb1a8e1a928c4f8d1a5e9aeab4a to your computer and use it in GitHub Desktop.
scalaExercisesCats.scala
import cats._, cats.implicits._
import cats.data.Xor
object Main extends App {
assert(Foldable[List].foldK(List(List(1, 2), List(3, 4, 5))) == List(1,2,3,4,5))
assert(Foldable[List].foldK(List(None, Option("two"), Option("three"))) == Some("two"))
def parseInt(s: String): Option[Int] =
Xor.catchOnly[NumberFormatException](s.toInt).toOption
assert(Foldable[List].traverse_(List("1", "2", "3"))(parseInt) == Some(()))
assert(Foldable[List].traverse_(List("a", "b", "c"))(parseInt) == None)
val FoldableListOption = Foldable[List].compose[Option]
assert(FoldableListOption.fold(List(Option(1), Option(2), Option(3), Option(4))) == 10)
assert(FoldableListOption.fold(List(Option("1"), Option("2"), None, Option("3"))) == "123")
// MonoidK
// Traverse
// cats.data.Reader // Reader[E, A] == Kleisli[Id, E, A]
import cats.Semigroup
import cats.data.{NonEmptyList, OneAnd, Validated, ValidatedNel, Xor}
import cats.std.list._
import cats.syntax.traverse._
def parseIntXor(s: String): Xor[NumberFormatException, Int] =
Xor.catchOnly[NumberFormatException](s.toInt)
def parseIntValidated(s: String): ValidatedNel[NumberFormatException, Int] =
Validated.catchOnly[NumberFormatException](s.toInt).toValidatedNel
assert(List("1", "2", "3").traverseU(parseIntXor) == Xor.Right(List(1, 2, 3)))
assert(List("1", "abc", "3").traverseU(parseIntXor).isLeft)
import cats.data.{NonEmptyList, OneAnd, ValidatedNel}
assert(List("1", "2", "3").traverseU(parseIntValidated).isValid)
import cats.syntax.foldable._
assert(List(Option(1), Option(2), Option(3)).sequence_ == Some(()))
assert(List(Option(1), None, Option(3)).sequence_ == None)
// IDENTITY
val one: Int = 1
Functor[Id].map(one)(_ + 1)
assert(Applicative[Id].pure(42) == 42)
Monad[Id].map(one)(_ + 1)
Monad[Id].flatMap(one)(_ + 1)
val fortytwo: Int = 42
assert(Comonad[Id].coflatMap(fortytwo)(_ + 1) == 43)
// Xor
val right: String Xor Int = Xor.Right(41)
assert(right.map(_ + 1) == Xor.Right(42))
val left: String Xor Int = Xor.Left("went of")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment