Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,40 @@
// version 1.1.2
fun rpnCalculate(expr: String) {
if (expr.isEmpty()) throw IllegalArgumentException("Expresssion cannot be empty")
println("For expression = $expr\n")
println("Token Action Stack")
val tokens = expr.split(' ').filter { it != "" }
val stack = mutableListOf<Double>()
for (token in tokens) {
val d = token.toDoubleOrNull()
if (d != null) {
stack.add(d)
println(" $d Push num onto top of stack $stack")
}
else if ((token.length > 1) || (token !in "+-*/^")) {
throw IllegalArgumentException("$token is not a valid token")
}
else if (stack.size < 2) {
throw IllegalArgumentException("Stack contains too few operands")
}
else {
val d1 = stack.removeAt(stack.lastIndex)
val d2 = stack.removeAt(stack.lastIndex)
stack.add(when (token) {
"+" -> d2 + d1
"-" -> d2 - d1
"*" -> d2 * d1
"/" -> d2 / d1
else -> Math.pow(d2, d1)
})
println(" $token Apply op to top of stack $stack")
}
}
println("\nThe final value is ${stack[0]}")
}
fun main(args: Array<String>) {
val expr = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
rpnCalculate(expr)
}

View file

@ -0,0 +1,79 @@
{calc 3 4 2 * 1 5 - 2 3 pow pow / +}
->
3:
4: 3
2: 4 3
*: 2 4 3
1: 8 3
5: 1 8 3
-: 5 1 8 3
2: -4 8 3
3: 2 -4 8 3
pow: 3 2 -4 8 3
pow: 8 -4 8 3
/: 65536 8 3
+: 0.0001220703125 3
-> 3.0001220703125
where
{def calc
{def calc.r
{lambda {:x :s}
{if {empty? :x}
then -> {car :s}
else {car :x}: {disp :s}{br}
{calc.r {cdr :x}
{if {unop? {car :x}}
then {cons {{car :x} {car :s}} {cdr :s}}
else {if {binop? {car :x}}
then {cons {{car :x} {car {cdr :s}} {car :s}} {cdr {cdr :s}}}
else {cons {car :x} :s}} }}}}}
{lambda {:s}
{calc.r {list :s} nil}}}
using the unop? & binop? functions to test unary and binary operators
{def unop?
{lambda {:op}
{or {W.equal? :op sqrt} // n sqrt sqrt(n)
{W.equal? :op exp} // n exp exp(n)
{W.equal? :op log} // n log log(n)
{W.equal? :op cos} // n cos cos(n)
... and so // ...
}}}
{def binop?
{lambda {:op}
{or {W.equal? :op +} // m n + m+n
{W.equal? :op -} // m n - m-n
{W.equal? :op *} // m n * m*n
{W.equal? :op /} // m n / m/n
{W.equal? :op %} // m n % m%n
{W.equal? :op pow} // m n pow m^n
... and so on // ...
}}}
and the list, empty? and disp functions to create
a list from a string, test its emptynes and display it.
{def list
{lambda {:s}
{if {W.empty? {S.rest :s}}
then {cons {S.first :s} nil}
else {cons {S.first :s} {list {S.rest :s}}}}}}
{def empty?
{lambda {:x}
{W.equal? :x nil}}}
{def disp
{lambda {:l}
{if {empty? :l}
then
else {car :l} {disp {cdr :l}}}}}
Note that everything is exclusively built on 5 lambdatalk primitives:
- "cons, car, cdr", to create lists,
- "W.equal?" which test the equality between two words,
- and the "or" boolean function.