[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: how to make anydimensional array?
- From: Luis Carvalho <carvalho@...>
- Date: Sun, 23 Apr 2006 15:04:39 -0400
> I'd like to ask what is the most "luaic" implementation of polynomials
> in n variables
>
> I was naturally thinking of a table t, with t.dim equal to n, and (say)
> t[{k1,k2,..,kn}] equal to the coefficient of the polynomial in front
> of (x1^k1 * x2^k2 * .. *xn^kn)
> (the 'default value' of the table would not be nil, but rather 0, and
> one would implement operations with polynomials using a metatable of
> t).
What about:
<poly.lua>
local setmetatable = setmetatable
local type = type
local print = print
module'poly'
local poly_mt = {
__index = function(o, k) return 0 end,
__call = function(o, l)
local e = o
for i=1,o.dim do e=e[l[i]] end
return e
end
}
new = function(dim, degree)
if dim<=1 then
return setmetatable({dim=dim, degree=degree}, poly_mt)
else
local p = {dim=dim, degree=degree}
for i=0,degree do p[i] = new(dim-1, degree) end
return setmetatable(p, poly_mt)
end
end
</poly.lua>
$ lua
Lua 5.1 Copyright (C) 1994-2006 Lua.org, PUC-Rio
> require'poly'
> p = poly.new(3,3)
> p[1][2][3] = 2
> = p[1][2][3]
2
> = p{1,2,3}
2
> = p[1]{2,3}
2
> = p{1,1,0}
0
The hierarchical structure in poly is meant to make it easier to implement
evaluations (Horner's scheme, for example) or operations. Depending on your
needs thaty might not be necessary, that is, you can stick to regular
tables.
Cheers,
luis.
--
A mathematician is a device for turning coffee into theorems.
-- P. Erdos
--
Luis Carvalho
Applied Math PhD Student - Brown University
PGP Key: E820854A <carvalho@dam.brown.edu>