I'm trying to cache the result of an infinite sequence of triangle numbers.
let triCalc n = (n*(n+1))/2
let triNumC = 0 |> Seq.unfold (fun n -> Some((triCalc n, n+1))) |> Seq.cache
However, when I try to cache it doesn't seem to work as I expect
let x = Seq.take 4 (triNumC)
let y = Seq.take 4 (triNumC)
printf "%A" x
printf "%A" y
This prints
seq [0; 1; 3; 6]seq [0; 1; 3; 6]
Am I caching incorrectly? Shouldn't the second sequence printed be a continuation of the first? I am not quite sure how to progress.
If you want the continuation you need to skip. The sequence remains the same
let y = triNumC
|> Seq.skip 4
|> Seq.take 4
Caching is fine. The benefit of caching is that when calculating y is that starts from the 5th term onwards since the first 4 are already cached.