The traditional functional idiom for primes is something like

1
2
3
4
5
6
let primes = 
  let rec prim s = 
    { let h = Seq.hd s
       -> h 
       ->> prim {for i in s when i%h<>0 -> i} } in
  Seq.init_infinite ((+)2) |> prim

though the current syntax for sequence expressions is not as beautiful as it could be.

By on 11/24/2007 2:13 PM ()

It's recommended you use yield/yield! instead of "->" and "->>" in sequence expressions of any real size.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
 

#light
let primes = 
  let rec prim n (sofar: list<int>) = 
      seq { if (sofar |> List.for_all (fun i -> n%i <> 0)) then 
                yield n
                yield! prim (n+1) (n :: sofar) 
            else 
                yield! prim (n+1) sofar }
  prim 2 []

Or using a mutable buffer to hold the generated primes:

1
2
3
4
5
6
7
8
9
10
11
12
13
 

#light
let primes2 = 
  let sofar = new ResizeArray<_>()
  let rec prim n  = 
      seq { if (sofar |> ResizeArray.for_all (fun i -> n%i <> 0)) then 
                do sofar.Add(n)
                yield n
            yield! prim (n+1) }
  prim 2

Kind regards

don

By on 11/24/2007 11:08 PM ()

Don, what *is* <i>yield!<i>, exactly? Is -> to <i>yield<i> as ->> is to <i>yield!<i>? Apropos, I saw <i>return!<i> for the first time today, on your blog. Could I ask what it means? Sorry if this is an elementary question; I'm struggling with f.p.

By on 12/10/2007 8:33 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