是否有本機語言支持的懶惰評估語法?類似於斯卡拉的lazy val
。如何在Dart中進行懶惰評估?
我已經通過the docs,找不到任何東西。關於「懶惰地加載一個圖書館」只有一章,但這不是我所要求的。
基於這項研究,我傾向於相信(請糾正我,如果我錯了),目前沒有這樣的事情。但是,也許你知道任何計劃或功能要求將提供功能?或者也許它被Dart團隊考慮並拒絕了?
如果確實沒有本地支持,那麼實現懶惰評估的最佳實踐(最好的語法)是什麼?一個例子,將不勝感激。
編輯:
,我尋找的功能的好處大多是一樣的,在其他語言的實現:Scala's lazy val
或C#'s Lazy<T>
或Hack's __Memorize attribute:
- 簡潔的語法
- 延遲計算,直到需要該值
- 緩存結果(需要個懶惰)
- 不破純功能範式(下面說明)
一個簡單的例子:
class Fibonacci {
final int n;
int _res = null;
int get result {
if (null == _res) {
_res = _compute(this.n);
}
return _res;
}
Fibonacci(this.n);
int _compute(n) {
// ...
}
}
main(List<String> args) async {
print(new Fibonacci(5).result);
print(new Fibonacci(9).result);
}
該吸氣劑是非常冗長,並具有重複的代碼。 此外,我不能使構造函數const
,因爲緩存變量_res
必須按需計算。我想如果我有一個類似於Scala的lazy
特性,那麼我也會有一個持久構造函數的語言支持。這是由於事實,懶惰評估_res
是referentially transparent和would not be in the way。
class Fibonacci {
final int n;
int lazy result => _compute(this.n);
const Fibonacci(this.n); // notice the `const`
int _compute(n) {
// ...
}
}
main(List<String> args) async {
// now these makes more sense:
print(const Fibonacci(5).result);
print(const Fibonacci(9).result);
}
可以喲請提供一個具體的例子,說明你想用惰性評估來完成什麼。就我所知,沒有特別的語言支持,也沒有關於它的討論。列表,地圖...上的很多方法都是懶惰評估的。例如'map()','fold()','reduce()',...參見http://stackoverflow.com/questions/20491777/dart-fold-vs-reduce。也許只是關閉做你想做的事。 –