実現したいこと
C#のLinqによるリスト操作において、参照するまでは評価されず、一度評価したものについては二度目の評価を行わせないようにしたいです。
例えば次のようなコードにおいて、メモ化されていればMapメソッドの実行回数は10回となりますが、メモ化されていないがために15回実行されてしまいます。
cs
1using System; 2using System.Linq; 3using System.Collections.Generic; 4 5public class Sample { 6 7 private static int _counter = 0; 8 9 public static void Main() { 10 var xs = GetList(); 11 var mapped = xs.Select(Map); 12 Console.WriteLine(mapped.Take(5).Count()); 13 foreach (var x in mapped.Take(10)) { 14 Console.WriteLine(x); 15 } 16 Console.WriteLine($"about counter: expected=10, actual={_counter}"); //=> about counter: expected=10, actual=15 17 } 18 19 private static IEnumerable<int> GetList() { 20 var n = 0; 21 while (true) { 22 yield return n++; 23 } 24 } 25 26 private static int Map(int x) { 27 _counter++; 28 return x; 29 } 30}
これを、遅延評価的な挙動を維持したまま適切にメモ化するにはどうすればよいでしょうか?

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2024/07/27 05:04
2024/07/27 05:36
2024/07/28 10:39 編集
2024/07/30 10:07