Created
January 8, 2018 01:45
-
-
Save yasuabe/adb493958110dd7f3fd234298500f75f to your computer and use it in GitHub Desktop.
profunctor exercise 1
This file contains hidden or 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
import cats.arrow.Profunctor | |
import cats.data.Kleisli | |
import eu.timepit.refined.api.Refined | |
import eu.timepit.refined.boolean.Not | |
import eu.timepit.refined.generic.Equal | |
import eu.timepit.refined.string.MatchesRegex | |
import eu.timepit.refined.{W, refineMV, refineV} | |
import shapeless.Nat._0 | |
import cats.instances.function._ | |
import cats.syntax.profunctor._ | |
import cats.instances.either._ | |
import cats.syntax.either._ | |
import shapeless._ | |
val fab: Double => Double = x => x + 0.3 | |
val f: Int => Double = x => x.toDouble / 2 | |
val g: Double => Double = x => x * 3 | |
val h = Profunctor[Function1].dimap(fab)(f)(g) | |
h(3) | |
val h2 = fab.dimap(f)(g) | |
type NonZeroInt = Int Refined Not[Equal[_0]] | |
type ErrorOr[A] = Either[String, A] | |
case class Rational(n: Int, d: NonZeroInt) | |
val denomLens = lens[Rational].d | |
def minusOne(nz: NonZeroInt): ErrorOr[NonZeroInt] = refineV(nz.value - 1) | |
val r1 = Rational(1, refineMV(1)) | |
val r2 = Rational(1, refineMV(2)) | |
denomLens.get(r1) | |
val pf = (src: Rational, dst: Rational) => | |
(minusOne _).dimap(denomLens.get)(_.map(denomLens.set(dst)))(src) | |
pf(r1, r2) | |
pf(r2, r1) | |
// ------------------- | |
type NameConstraint = MatchesRegex[W.`"[a-z]+"`.T] | |
type Name = String Refined NameConstraint | |
case class Person(name: Name) | |
val p1 = Person(refineMV("test")) | |
val p2 = Person(refineMV("testfoo")) | |
val stripTest: Kleisli[ErrorOr, Name, Name] = | |
Kleisli(name => refineV(name.value.stripPrefix("test"))) | |
val nameLens = lens[Person].name | |
def dimapped(p: Person) = stripTest.dimap(nameLens.get)(nameLens.set(p)) | |
def stripTestFromName(p: Person) = dimapped(p).run(p) | |
stripTestFromName(p1) | |
stripTestFromName(p2) | |
stripTestFromName(Person(refineMV("abc"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment