Created
February 4, 2016 01:14
-
-
Save yamamotoj/aeaf43e370b82f5db6b7 to your computer and use it in GitHub Desktop.
Stack Machine in kotlin
This file contains 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
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