Created
December 21, 2018 13:48
-
-
Save yasuabe/61dec6bb08bc75aeb8afb3949c2e246c to your computer and use it in GitHub Desktop.
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.Alternative | |
import cats.syntax.apply._ | |
import cats.syntax.semigroupk._ | |
import cats.syntax.option._ | |
import cats.instances.option._ | |
import cats.syntax.traverse._ | |
import cats.instances.list._ | |
trait Div[A] { | |
def div(n: Int): Option[A] | |
} | |
object Div { | |
def apply(m: Int, s: String): Div[String] = n => if (n % m == 0) s.some else None | |
val Default: Div[String] = n => n.toString.some | |
} | |
implicit val dividesAlternative = new Alternative[Div] { | |
def empty[A]: Div[A] = _ => None | |
def combineK[A](x: Div[A], y: Div[A]): Div[A] = in => x.div(in) orElse y.div(in) | |
def pure[A](x: A): Div[A] = _ => x.some | |
def ap[A, B](ff: Div[A => B])(fa: Div[A]): Div[B] = | |
in => ff.div(in) ap fa.div(in) | |
} | |
import Div.Default | |
val fizzbuzz = Div(15, "FizzBuzz") <+> Div(3, "Fizz") <+> Div(5, "Buzz") <+> Default | |
(1 to 100).map(fizzbuzz.div).toList.sequence[Option, String] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment