Learning F# - printing prime numbers
algorithm, f#, primes
Solution
Here is a simple implementation of the Sieve of Eratosthenes in F#:
let rec sieve = function
| (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ]
| [] -> []
let primes = sieve [2..50]
printfn "%A" primes // [2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47]
This implementation won't work for very large lists but it illustrates the elegance of a functional solution.
Problem
Yesterday I started looking at F# during some spare time. I thought I would start with the standard problem of printing out all the prime numbers up to 100. Heres what I came up with... ``` #light open System let mutable divisable = false let mutable j = 2 for i = 2 to 100 do j <- 2 while j < i do if i % j = 0 then divisable <- true j <- j + 1 if divisable = false then Console.WriteLine(i) divisable <- false ``` The thing is I feel like I have approached this from a C/C# perspective and not embraced the true functional language aspect. I was wondering what other people could come up with - and whether anyone has any tips/pointers/suggestions. I feel good F# content is hard to come by on the web at the moment, and the last functional language I touched was HOPE about 5 years ago in university.