A better way to write this in F# would be

1
2
3
let isqrt n = n |> float |> sqrt |> int

let isPrime x = Seq.nonempty { for y in 2..isqrt x when x % y = 0 -> y } |> not

With

1
Seq.nonempty

computation will stop after the first factor is found making the number composite, whereas with Seq.length all factors are unnecessarily computed.

The match and the especially the if were kind of unecessary too.

Using List instead of Seq would not be better in this code because since Seq is lazy the list of factors is only evaluated as needed. Whereas List is strict so even using

1
List.nonempty

the entire list of factors is necessarily evaluated.

Oh, and I made a small algorithmic improvement of iterating to sqrt x instead of x-1.

And good luck with learning functional programming and F#!

By on 2/3/2008 7:27 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper