Skip to content

Instantly share code, notes, and snippets.

@Yaneeve
Created December 14, 2018 17:38
Show Gist options
  • Save Yaneeve/93edb9a45eae5cdeda6a1ddd89e629ac to your computer and use it in GitHub Desktop.
Save Yaneeve/93edb9a45eae5cdeda6a1ddd89e629ac to your computer and use it in GitHub Desktop.

Revisions

  1. Yaneeve created this gist Dec 14, 2018.
    45 changes: 45 additions & 0 deletions cps_no_curry.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    // https://en.wikibooks.org/wiki/Haskell/Continuation_passing_style#Passing_continuations

    def add(x: Int, y:Int): Int = x + y

    def addCps[R](x: Int, y: Int): ((Int => R) => R) = {
    def lambda[K]: (Int => K) => K = {k: (Int => K) => k(add(x, y))}
    lambda
    }

    def square(x: Int): Int = x * x

    def squareCps[R](x: Int): ((Int => R) => R) = {
    def lambda[K]: (Int => K) => K = { k: (Int => K) => k(square(x)) }
    lambda
    }

    def pythagoras(x: Int, y: Int): Int = add(square(x), square(y))

    def pythagorasCps[R](x: Int, y: Int): ((Int => R) => R) = {
    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 =>
    addCps[K](xSquared, ySquared)(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/PIcmIoO6SJyJREjNezp8qg