1 people like it.

Primes

Generates the Prime Number Sequence.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
open System
open System.Linq

let Primes =
  seq { 
        let PrimesSoFar = ref [2]
        let Primality =
          fun(primes : Int32 list, number) ->
            let IsComposite = primes.AsParallel().Any(fun x-> (number % x)=0)
            (not IsComposite , primes @ (if IsComposite then [] else [number;]))
        //  Generate the Prime Number Sequence
        yield 2
        for number in 3..2..Int32.MaxValue do
          let ( IsPrime, PrimeSeq ) =  Primality(!PrimesSoFar, number)
          if IsPrime then
            PrimesSoFar := PrimeSeq
            yield number
      }

// Example
//
// let PrimeSum = Prime.Take(1000).Sum()
namespace System
namespace System.Linq
val Primes : seq<int>

Full name: Script.Primes
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
val PrimesSoFar : int list ref
Multiple items
val ref : value:'T -> 'T ref

Full name: Microsoft.FSharp.Core.Operators.ref

--------------------
type 'T ref = Ref<'T>

Full name: Microsoft.FSharp.Core.ref<_>
val Primality : (Int32 list * Int32 -> bool * Int32 list)
val primes : Int32 list
type Int32 =
  struct
    member CompareTo : value:obj -> int + 1 overload
    member Equals : obj:obj -> bool + 1 overload
    member GetHashCode : unit -> int
    member GetTypeCode : unit -> TypeCode
    member ToString : unit -> string + 3 overloads
    static val MaxValue : int
    static val MinValue : int
    static member Parse : s:string -> int + 3 overloads
    static member TryParse : s:string * result:int -> bool + 1 overload
  end

Full name: System.Int32
type 'T list = List<'T>

Full name: Microsoft.FSharp.Collections.list<_>
val number : Int32
val IsComposite : bool
(extension) Collections.IEnumerable.AsParallel() : ParallelQuery
(extension) Collections.Generic.IEnumerable.AsParallel<'TSource>() : ParallelQuery<'TSource>
val x : Int32
val not : value:bool -> bool

Full name: Microsoft.FSharp.Core.Operators.not
val number : int
field int.MaxValue = 2147483647
val IsPrime : bool
val PrimeSeq : Int32 list
Raw view Test code New version

More information

Link:http://fssnip.net/f1
Posted:11 years ago
Author:AdamSpeight2008
Tags: mathematics , sequence , f#