McMuttons
McMuttons

Reputation: 891

How to generate a sequence based on a different sequence

I have this sequence:

let wheel235 = [4; 2; 4; 2; 4; 6; 2; 6]
let wheel = seq { while true yield! wheel235 }

I'd like to build a second sequence that starts on a particular number, and each following number in that sequence is the previous number with the next item in the wheel sequence added to it. So if I started the sequence at 5, I would have 5, 9, 11, 15, 17, 21, 27, etc...

I can't quite wrap my head around how to do it.

For those familiar with it, it's obviously a number wheel for prime number generation, but I don't think knowing that would matter much for the answer. :)

Upvotes: 1

Views: 123

Answers (2)

LukeH
LukeH

Reputation: 269348

You can do it with Seq.scan:

let wheel235 = [4; 2; 4; 2; 4; 6; 2; 6]
let wheel = seq { while true do yield! wheel235 }

let result = wheel |> Seq.scan (+) 5

# result will be 5, 9, 11, 15, 17, 21, 27, etc

Upvotes: 7

svick
svick

Reputation: 244767

I think that if you want to do this just using a sequence expression, you would need to use a mutable ref cell:

let wheel = seq { 
    let result = ref 5
    yield !result
    while true do
        for x in wheel235 do
            result := !result + x
            yield !result
    }

But I think a better way would be to combine your code to repeat wheel235 inifitely (after fixing the syntax error) with Seq.scan (as suggested bu LukeH):

let wheel = seq { while true do yield! wheel235 } |> Seq.scan (+) 5

Upvotes: 3

Related Questions