Skip to content

Instantly share code, notes, and snippets.

View rohinp's full-sized avatar

Rohin rohinp

  • Amsterdam, The Netherlands
View GitHub Profile
trait Monoid[T] {
def associative(t1:T,t2:T):
def zero:T
}
//We will take a really simple example of summing a list of ints
def summ(xs:List[Int]):Int = xs.foldLeft(0)(_ + _)
//there is a reason why we have selected foldLeft operation
//May be later in the blog it will be clear.
//this wont work as type T is unware of the operation +
//value 0 is not a zero value for type T
def summ[T](xs:List[T]):T = xs.foldLeft(0)(_ + _)
//we have our monoid
trait Monoid[T] {
def associative(t1:T,t2:T):T
def zero:T
}
// lets have an implimentaion for int type
implicit val IntSumMonoid = new Monoid[Int] {
def associative(t1:Int,t2:Int): t1 + t2
def zero:Int = 0
// one more implementation
implicit val StringConcateMonoid = new Monoid[String] {
def associative(t1:String,t2:String): t1 + t2
def zero:Int = ""
}
//Lets pass some strings
summ(List("1.","2.","3..."))
trait Monoid[T] {
def assco(t1:T,t2:T):T
def zero:T
}
implicit val IntSumMnoid = new Monoid[Int] {
override def assco(t1: Int, t2: Int): Int = t1 + t2
override def zero: Int = 0
}
def add[A: Num](a: A, b: A): A = implicitly[Num[A]].+(a, b)
trait Num[A] {
def +(a: A, b: A): A
def -(a: A, b: A): A
def *(a: A, b: A): A
def negate(a: A): A
def fromInteger(i: Int): A
}
//simple addition operation, nothing to explain in this v1
def add(a: Int, b: Int): Int = a + b
//Lets make version v1 polymorphic
//below code will fail as the type A may or may not have an + operation
def add[A](a: A, b: A): A = a + b
//so we need a trait which can define that operation for us
trait Num[A] {
def +(a: A, b: A): A
@rohinp
rohinp / RecursionSchemes.scala
Last active January 31, 2020 07:32
Trying out recursive schemes with matryoshka scala library
//Notes and code from this talk https://www.youtube.com/watch?v=IlvJnkWH6CA
object RecursiveSchemes extends App{
object one {
sealed trait Exp
final case class IntValue(v:Int) extends Exp
final case class DecValue(v:Double) extends Exp
final case class Sum(exp1:Exp, exp2:Exp) extends Exp
final case class Multiply(exp1:Exp, exp2:Exp) extends Exp
final case class Divide(exp1:Exp, exp2:Exp) extends Exp
import cats.Monad
import cats.implicits._
/*
Interesting to note that if the parametic type is F[A] and your function is expecting F[F[A]]
Then the implicit function as used in the below function works like a charm
It tells scala compiler to use F[F[A]] the implicit is provided by scala itself you don't need to implement
*/
implicit class SomeOps[F[_], A](v:F[A]){