且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

F#正确使用序列缓存

更新时间:2022-02-24 09:00:16

Seq.cache 缓存 IEnumerable< T> 实例,以便序列中的每个项目仅计算一次。不过,就您而言,您要缓存一个函数返回的序列,并且每次调用该函数时,都会得到一个 new 缓存序列,这对您没有任何好处。正如您所概述的那样,我认为缓存并不是解决问题的正确方法;

Seq.cache caches an IEnumerable<T> instance so that each item in the sequence is only calculated once. In your case, though, you're caching the sequence returned by a function, and each time you call the function you get a new cached sequence, which doesn't do you any good. I don't think caching is really the right approach to your problem as you've outlined it; instead you should probably look into memoization.

如果要定义质数小于 n 的函数,而不是定义该函数来定义素数的无限可数序列,那么缓存就更有意义了。看起来更像这样:

If instead of defining a function giving the primes less than n you want to define an infinite enumerable sequence of primes, then caching makes more sense. That would look more like this:

let rec upFrom i =
  seq { 
    yield i
    yield! upFrom (i+1)
  }

let rec primes =
  seq { 
    yield 2
    yield!
      upFrom 3 |>
      Seq.filter (fun p -> primes |> Seq.takeWhile (fun j -> j*j <= p) |> Seq.forall (fun j -> p % j <> 0))
  }
  |> Seq.cache

我没有将这种方法的性能与您的方法进行比较。

I haven't compared the performance of this method compared to yours.