Skip to content

Instantly share code, notes, and snippets.

View harmeetsingh0013's full-sized avatar

Harmeet Singh(Taara) harmeetsingh0013

View GitHub Profile
object EvalExample2 extends App {
def twice(value: Int): Int = value * value
def divideBy2(value: Int): Int = value / 2
val value = 42
val intermediateResult = twice(value)
val result = divideBy2(intermediateResult)
println(result)
object EvalExample1 extends App {
val eager = Eval.now {
println("Hey !! I am eager eval")
"Hello Eval Eager"
}
val lazyEval = Eval.later {
println("Hey !! I am lazy eval")
"Hello Eval Lazy"
object IdExample1 extends App {
def sumSquare[F[_]: Monad](a: F[Int], b: F[Int]): F[Int] = {
a.flatMap(x => b.map(y => x*x + y*y))
}
import cats.instances.list._
import cats.instances.option._
val result1 = sumSquare(Option(2), Option(5))
import cats.Functor
import cats.instances.list._
val ints = List(1, 2, 3, 4, 5)
Functor[List].map(ints)(_.toString)
trait Functor[F[_]] {
def map[A, B](fa: F[A])(f: A => B): F[B]
}
val listFunctor = new Functor[List] {
override def map[A, B](fa: List[A])(f: A => B): List[B] = fa match {
case Nil => Nil
case h :: t => f(h) :: map(t)(f)
}
}
object Example1Monoid extends App {
case class TwitterUser(username: String, followers: Int) extends Ordered[TwitterUser] {
override def compare(that: TwitterUser): Int = {
val c = this.followers - that.followers
if(c == 0) this.username.compareTo(that.username) else c
}
}
implicit val twitterUserMonoid = new Monoid[TwitterUser] {
import cats.kernel.Monoid
object Example1Monoid extends App with Data {
implicit val moneyMonoid = new Monoid[Money] {
override def empty: Money = Money(0, 0)
override def combine(x: Money, y: Money): Money = {
Money(x.dollars + y.dollars + ((x.cents + y.cents) / 100),
(x.cents + y.cents) % 100)
object Example4Semigroup extends App with Data {
implicit val moneySemigroup = new Semigroup[Money] {
override def combine(x: Money, y: Money): Money = {
Money(x.dollars + y.dollars + ((x.cents + y.cents) / 100),
(x.cents + y.cents) % 100)
}
}
import cats.instances.int._
object Example1Semigroup extends App with Data {
trait Addable[T] {
def add(a: T, b: T): T
}
implicit val addInt = new Addable[Int] {
override def add(a: Int, b: Int): Int = a + b
}
// add implementation for int type
implicit val addInt = new Addable[Int] {
override def add(a: Int, b: Int): Int = a + b
}
// add implementation for money type
implicit val addMoney = new Addable[Money] {
override def add(a: Money, b: Money): Money = {
Money(a.dollars + b.dollars + ((a.cents + b.cents) / 100),
(a.cents + b.cents) % 100)