File: sieve.dats

package info (click to toggle)
ats2-lang 0.4.2-4
  • links: PTS
  • area: main
  • in suites:
  • size: 40,524 kB
  • sloc: ansic: 389,898; makefile: 7,138; javascript: 1,852; lisp: 811; sh: 657; php: 573; python: 387; perl: 365
file content (100 lines) | stat: -rw-r--r-- 1,768 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//usr/bin/env myatscc "$0"; exit
(* ****** ****** *)
(*
//
// Implementing Erathosthene's sieve
//
// author: Hongwei Xi (November, 2006)
//
*)
(* ****** ****** *)
//
// HX-2012-11-25: ported to ATS/Postiats (typecheck)
// HX-2012-06-08: ported to ATS/Postiats (compilation)
//
(* ****** ****** *)
(*
##myatsccdef=\
patsopt --constraint-ignore --dynamic $1 | \
tcc -run -DATS_MEMALLOC_LIBC -I${PATSHOME} -I${PATSHOME}/ccomp/runtime -
*)
(* ****** ****** *)

staload INT = "prelude/DATS/integer.dats"

(* ****** ****** *)
//
// lazy list:
//
datatype llist = lcons of (intGte 2, () -<cloref1> llist)
//
#define :: lcons
//
(* ****** ****** *)

fun filter
  (p: intGte 2 -<cloref> bool, xs: llist): llist = let
  val+ x :: fxs = xs
in
  if p (x) then x :: (lam () =<cloref1> filter (p, fxs ()))
  else filter (p, fxs ())
end // end of [filter]

//

infix nmod
macdef nmod (x1, x2) = g1int_nmod<int_kind> (,(x1), ,(x2))

fun sieve (
  xs: llist
) : llist = let
  val+ x :: fxs = xs
in
  x :: (lam () => sieve (filter (lam (x') => (x' nmod x) != 0, fxs ())))
end // end of [sieve]

//

val
rec primes: llist = let
  fun aux (i: intGte 2): llist = i :: (lam () => aux (i + 1))
in
  sieve (aux 2)
end // end of [primes]

//

(* ****** ****** *)

fun print_ints
  (N: int, xs: llist): void =
(
if N > 0 then let
  val+ x :: fxs = xs
in
  print x; print ", ";
  print_ints (N-1, fxs ())
end else
  (print "..."; print_newline ())
) // end of [print_ints]

(* ****** ****** *)
//
implement
main (argc, argv) = let
//
val N =
(
if argc >= 2 then
  $extfcall (int, "atoi", argv[1]) else 100
) : int // end of [val]
//
val () = assertloc (N > 0)
//
in
  let val () = print_ints (N, primes) in 0(*normal*) end
end // end of [main]
//
(* ****** ****** *)

(* end of [sieve.dats] *)