El mié, 24 de mar. de 2021 a la(s) 16:47, Hans Hagen (j.hagen@xs4all.nl) escribió:
On 3/24/2021 6:33 PM, Jairo A. del Rio wrote:
Hi, Hans. Here's my (miserably failing) attempt:
\definedataset[nicedata]
\starttext
\startluacode
local name = "nicedata"
-- For exposition only
local function dofactorial(n)
local function inner(c,m)
if m<2 then return c end
return inner(c*m, m-1)
end
return inner(1,n)
end
local function factorial(n)
local stringn = tostring(n)
if job.datasets.collected[name] then
return job.datasets.collected[name].factorial[stringn]
else
local mydata = {[stringn] = tostring(dofactorial(n))}
job.datasets.setdata{
name = name,
tag = "factorial",
data = mydata
}
return mydata[stringn]
end
end
interfaces.implement{
name = "factorial",
public = true,
arguments = {"string"},
actions = {tonumber, factorial, context}
}
\stopluacode
\factorial{7}
\stoptext
What happens is that, in each run, both the first and the second conditions are met, so the compilation is twice as slow, the opposite result of what I meant to do. How do I fix that?
\definedataset[nicedata]
\starttext
\startluacode
local function dofactorial(n) local function inner(c,m) if m < 2 then return c else return inner(c*m, m-1) end end return inner(1,n) end
local function factorial(n) local data = job.datasets.getdata("factorials","list") if not data then data = { } end local f = data[n] if not f then f = dofactorial(n) data[n] = f end job.datasets.setdata { name = "factorials", tag = "list", data = data } return f end
interfaces.implement{ name = "factorial", public = true, arguments = { "integer" }, actions = { factorial, context } }
\stopluacode
\dorecurse {20} { \factorial #1 \relax }
\stoptext
It does exactly what I need. It's good to know datasets can be directly generated, too. Thank you a lot!
but you probably don't gain much as these factorials are not that slow (if you use them many times in a document you can just cache them)
It was only a toy example. I intend to work with way larger numbers. :)
Hans
----------------------------------------------------------------- Hans Hagen | PRAGMA ADE Ridderstraat 27 | 8061 GH Hasselt | The Netherlands tel: 038 477 53 69 | www.pragma-ade.nl | www.pragma-pod.nl -----------------------------------------------------------------
Best regards, Jairo