I need to create an infinite sequence containing a subsequence of elements which repeats infinitely.
[1; 2; 3; 4; 1; 2; 3; 4; 1; 2; 3; 4; ...]
So I wrote this:
let l = [1; 2; 3; 4]
let s = seq { while true do yield! l }
Is there a standard way (function) to do this?
I think that your approach is good in this scenario. There is no built-in function to implement repetition, but if you need to repeat sequences often, you can define one yourself and make it available in the
Seqmodule:Then you can nicely write
Seq.repeat [ 1 .. 4 ], as ifrepeatwas a standard F# library function, because F# IntelliSense shows both functions from yourSeqmodule and from theSeqmodule as if they were defined in a single module.Aside from your implementation, you can also use recursive sequence expression, which is another quite common pattern when generating sequences. Using
whileis in some ways imperative (although you don’t need any state for simple repetitions) compared to functional recursion:This approach is better when you want to keep some state while generating. For example, generating all numbers
1 ..usingwhilewould not be so nice, because you’d need mutable state. Using recursion, you can write the same thing as: