Skip to content

Instantly share code, notes, and snippets.

@rabitarochan
Created September 24, 2015 09:40
Show Gist options
  • Save rabitarochan/b1d4364ec2e2fa7c2c86 to your computer and use it in GitHub Desktop.
Save rabitarochan/b1d4364ec2e2fa7c2c86 to your computer and use it in GitHub Desktop.
case class Endo[A](run: A => A) {
def apply(a: A): A = run(a)
def compose(other: Endo[A]): Endo[A] = {
Endo.endo(run compose other.run)
}
def andThen(other: Endo[A]): Endo[A] = {
other compose this
}
def ~>(other: Endo[A]): Endo[A] = compose(other)
}
object Endo {
def endo[A](f: A => A): Endo[A] = new Endo(f)
def idEndo[A]: Endo[A] = endo[A](a => a)
}
object Main extends App{
// Int
{
val f = Endo.endo[Int](_ + 1)
val g = Endo.endo[Int](_ * 2)
val fg = f ~> g
val gf = g ~> f
println(s"fg(3): ${fg(3)}")
println(s"gf(3): ${gf(3)}")
}
// Int => Int
{
val f = Endo.endo[Int => Int](_f => i => _f(i + 1))
val g = Endo.endo[Int => Int](_g => i => _g(i * 2))
val fg = f ~> g
val gf = g ~> f
println(s"fg(identity)(3): ${fg(identity)(3)}")
println(s"gf(identity)(3): ${gf(identity)(3)}")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment