aboutsummaryrefslogtreecommitdiff
path: root/example/prime/prime.cc
blob: cd119d8b0fc9509ba77049fb754695ba64ae2398 (plain)
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
#include <iostream>

#include "type.h"
#include "operation/math.h"
#include "function/apply.h"

#include "list/list.h"
#include "list/generator/iota.h"
#include "list/operation/higher/remove.h"

#include "runtime/list/for_each.h"

// (define candidates (iota 1000 2 1))
using candidates = tav::Iota<tav::Size<1000>, tav::Int<2>, tav::Int<1>>;

// (define (isMultipleOf candidate base) (= (modulo candidate base) 0))
template <
	typename Candidate,
	typename Base
>
using isMultipleOf = tav::IsEqualValue<
	tav::Modulo<Candidate, Base>,
	tav::Int<0>
>;

// (define (removeMultiplesOf candidates base)
//   (remove (lambda (x) (isMultipleOf x base))
//           candidates))
template <
	typename Candidates,
	typename Base
>
using removeMultiplesOf = tav::Remove<
	tav::Apply<isMultipleOf, tav::_0, Base>::template function,
	Candidates
>;

// (define (sieve candidates)
//   (cond ((null-list? candidates) (list))
//         (else                    (cons (car candidates)
//                                        (sieve (removeMultiplesOf (cdr candidates)
//                                                                  (car candidates)))))))
template <typename Candidates>
struct Sieve {
	typedef tav::Cons<
		tav::Head<Candidates>,
		tav::Eval<Sieve<
			removeMultiplesOf<
				tav::Tail<Candidates>,
				tav::Head<Candidates>
			>
		>>
	> type;
};

template <>
struct Sieve<void> {
	typedef void type;
};

// (define primes (sieve candidates))
using primes = tav::Eval<Sieve<candidates>>;

int main(int, char **) {
	tav::runtime::for_each<primes>([](const int x) {
		std::cout << x << std::endl;
	});
}