Skip to content

Instantly share code, notes, and snippets.

@Yaneeve
Created December 14, 2018 15:06
Show Gist options
  • Save Yaneeve/19a2615f3e4ab45c87920d7eaf616ef2 to your computer and use it in GitHub Desktop.
Save Yaneeve/19a2615f3e4ab45c87920d7eaf616ef2 to your computer and use it in GitHub Desktop.
Continuation Passing Style - example converted to scala from haskell
object Dollar { // https://en.wikibooks.org/wiki/Haskell/Higher-order_functions#Function_manipulation
def $[A, B]: (A => B) => A => B = { f => { a => f(a) } }
}
Dollar.$[Int, Int]{_ * 2}(3)
implicit class DollarOps[A, B](f: A => B) {
private def app[O, P]: (O => P, O) => P = Function.uncurried(Dollar.$)
def $(b: A) = app(f, b)
}
val s = Seq({x: Int => x * 2}, {x: Int => x + 13})
s.map(_ $ 3)
//~~~~~~~~~~~~
//https://en.wikibooks.org/wiki/Haskell/Continuation_passing_style#Passing_continuations
val add: Int => Int => Int = {x => { y => x + y}}
//add(1)(2)
//Function.uncurried(add)(1, 2)
def addCps[R]: Int => Int => ((Int => R) => R) = {x => { y =>
def lambda[K]: (Int => K) => K = {k: (Int => K) => k(add(x)(y))}
lambda
}}
val square: Int => Int = { x => x * x }
//square(2)
def squareCps[R]: Int => ((Int => R) => R) = { x =>
def lambda[K]: (Int => K) => K = { k: (Int => K) => k(square(x)) }
lambda
}
val pythagoras: Int => Int => Int = {x => {y => add(square(x))(square(y))}}
//pythagoras(2)(3)
//Function.uncurried(pythagoras)(2, 3)
def pythagorasCps[R]: Int => Int => ((Int => R) => R) = {x => {y =>
def lambda[K]: (Int => K) => K = {k: (Int => K) =>
val `x^2`: (Int => K) => K = squareCps[K](x)
val `y^2`: (Int => K) => K = squareCps[K](y)
`x^2` $ { xSquared =>
`y^2` $ { ySquared =>
val added: (Int => K) => K = addCps[K](xSquared)(ySquared)
added $ k
}
}
}
lambda
}}
val sCps: (Int => Unit) => Unit = squareCps[Unit](2)
sCps({a => println(a)})
val aCps: (Int => Unit) => Unit = addCps[Unit](1)(2)
aCps({a =>
val b = a*13
println(b)
})
val pCsp: (Int => Unit) => Unit = pythagorasCps[Unit](3)(4)
pCsp(println)
//https://scastie.scala-lang.org/Yaneeve/Z5fEW8m2RHq23UTy9wkVEA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment