Debian Codegraph @

texmf-dist/tex/lualatex/luacas/test/luacas-parser.lua

raw
1 -- Rudimentary parser for making the CAS easier to use. Essentially just wraps SymbolExpression() around symbols and Integer() around integers.
2
3
4 local luacas = require("luacas_init")
5 luacas:initglobalmodule("core")
6 luacas:initglobalmodule("algebra")
7 luacas:initglobalmodule("calculus")
8
9 -- Splits a string on a seperator.
10 function split(str, sep)
11 local t={}
12 for match in string.gmatch(str, "([^".. sep .."]+)") do
13 t[#t+1] = match
14 end
15 return t
16 end
17
18 -- Displays an expression. For use in the parser.
19 function disp(expression, inline, simple)
20 if type(expression) ~= "table" then
21 tex.print(tostring(expression))
22 elseif expression.autosimplify then
23 if inline then
24 if simple then
25 tex.print('$' .. expression:autosimplify():tolatex() .. '$')
26 else
27 tex.print('$' .. expression:tolatex() .. '$')
28 end
29 else
30 if simple then
31 tex.print('\\[' .. expression:autosimplify():tolatex() .. '\\]')
32 else
33 tex.print('\\[' .. expression:tolatex() .. '\\]')
34 end
35 end
36 else
37 tex.print(tostring(expression))
38 end
39 end
40
41 -- Displays an expression. For use in the parser.
42 function displua(expression)
43 if type(expression) ~= "table" then
44 print(tostring(expression))
45 elseif expression.autosimplify then
46 print(expression:autosimplify():tolatex())
47 else
48 print(tostring(expression))
49 end
50 end
51
52 function vars(...)
53 for _, string in ipairs(table.pack(...)) do
54 if string ~= "_" then
55 _G[string] = SymbolExpression(string)
56 end
57 end
58 end
59
60 function clearvars()
61 for index, value in pairs(_G) do
62 if type(value) == "table" and value.type and value:type() == SymbolExpression then
63 _G[index] = nil
64 end
65 end
66 end
67
68 function range(a, b, step)
69 if not b then
70 b = a
71 a = Integer.one()
72 end
73 step = step or Integer.one()
74 local f =
75 step > Integer.zero() and
76 function(_, lastvalue)
77 local nextvalue = lastvalue + step
78 if nextvalue <= b then return nextvalue end
79 end or
80 step < Integer.zero() and
81 function(_, lastvalue)
82 local nextvalue = lastvalue + step
83 if nextvalue >= b then return nextvalue end
84 end or
85 function(_, lastvalue) return lastvalue end
86 return f, nil, a - step
87 end
88
89 function factor(exp,squarefrei)
90 if exp:type() == Integer then
91 return exp:primefactorization()
92 end
93 if exp:type() == PolynomialRing then
94 if not squarefrei then
95 return exp:factor()
96 else
97 if exp.ring == Integer.getring() or Rational.getring() then
98 return exp:squarefreefactorization()
99 end
100 if exp.ring == IntegerModN.getring() then
101 return exp:modularsquarefreefactorization()
102 end
103 return exp:factor()
104 end
105 end
106 return exp:autosimplify():factor()
107 end
108
109 function expand(exp)
110 return exp:autosimplify():expand()
111 end
112
113 function simplify(exp)
114 return exp:simplify()
115 end
116
117 function exp(x)
118 return e^x
119 end
120
121 function substitute(tbl,expr)
122 return expr:substitute(tbl)
123 end
124
125 function roots(expression)
126 poly,ispoly = topoly(expression)
127 if ispoly then
128 return poly:roots()
129 end
130 return RootExpression(expression)
131 end
132
133 function combine(expr)
134 return expr:combine()
135 end
136
137 function Mod(f,n)
138 if f:type() == Integer then
139 return IntegerModN(f,n)
140 end
141 if f:type() == PolynomialRing and f.ring == Integer.getring() then
142 local coeffs = {}
143 for i=0,f.degree:asnumber() do
144 coeffs[i] = IntegerModN(f.coefficients[i],n)
145 end
146 return PolynomialRing(coeffs,f.symbol,f.degree)
147 end
148 end
149
150 function Poly(coefficients,symbol,degree)
151 local variable = symbol or 'x'
152 return PolynomialRing:new(coefficients,variable,degree)
153 end
154
155 function topoly(a)
156 a = a:expand():autosimplify()
157 return a:topolynomial()
158 end
159
160 function gcd(a,b)
161 if a:type() == Integer and b:type() == Integer then
162 return Integer.gcd(a,b)
163 end
164 if a:type() == PolynomialRing and b:type() == PolynomialRing then
165 return PolynomialRing.gcd(a,b)
166 end
167 end
168
169 function gcdext(a,b)
170 if a:type() == Integer and b:type() == Integer then
171 return Integer.extendedgcd(a,b)
172 end
173 A, ATF = topoly(a)
174 B, BTF = topoly(b)
175 if ATF and BTF then
176 return PolynomialRing.extendedgcd(A,B)
177 end
178 return nil,nil,nil
179 end
180
181 function parfrac(f,g,ffactor)
182 local f,check1 = topoly(f)
183 local g,check2 = topoly(g)
184 if check1 and check2 then
185 if f.degree >= g.degree then
186 local q,r
187 q,r = f:divremainder(g)
188 return q + PolynomialRing.partialfractions(r,g,ffactor)
189 else
190 return PolynomialRing.partialfractions(f,g,ffactor)
191 end
192 else
193 return f/g
194 end
195 end
196
197 function factorial(a)
198 return FactorialExpression(a)
199 end
200
201 -- Constants for the CAS. We may not want these in Lua itself, but in the latex end the user probably expects them.
202 e = E
203 pi = PI
204 -- sqrt = SQRT
205 ln = LN
206 log = LOG
207 int = INT
208 sin = SIN
209 cos = COS
210 tan = TAN
211 csc = CSC
212 sec = SEC
213 cot = COT
214 arcsin = ARCSIN
215 arccos = ARCCOS
216 arctan = ARCTAN
217 arccsc = ARCCSC
218 arcsec = ARCSEC
219 arccot = ARCCOT
220 abs = ABS
221
222 function ZTable(t)
223 t = t or {}
224 return setmetatable(t, JoinTables(getmetatable(t),
225 {__index = function (t, k)
226 if type(k) == "table" and k.type and k:type() == Integer then
227 return rawget(t, k:asnumber())
228 else
229 return rawget(t, k)
230 end
231 end,
232 __newindex = function (t, k, v)
233 if type(k) == "table" and k.type and k:type() == Integer then
234 rawset(t, k:asnumber(), v)
235 else
236 rawset(t, k, v)
237 end
238 end}))
239 end
240
241 function RR(n)
242 if type(n) == "number" then
243 return n
244 end
245
246 if type(n) == "string" then
247 return tonumber(n)
248 end
249
250 if type(n) == "table" and n.asnumber then
251 return n:asnumber()
252 end
253
254 error("Could not convert to a real number.")
255 end
256
257 function ZZ(n)
258 if type(n) == "table" and n.type and n:type() == Rational then
259 return n.numerator // n.denominator
260 end
261 return Integer(n)
262 end
263
264 function QQ(n)
265 if type(n) == "table" then
266 return n
267 end
268
269 if type(n) == "number" then
270 n = tostring(n)
271 end
272
273 if type(n) == "string" then
274 local parts = split(n, "%.")
275 if #parts == 1 then
276 return Integer(parts[1])
277 else
278 return Integer(parts[1])..Integer(parts[2])
279 end
280 end
281
282 error("Could not convert to a rational number.")
283 end
284
285 --- Parses raw input into Lua code and executes it.
286 --- @param input string
287 function CASparse(input)
288
289 -- First, we replace any occurrence of a decimal with the appropriate fraction.
290
291 local str = string.gsub(input,"%d+%.%d+", function(s)
292 local ints = split(s,"%.")
293 return "("..ints[1]..ints[2].." / 10^" .. tostring(string.len(ints[2])) .. ")"
294 end)
295
296 -- Next, we replace any occurance of a number with an integer or rational version of itself.
297
298 str = string.gsub(str, ".?[0-9]+", function (s)
299 -- Here, we are part of an identifier, so we don't replace anything
300 if string.match(string.sub(s, 1, 1), "[A-Z]") or string.match(string.sub(s, 1, 1), "[a-z]") or string.match(string.sub(s, 1, 1), "_") then
301 return
302 end
303
304 if string.match(string.sub(s, 1, 1), "[0-9]") then
305 return "Integer('" .. s .. "')"
306 end
307
308 return string.sub(s, 1, 1) .. "Integer('" .. string.sub(s, 2, #s) .. "')"
309 end)
310
311 --------------------------
312 -- HERE COMES THE JANK. --
313 --------------------------
314 -- The JANK may not actually be doing anything now. But for the sake of posterity...
315 -- Replaces each instance of a decimal with .., so we can use integer metatables to convert it into a rational properly.
316 str = string.gsub(str, "Integer%('[0-9]+'%)%.Integer%('[0-9]+'%)", function (s)
317 local ints = split(s, "%.")
318 return "("..ints[1] .. ".." .. ints[2] .. ")"
319 end)
320 str = string.gsub(str, ".?%.Integer%('[0-9]+'%)", function (s)
321 if string.sub(s, 1, 2) == ".." then
322 return
323 end
324 return string.sub(s, 1, 1) .. "Integer('0')." .. string.sub(s, 2, #s)
325 end)
326
327 local exe, err = load(str .. "\n return true")
328 if exe then
329 exe()
330 else
331 print(err)
332 end
333 end