sieve of eratosthenes

Standard ML

(* Sieve of Eratosthenes in Standard ML
 * Written by Rob Hoelz
 *
 * To run:
 *  $ sml sieve.sml
 *  - main <limit>
 *
 *)

datatype 'a lazyList =
    nullList | cons of 'a * (unit -> 'a lazyList)

fun seq first last =
  if first = last then
    cons(first, (fn () => nullList))
  else
    cons(first, (fn () => seq (first + 1) last))

fun lazyMap func nullList = []
  | lazyMap func (cons(h,t)) =
        (func h) :: (lazyMap func (t()))

fun filter _ nullList = nullList
  | filter pred (cons(h,t)) =
        if (pred h) then
          cons(h, (fn () => filter pred (t())))
        else
          filter pred (t())

fun primesAux _ nullList = nullList
  | primesAux limit (cons(h, t)) =
        if (h * h) <= limit then
          cons(h, (fn () => primesAux limit (filter (fn y => (y mod h) <> 0) (t()))))
        else
          cons(h, t)

fun primes limit = primesAux limit (seq 2 limit)

fun main limit = ((lazyMap (print o (fn x => (Int.toString x) ^ " ")) (primes limit)); print "\n")

back to Eratosthenes page

stats

It is Saturday May 17, 2008 10:50 am
This page served 604 times
This page last modified: April 14, 2008 11:28 am
Your IP address is: 38.103.63.17
You are browsing using: CCBot/1.0 (+http://www.commoncrawl.org/bot.html)
You are browsing from: United States.
badcomputer.org's uptime: 10:50:06 up 23 days, 11:32, 0 users, load average: 0.00, 0.00, 0.00

local

home | unix stuff | dir2ogg | sneetchalizer | wmainfo | q&d guide to permissions | q&d guide to tar and gzip | code | MS rant | browser shootout | linux & iAudio X5 | photos | music | programming poetry | sieve of Eratosthenes | plea | rain | suffer | archive | about | recipes | compaqr3000 | sitemap

search

Google

credits

hacker emblem

This page, and all pages on this site were created and are maintained by Darren Kirby using valid XHTML 1.0 and CSS, and are ©copyright 2002 - 2008. The Penguin image was created by Tukka, and is used by permission. Inspiration for the look of this site was provided by Eric A. Meyer's CSS gallery. This website runs on Gentoo Linux. It is served by Apache. PHP and MySQL hold together the backend.

advertisement