我想在scala中编写一个memoize函数,无论函数对象是什么,它都可以应用于任何函数对象.我希望以一种允许我使用memoize的单个实现的方式这样做.我对语法很灵活,但理想情况下,memoize出现在非常接近函数声明的地方,而不是函数之后.我还想避免首先声明原始函数,然后再为memoized版本声明第二个声明.
所以一些理想的语法可能是这样的:
def slowFunction(<some args left intentionally vague>) = memoize {
// the original implementation of slow function
}
Run Code Online (Sandbox Code Playgroud)
甚至这是可以接受的:
def slowFUnction = memoize { <some args left intentionally vague> => {
// the original implementation of slow function
}}
Run Code Online (Sandbox Code Playgroud)
我已经看到了这样做的方法,其中必须为每个arity函数重新定义memoize,但我想避免这种方法.原因是我需要实现几十个类似于memoize的函数(即其他装饰器),要求每个arity函数都要复制每个函数太多了.
一种做memoize的方法确实需要你重复memoize声明(所以它没有用)是什么类型用于在Scala中存储内存中的可变数据表?.
最近,Lee Baldwin展示了如何编写一个通用的,可变参数memoize函数.我认为返回一个只需要一个参数的简单函数会更好.这是我的全部伪造尝试:
local function memoize(f)
local cache = {}
if select('#', ...) == 1 then
return function (x)
if cache[x] then
return cache[x]
else
local y = f(x)
cache[x] = y
return y
end
end
else
return function (...)
local al = varg_tostring(...)
if cache[al] then
return cache[al]
else
local y = f(...)
cache[al] = y
return y
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
显然,select('#', ...)
在这种情况下失败并且无论如何都不会真正做我想做的事情.有没有办法告诉内部memoize有多少参数f期望?
如果你肯定知道,"不"是一个很好的答案.使用两个单独的memoize函数并不是什么大问题.
我有许多操作字符串的函数来从这些字符串中提取有趣的属性。其中许多函数调用的一个特定函数非常昂贵,最终会生成一个值表:
local function expensive(s)
local t = nil
return function()
if not t then
t = {}
-- some expensive operations with s which add items to t
end
return t
end
end
local function fn1(s)
local t = expensive(s)
-- some other fast operations using t and s
end
local function fn2(s)
local t = expensive(s)
-- some other fast operations using t and s
end
local s1, s2 = 'a', 'b'
fn1(s1) -- should create the 't' table …
Run Code Online (Sandbox Code Playgroud) 如何用给定的语言编写以下语句?
a(0) = 1
a_(n+1) = 1 - 1 / ( a_n + 3)
Run Code Online (Sandbox Code Playgroud)
我需要找到的最小值n
时a_n -> 0.732050...
.
我在Mathematica的尝试
a[(x+1)_] = 1 - 1/(a[x_] + 3)
Run Code Online (Sandbox Code Playgroud)
问题显然在于此a[(x+1)_]
.但是,我不知道如何在Mathematica中迭代地完成它.