- 论坛徽章:
- 2
|
补充一下,JS与Clojure的named function expression的name的作用域是在被调用函数(callee)中当中而非调用者(caller)中。
ecmascript5:
- // caller scope
- [1,2,3].map(function f(x) { /*callee scope*/return x>1? x*f(x-1): 1 }) // [1,2,6]
- // caller scope
复制代码 Clojure同理:
- // caller scope
- (map (fn f [x] "callee scope" (if (> x 1) (* x (f (- x 1))) 1)) '(1 2 3)) ; (1 2 6)
- // caller scope
复制代码 前面提到的:http://codereview.stackexchange. ... d-under-vistual-stu
可以达到这样的效果:
- // caller scope
- transform(beg, end, dst,
- getFix([](std::function<int (int)> f) -> std::function<int (int)>{
- // callee scope
- return [f](int n)->int { if(n==0) return 1; else return n * f(n-1); };
- }) );
- // caller scope
复制代码 注意getFix的参数, 不是阶乘本身, 而是一个返回函数的函数。 返回的函数中才包含了阶乘计算。通过这样绕过生命周期问题。
再通过loopfunc_t绕过f(f)的类型问题。
最后用变长模板参数解决签名问题。
PS: 实践中最好不要这样玩,这已经超出C++的能力了。
实践中,让函数名在caller scope但又不是top-level的机制在C++98就存在了, 就是inner class。
|
|