Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created December 21, 2018 13:55
Show Gist options
  • Save yasuabe/b0a8f17865950809d8edb073e04034d0 to your computer and use it in GitHub Desktop.
Save yasuabe/b0a8f17865950809d8edb073e04034d0 to your computer and use it in GitHub Desktop.
import cats.Contravariant
import cats.implicits._
case class Money(amount: Int)
case class Earnings(basic: Money)
case class Deductions(tax: Money)
case class Salary(earnings: Earnings, deductions: Deductions)
val salary: Salary = Salary(Earnings(Money(100)), Deductions(Money(10)))
trait Validate[A] {
def validate(a: A): Boolean
}
implicit val validateContr: Contravariant[Validate] = new Contravariant[Validate] {
def contramap[A, B](fa: Validate[A])(f: B => A) = b => fa validate f(b)
}
implicit val nonNegative: Validate[Money] = m => m.amount >= 0
val basic = (e: Earnings) => e.basic
(nonNegative contramap basic) validate Earnings(Money(-100))
val earningsAmount = (s: Salary) => s.earnings.basic
val deductionsAmount = (s: Salary) => s.deductions.tax
(nonNegative contramap earningsAmount) validate salary
(nonNegative contramap deductionsAmount) validate salary
val earnings = (s: Salary) => s.earnings
(nonNegative contramap basic contramap earnings) validate salary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment