Last active
July 21, 2022 14:52
-
-
Save sshark/574b8e91919454cbafcb0c6a447cecc0 to your computer and use it in GitHub Desktop.
Demonstrate contravariant Functor with Show typeclass without using Cats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.teckhooi | |
import scala.language.implicitConversions | |
trait Show[A] { | |
def show(a: A): String | |
} | |
trait ShowOps { | |
def show: String | |
} | |
implicit def showOps[A: Show](a: A): ShowOps = new ShowOps { | |
override def show: String = implicitly[Show[A]].show(a) | |
} | |
trait ContraMap[F[_]] { | |
def contraMap[A, B](fa: F[A])(f: B => A): F[B] | |
} | |
case class Money(amount: Int) | |
case class Salary(size: Money) | |
object ShowMeTheMoneyApp extends App { | |
implicit val showContraMap: ContraMap[Show] = new ContraMap[Show] { | |
override def contraMap[A, B](fa: Show[A])(f: B => A): Show[B] = (b: B) => fa.show(f(b)) | |
} | |
implicit val showMoney: Show[Money] = (m: Money) => s"$$${m.amount}" | |
implicit val showSalary: Show[Salary] = | |
showContraMap.contraMap[Money, Salary](showMoney)(salary => salary.size) | |
println(Salary(Money(1000)).show) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment