I'm getting acquainted with F# by going over Project Euler and solving some of the problems. Many of the early problems consist of prime numbers. After looking around I came up with the following solution:
let primesL =
let rec prim n sofar =
seq { if (sofar |> List.forall (fun i->n%i <>0L)) then
yield n
yield! prim (n+1L) (n::sofar)
else
yield! prim (n+1L) sofar }
prim 2L []
This works well, but then I generate all the prime numbers up to 2000000:
let smallPrimes = primesL |> Seq.takeWhile (fun n->n<=2000000)
This takes ages. It's quite obvious something is done in O(N^2) or worst.
I know I can write an imperative version and implement a sieve of some sort, but I want to stick to functional code. If I wanted imperative, I would have stayed with C#.
What am I missing?