Skip to content

Instantly share code, notes, and snippets.

@yamamotoj
Created February 4, 2016 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yamamotoj/aeaf43e370b82f5db6b7 to your computer and use it in GitHub Desktop.
Save yamamotoj/aeaf43e370b82f5db6b7 to your computer and use it in GitHub Desktop.
Stack Machine in kotlin
class Stack(val value:Int, val succ:Stack?){
fun push(i:Int) = Stack(i, this)
fun apply(op:(Int, Int) -> Int):Stack = succ?.let{
Stack(op(value, it.value), succ.succ)
} ?: throw IllegalArgumentException()
}
fun solution(s:String):Int =s.fold<Stack?>(null){ stack , char -> when(char){
'0','1','2','3','4','5','6','7','8','9' -> stack?.let {it.push(char - '0')} ?: Stack(char- '0', null)
'+' -> stack?.let { it.apply{ x1, x2 -> x1 + x2 } } ?: throw IllegalArgumentException()
'*' -> stack?.let { it.apply{ x1, x2 -> x1 * x2 } } ?: throw IllegalArgumentException()
else -> throw IllegalArgumentException()
}}?.value ?: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment