Help me to refactor this F# code to tail recursion

Posted by Kev on Stack Overflow See other posts from Stack Overflow or by Kev
Published on 2010-06-04T10:25:27Z Indexed on 2010/06/05 10:32 UTC
Read the original article Hit count: 277

Filed under:

I write some code to learning F#. Here is a example:

let nextPrime list=
    let rec loop n=
        match n with
        | _ when (list |> List.filter (fun x -> x <= ( n |> double |> sqrt |> int)) |> List.forall (fun x -> n % x <> 0)) -> n
        | _ -> loop (n+1)
    loop (List.max list + 1)

let rec findPrimes num=
    match num with
    | 1 -> [2]
    | n -> 
        let temp = findPrimes <| n-1
        (nextPrime temp ) :: temp

//find 10 primes
findPrimes 10 |> printfn "%A"

I'm very happy that it just works!

I'm totally beginner to recursion

Recursion is a wonderful thing.

I think findPrimes is not efficient.

Someone help me to refactor findPrimes to tail recursion if possible?

BTW, is there some more efficient way to find first n primes?

© Stack Overflow or respective owner

Related posts about F#