second draft

This commit is contained in:
2024-03-03 16:37:02 +03:00
parent daaf7b060d
commit 335f23f047
11 changed files with 87 additions and 158 deletions
@@ -8,7 +8,6 @@ import javafx.stage.Stage
import ru.darktale.calc.infra.BasicModule
import ru.darktale.calc.infra.CalculationsModule
import ru.darktale.calc.service.KeyEventHandler
import kotlin.system.measureNanoTime
import kotlin.system.measureTimeMillis
@@ -40,7 +39,7 @@ fun main() {
val parser = injector.getInstance(Parser::class.java)
val calculator = injector.getInstance(Calculator::class.java)
val expression = "9^2"
val expression = "(3+1)!"
val time = measureTimeMillis {
println("$expression = ${calculator.calculate(parser.parse(expression))}")
}
@@ -19,7 +19,7 @@ class CalculatorImpl @Inject constructor(
converter.convert(expression).process(operands)
return if (operands.size == 1)
operands.removeFirst().toBigDecimal()
else throw CalculationException()
else throw CalculationException("unexpected stack size: ${operands.size}")
}
private fun List<CalculationToken>.process(operands: ArrayDeque<Operand>) = forEach {
@@ -34,4 +34,4 @@ class CalculatorImpl @Inject constructor(
}
}
class CalculationException : Exception()
class CalculationException(message: String) : Exception(message)
@@ -19,7 +19,7 @@ class ExpressionToRplConverterImpl : ExpressionToRplConverter {
if (operationStack.firstOrNull() is UnaryOperation) this += operationStack.removeFirst() as UnaryOperation
}
is Expression -> queue += element.elements.toTypedArray()
is Expression -> queue.addAll(0, element.elements)
OpenBracket -> operationStack.addFirst(element)
is UnaryOperation -> {
if (element.isPrefix) operationStack.addFirst(element)
+1 -34
View File
@@ -69,6 +69,7 @@ object UnaryMinus : UnaryOperation("-", true)
object UnaryPlus : UnaryOperation("+", true)
object Sinus : UnaryOperation("sin", true)
object Sqrt : UnaryOperation("sqrt", true)
object Factorial : UnaryOperation("!", false)
sealed class BinaryOperation(
override val value: String,
@@ -93,40 +94,6 @@ enum class ElementType {
EXPRESSION,
}
interface OperationMapper<T> {
val typeMap: Map<String, T>
operator fun get(key: String): OperationElement?
}
enum class UnaryOperations(
var operationElement: UnaryOperation?
) {
UNARY_MINUS(UnaryMinus),
UNARY_PLUS(UnaryPlus),
SQRT(Sqrt),
SINUS(Sinus);
companion object : OperationMapper<UnaryOperations> {
override val typeMap = entries.associateBy { it.operationElement.toString() }
override fun get(key: String) = typeMap[key]?.operationElement
}
}
enum class BinaryOperations(
val operationElement: BinaryOperation,
) {
BINARY_MINUS(BinaryMinus),
BINARY_PLUS(BinaryPlus),
MULTIPLICATION(Multiplication),
POWER(Power),
DIVISION(Division);
companion object : OperationMapper<BinaryOperations> {
override val typeMap = entries.associateBy { it.operationElement.toString() }
override fun get(key: String) = typeMap[key]?.operationElement
}
}
enum class Brackets(
val bracket: Bracket,
) {
+15 -11
View File
@@ -1,6 +1,6 @@
package ru.darktale.calc
import java.math.BigDecimal
import com.google.common.math.BigIntegerMath.factorial
import java.math.MathContext.DECIMAL128
import java.util.function.BiFunction
import java.util.function.Function
@@ -10,7 +10,7 @@ interface UnaryOperationFunction<T: UnaryOperation> : Function<Operand, Operand>
interface BinaryOperationFunction<T: BinaryOperation> : BiFunction<Operand, Operand, Operand>
object UnaryMinusFunction : UnaryOperationFunction<UnaryMinus> {
override fun apply(operand: Operand) = operand.toBigDecimal().unaryMinus().toNumber()
override fun apply(operand: Operand) = operand.toBigDecimal().unaryMinus().toOperand()
}
object UnaryPlusFunction : UnaryOperationFunction<UnaryPlus> {
@@ -18,36 +18,40 @@ object UnaryPlusFunction : UnaryOperationFunction<UnaryPlus> {
}
object SinusFunction : UnaryOperationFunction<Sinus> {
override fun apply(operand: Operand) = sin(operand.toBigDecimal().toDouble()).toNumber()
override fun apply(operand: Operand) = sin(operand.toBigDecimal().toDouble()).toOperand()
}
object FactorialFunction : UnaryOperationFunction<Factorial> {
override fun apply(operand: Operand) =
factorial(operand.toBigDecimal().toInt()).toOperand()
}
object SqrtFunction : UnaryOperationFunction<Sqrt> {
override fun apply(operand: Operand) = operand.toBigDecimal().sqrt(DECIMAL128).toNumber()
override fun apply(operand: Operand) = operand.toBigDecimal().sqrt(DECIMAL128).toOperand()
}
object BinaryMinusFunction : BinaryOperationFunction<BinaryMinus> {
override fun apply(first: Operand, second: Operand) =
(first.toBigDecimal() - second.toBigDecimal()).toNumber()
(first.toBigDecimal() - second.toBigDecimal()).toOperand()
}
object BinaryPlusFunction : BinaryOperationFunction<BinaryPlus> {
override fun apply(first: Operand, second: Operand) =
(first.toBigDecimal() + second.toBigDecimal()).toNumber()
(first.toBigDecimal() + second.toBigDecimal()).toOperand()
}
object MultiplicationFunction : BinaryOperationFunction<Multiplication> {
override fun apply(first: Operand, second: Operand) =
(first.toBigDecimal() * second.toBigDecimal()).toNumber()
(first.toBigDecimal() * second.toBigDecimal()).toOperand()
}
object DivisionFunction : BinaryOperationFunction<Division> {
override fun apply(first: Operand, second: Operand) =
(first.toBigDecimal() / second.toBigDecimal()).toNumber()
(first.toBigDecimal() / second.toBigDecimal()).toOperand()
}
object PowerFunction : BinaryOperationFunction<Power> {
override fun apply(first: Operand, second: Operand) =
(first.toBigDecimal().pow(second.toBigDecimal().toInt())).toNumber()
(first.toBigDecimal().pow(second.toBigDecimal().toInt())).toOperand()
}
fun BigDecimal.toNumber() = Operand(toString())
fun Double.toNumber() = Operand(toString())
fun Number.toOperand() = Operand(toString())
+34 -66
View File
@@ -5,55 +5,13 @@ import jakarta.inject.Inject
interface Parser {
fun parse(expression: String): Expression
}
/*
class ParserImpl : Parser {
private val operations = UnaryOperations.typeMap.keys + BinaryOperations.typeMap.keys
override fun parse(expression: String): Expression {
val result = mutableListOf<ExpressionElement>()
var (tokenStart, tokenEnd) = 0 to 0
var prevNumber: String? = null
fun parseTokenOrNull(token: String): ExpressionElement? =
Brackets.typeMap[token]?.bracket
?: if (token in operations) getOperation(result.lastOrNull(), token)
else (token.toBigDecimalOrNull() ?: "${token}0".toBigDecimalOrNull())?.let {
prevNumber = token
return null
} ?: prevNumber?.let {
Number(it)
}
while (tokenEnd < expression.length) {
parseTokenOrNull(expression.substring(tokenStart..tokenEnd))?.let {
result += it
tokenStart = tokenEnd
if (it.elementType == ElementType.NUMBER)
tokenEnd--
else
tokenStart++
}
tokenEnd++
}
if (tokenStart < expression.length) {
result += Number(expression.substring(tokenStart))
}
return Expression(result)
}
private fun getOperation(previousElement: ExpressionElement?, token: String) = when {
previousElement?.elementType == ElementType.NUMBER ||
previousElement?.elementType == ElementType.BRACKET ->
BinaryOperations.typeMap[token]!!.operationElement
else -> UnaryOperations.typeMap[token]!!.operationElement
}
}
*/
class NestedExpressionsParser @Inject constructor(
private val unaryOperations: Map<String, UnaryOperation>,
private val binaryOperations: Map<String, BinaryOperation>,
) : Parser {
private val operations: Set<String> = unaryOperations.keys + binaryOperations.keys
private val maxOperLength = operations.maxBy { it.length }.length
override fun parse(expression: String): Expression {
val stack = ArrayDeque<MutableList<ExpressionElement>>()
@@ -80,16 +38,15 @@ class NestedExpressionsParser @Inject constructor(
Operand(expression.substring(position - it until position))
}
} else {
val operations =
if (elements.getOperationType(position) == ElementType.UNARY_OPERATION) UnaryOperations
else BinaryOperations
val key = getOperationKey(operations.typeMap.keys, expression, position)
position += (key.length)
operations[key]!!
val operation = getOperation(expression, position, elements.isUnaryPrefixOperation(position))
position += operation.value.length
operation
}
}
}
if (stack.isNotEmpty()) throw ParseException("Unexpected end of expression, unclosed bracket")
elements.validate()
return when {
elements.isEmpty() -> EMPTY_EXPRESSION
elements.size == 1 && elements[0] is Expression -> elements[0] as Expression
@@ -112,6 +69,14 @@ class NestedExpressionsParser @Inject constructor(
}
}
private fun List<ExpressionElement>.validate() {
when (val operation = this.lastOrNull()) {
is BinaryOperation -> throw ParseException("expression ends with binary operation")
is UnaryOperation -> if (operation.isPrefix) throw ParseException("expression ends with prefix unary operation")
else -> Unit
}
}
private fun List<ExpressionElement>.validateCloseBracket(position: Int) {
when (this.lastOrNull()) {
is Operand, is Expression, Brackets.CLOSE_BRACKET.bracket -> Unit
@@ -119,24 +84,28 @@ class NestedExpressionsParser @Inject constructor(
}
}
private fun List<ExpressionElement>.getOperationType(position: Int) =
when (this.lastOrNull()) {
is Operand, is Expression -> ElementType.BINARY_OPERATION
is UnaryOperation -> throw ParseException("Not a number after unary operation", position)
else -> ElementType.UNARY_OPERATION
private fun List<ExpressionElement>.isUnaryPrefixOperation(position: Int) =
when (val operation = this.lastOrNull()) {
is Operand, is Expression -> false
is UnaryOperation -> {
if (operation.isPrefix) throw ParseException(
"Not a number or expression after prefix unary operation",
position
)
else false
}
else -> true
}
private fun getOperationKey(keys: Set<String>, expression: String, position: Int): String {
val maxLength = keys.maxBy { it.length }.length
var length = 0
while (length < maxLength && position + length <= expression.length &&
expression.substring(position until position + length) !in keys
) length++
if (position + length >= expression.length
|| expression.substring(position until position + length) !in keys
)
private fun getOperation(expression: String, position: Int, isUnaryPrefixOper: Boolean): OperationElement {
val acceptableOperations =
if (isUnaryPrefixOper) unaryOperations.filter { it.value.isPrefix }
else unaryOperations.filter { !it.value.isPrefix } + binaryOperations
for (length in position until minOf(position + maxOperLength, expression.length)) {
acceptableOperations[expression.substring(position..length)]?.let { return it }
}
throw ParseException("Unknown operation", position)
return expression.substring(position until position + length)
}
private fun getNumberLength(expression: String, start: Int): Int {
@@ -157,4 +126,3 @@ class ParseException(message: String, position: Int? = null) :
Throwable("""$message${position?.let { " at $it" } ?: ""}""")
private val EMPTY_EXPRESSION = Expression(emptyList())
@@ -3,7 +3,6 @@ package ru.darktale.calc.infra
import com.google.inject.AbstractModule
import com.google.inject.TypeLiteral
import com.google.inject.multibindings.MapBinder
import com.google.inject.multibindings.Multibinder
import ru.darktale.calc.*
import ru.darktale.calc.service.CalculatorService
import ru.darktale.calc.service.CalculatorServiceImpl
@@ -23,6 +22,7 @@ class CalculationsModule : AbstractModule() {
UnaryPlus to UnaryPlusFunction,
Sinus to SinusFunction,
Sqrt to SqrtFunction,
Factorial to FactorialFunction,
)
private val binaryOperationMap = mapOf(
BinaryMinus to BinaryMinusFunction,
@@ -67,12 +67,6 @@ class CalculationsModule : AbstractModule() {
}
}
Multibinder.newSetBinder(binder, BinaryOperation::class.java).apply {
binaryOperationMap.keys.forEach {
addBinding().toInstance(it)
}
}
bind(ExpressionToRplConverter::class.java).to(ExpressionToRplConverterImpl::class.java)
bind(Calculator::class.java).to(CalculatorImpl::class.java)
bind(Parser::class.java).to(NestedExpressionsParser::class.java)
@@ -5,7 +5,6 @@ import javafx.event.EventHandler
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import ru.darktale.calc.CalcController
import java.awt.Event.BACK_SPACE
interface KeyEventHandler : EventHandler<KeyEvent>
@@ -47,5 +47,9 @@ class ExpressionProvider : ArgumentsProvider {
Expression(UnaryMinus, Operand("3"), Multiplication, OpenBracket, UnaryMinus, Operand("2"), BinaryPlus, Operand("1"), CloseBracket),
listOf(Operand("3"), UnaryMinus, Operand("2"), UnaryMinus, Operand("1"), BinaryPlus, Multiplication)
),
Arguments.of(
Expression(OpenBracket, Operand("5"), BinaryPlus, Operand("1"), CloseBracket, Factorial),
listOf(Operand("5"), Operand("1"), BinaryPlus, Factorial)
),
)
}
@@ -1,5 +1,6 @@
package ru.darktale.calc
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.params.ParameterizedTest
@@ -8,7 +9,28 @@ import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class NestedExpressionsParserTest {
private val parser = NestedExpressionsParser()
private lateinit var unaryOperations: Map<String, UnaryOperation>
private lateinit var binaryOperations: Map<String, BinaryOperation>
private lateinit var parser: NestedExpressionsParser
@BeforeEach
fun setup() {
// todo add mocks
unaryOperations = mapOf(
"sin" to Sinus,
"-" to UnaryMinus,
"+" to UnaryPlus,
"!" to Factorial,
)
binaryOperations = mapOf(
"+" to BinaryPlus,
"-" to BinaryMinus,
"*" to Multiplication,
"/" to Division,
)
parser = NestedExpressionsParser(unaryOperations, binaryOperations)
}
@ParameterizedTest
@CsvSource(
@@ -19,6 +41,7 @@ class NestedExpressionsParserTest {
"-1", "+0", "-.5",
"-1*(-1)", "-1*-1",
"sin45", "sin(45)", "sin(45*2)",
"(5+1)!",
)
@DisplayName(("Parse correct expressions"))
fun parseSuccess(expression: String) {
@@ -31,6 +54,7 @@ class NestedExpressionsParserTest {
"-", "+",
"(", ")", "(()", ")(", "()",
"1++", "++1", "+1+",
"!", "+!", "!5",
)
@DisplayName("Fail incorrect expressions")
fun parseException(expression: String) {
@@ -1,30 +0,0 @@
package ru.darktale.calc
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
/*
class ParserImplTest {
private val parser = ParserImpl()
@ParameterizedTest(name = "input {0} expects {1}")
@CsvSource(
"123; [123]",
"12+13; [12, +, 13]",
"120*9; [120, *, 9]",
"-11; [-, 11]",
"(3+2)*8; [(, 3, +, 2, ), *, 8]",
"1e3; [1e3]",
"1e+3; [1e+3]",
"1e-3; [1e-3]",
"1e0; [1e0]",
"1e0-3; [1e0, -, 3]",
delimiter = ';'
)
fun parseSimpleExpression(expression: String, expectedResult: String) {
val result = parser.parse(expression)
assertEquals(expression, result.toString())
}
}
*/