Created
December 1, 2020 21:32
-
-
Save amitgupta1202/9abdd8f29814942db23f12059e5d014e to your computer and use it in GitHub Desktop.
instruction demo
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
import java.lang.RuntimeException | |
sealed class InstructionPart | |
data class Add(val argument: Int): InstructionPart() | |
data class Subtract(val argument: Int): InstructionPart() | |
data class Multiply(val argument: Int): InstructionPart() | |
data class Divide(val argument: Int): InstructionPart() | |
data class Apply(val argument: Int): InstructionPart() | |
typealias Instruction = List<InstructionPart> | |
fun String.parse() = "(add|subtract|multiply|divide|apply) ([0-9]*)".toRegex().findAll(this) | |
.fold(emptyList<InstructionPart>()) { instruction, part -> | |
val parts = part.groupValues | |
val operator = parts[1] | |
val argument = parts[2].toInt() | |
val instructionPart = when(operator) { | |
"add" -> Add(argument) | |
"subtract" -> Subtract(argument) | |
"multiply" -> Multiply(argument) | |
"divide" -> Divide(argument) | |
"apply" -> Apply(argument) | |
else -> throw RuntimeException("unknown instruction") | |
} | |
instruction + instructionPart | |
} | |
fun Instruction.apply(): Int { | |
val initialResult = when(val ip = last()) { | |
is Apply -> ip.argument | |
else -> throw RuntimeException("unknown order of instruction") | |
} | |
return fold(initialResult) { r, i -> | |
when(i){ | |
is Add -> r + i.argument | |
is Subtract -> r - i.argument | |
is Multiply -> r * i.argument | |
is Divide -> r / i.argument | |
is Apply -> r | |
} | |
} | |
} | |
fun main() { | |
println("add 2 multiply 3 apply 3".parse().apply()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment