Skip to content

Instantly share code, notes, and snippets.

@ahoy-jon
Created September 23, 2025 23:34
Show Gist options
  • Select an option

  • Save ahoy-jon/7ee6ebfa08320c70a0be2d90dc897274 to your computer and use it in GitHub Desktop.

Select an option

Save ahoy-jon/7ee6ebfa08320c70a0be2d90dc897274 to your computer and use it in GitHub Desktop.
Direct Style vs Monadic Style Example
//> using scala 3.7.3
//> using dep in.rcard.raise4s::core:0.5.0
//> using dep io.getkyo::kyo-core::1.0-RC1
//> using dep io.getkyo::kyo-direct::1.0-RC1
//> using dep io.getkyo::kyo-combinators::1.0-RC1
import in.rcard.raise4s.*
import kyo.*
trait DirectStyle[A]:
def foo: A
def bar: A
def plus(a1: A, a2: A): A
def qux: A = plus(foo, bar)
def repeat3times(a: () => A): A = plus(plus(a(), a()), a())
def baz: A = repeat3times(() => qux)
trait MonadicStyle[A, S]:
val foo: A < S
val bar: A < S
def plus(a1: A, a2: A): A < S
def qux: A < S = (foo <*> bar).map(plus)
def repeat3times[S0](v: A < S0): A < (S0 & S) =
// for
// a_1 <- v
// a_2 <- v
// a12 <- plus(a_1, a_2)
// a_3 <- v
// a123 <- plus(a12, a_3)
// yield a123
((v <*> v).map(plus) <*> v).map(plus)
def baz: A < S = repeat3times(qux)
trait DirectSyntax[A, S]:
val foo: A < S
val bar: A < S
def plus(a1: A, a2: A): A < S
def qux: A < S =
direct:
// plus(foo.now, bar.now).now // can be improved in kyo-direct
val a1 = foo.now
val a2 = bar.now
plus(a1, a2).now
def repeat3times[S0](v: A < S0): A < (S0 & S) =
direct:
// plus(plus(v.now, v.now).now, v.now).now // can be improved in kyo-direct
val a1 = v.now
val a2 = v.now
val a12 = plus(a1, a2).now
val a3 = v.now
plus(a12, a3).now
def baz: A < S = repeat3times(qux)
trait AboutSafety[A, B, Error]:
type D_CreatePure = Raise[Error] ?=> A => B
type K_CreatePure = (A => B) < Abort[Error]
type D_UseLazy = A => Raise[Error] ?=> B
type K_UseLazy = A => B < Abort[Error]
type D_Nested = Raise[Error] ?=> A => Raise[Error] ?=> B
type K_Nested = (A => B < Abort[Error]) < Abort[Error]
def d_toCreatePure(nested: D_Nested): D_CreatePure = raise ?=> a => nested(a) // unsafe without Caprese
def k_toCreatePure(nested: K_Nested): K_CreatePure = ??? // not possible in monadic style
def d_toUseLazy(nested: D_Nested): D_UseLazy = a => raise ?=> nested(a)
def k_toUseLazy(nested: K_Nested) = (a: A) => nested.map(f => f(a))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment