Skip to content

Instantly share code, notes, and snippets.

@ngsw-taro
Created June 10, 2012 14:55
Show Gist options
  • Save ngsw-taro/2906042 to your computer and use it in GitHub Desktop.
Save ngsw-taro/2906042 to your computer and use it in GitHub Desktop.
RPN
import java.util.LinkedList
import java.util.List
fun rpn(expression : String) : Double {
val expressionElements = expression.split(' ').toLinkedList()
val result = foldl(rpn, Stack<Double>(), expressionElements)
return result.pop()
}
private fun foldl<T, U>(f : (T, U) -> T, a : T, l : List<U>) : T {
if(l.size == 0) {
return a
}
return foldl(f, f(a, l.remove(0)), l)
}
private val rpn : (Stack<Double>, String) -> Stack<Double> = {
(stack : Stack<Double>, str : String) ->
when(str) {
"+" -> stack.push( stack.pop() + stack.pop())
"-" -> stack.push( -stack.pop() + stack.pop())
"*" -> stack.push( stack.pop() * stack.pop())
"/" -> stack.push(1/stack.pop() * stack.pop())
else -> stack.push(str.toDouble())
}
stack
}
private class Stack<T>() {
private val elements = LinkedList<T>()
fun push(e : T) = elements.addFirst(e)
fun pop() = elements.remove()
}
private inline fun test(b : Boolean) {
if(!b) throw AssertionError()
}
fun main(args : Array<String>) {
test(rpn("1 2 +") == 3.0)
test(rpn("1 2 -") == -1.0)
test(rpn("1 2 *") == 2.0)
test(rpn("1 2 /") == 0.5)
test(rpn("1 2 + 3 *") == 9.0)
test(rpn("1 2 3 + *") == 5.0)
test(rpn("1 2 - 3 4 + *") == -7.0)
test(rpn("1 2 3 4 * * +") == 25.0)
test(rpn("1 2 3 4 * * 5 6 + -") == 13.0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment