Skip to content

Instantly share code, notes, and snippets.

@arosien
Created November 30, 2018 19:07
Show Gist options
  • Save arosien/d2beb525ec276c2a2f93d169281ceec5 to your computer and use it in GitHub Desktop.
Save arosien/d2beb525ec276c2a2f93d169281ceec5 to your computer and use it in GitHub Desktop.
import $ivy.`org.typelevel::cats-core:1.4.0`
import cats._
import cats.data._
import cats.implicits._
// compose "regular" functions:
def a(s: String): Int = s.length
def b(i: Int): Int = i + 1
def c(i: Int): String = i.toString + "!"
def d(s: String): String = s"got: $s"
val abcd = (a _ andThen b andThen c andThen d)
println(abcd("hi"))
// got: 3!
// compose functions that return Kleisli's:
case class Extra(msg: String)
type WithExtra[A] = Reader[Extra, A]
def a2(s: String): WithExtra[Int] = Kleisli.pure(s.length)
def b2(i: Int): WithExtra[Int] = Kleisli.pure(i + 1)
def c2(i: Int): WithExtra[String] = Kleisli.pure(i.toString + "!")
def d2(s: String): WithExtra[String] = Reader { extra => println(s"extra: $extra"); s"got: $s" }
// Kleisli of Kleisli? Weird?
val abcd2 = Kleisli(a2) andThen Kleisli(b2) andThen Kleisli(c2) andThen Kleisli(d2)
println(abcd2.run("hi").run(Extra("extra")))
// extra: Extra(extra)
// got: 3!
@ivanopagano
Copy link

val a = (_: String).length
val b = (_: Int) + 1
val c = (_: Int).show + "!"
val d = Reader[(Extra, String), String] {
  case (x, s) =>
    val combo = a andThen b andThen c
    println(s"extra: $x")
    s"got: ${combo(s)}"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment