Created
August 10, 2012 00:56
-
-
Save vlasovskikh/3309823 to your computer and use it in GitHub Desktop.
Object algebra approach to the Expression problem in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Object algebra approach to the Expression problem in Kotlin. | |
* | |
* See also <http://lambda-the-ultimate.org/node/4572>. | |
*/ | |
// Cannot put this fun inside main() in Kotlin M2 | |
fun exp2plus3<A>(f: IntAlg<A>): A = f.add(f.lit(2), f.lit(3)) | |
fun main(args : Array<String>) { | |
println("${exp2plus3(IntPrint()).print()} = ${exp2plus3(IntFactory()).eval()}") | |
} | |
trait Exp { | |
fun eval(): Int | |
} | |
class Lit(val x: Int) : Exp { | |
override fun eval() = x | |
} | |
class Add(val e1: Exp, val e2: Exp) : Exp { | |
override fun eval() = e1.eval() + e2.eval() | |
} | |
trait IntAlg<A> { | |
fun lit(x: Int): A | |
fun add(e1: A, e2: A): A | |
} | |
class IntFactory : IntAlg<Exp> { | |
override fun lit(x: Int) = Lit(x) | |
override fun add(e1: Exp, e2: Exp) = Add(e1, e2) | |
} | |
trait Print { | |
fun print(): String | |
} | |
class IntPrint : IntAlg<Print> { | |
override fun add(e1: Print, e2: Print) = object : Print { | |
override fun print() = "${e1.print()} + ${e2.print()}" | |
} | |
override fun lit(x: Int) = object : Print { | |
override fun print() = x.toString() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment