aboutsummaryrefslogtreecommitdiff
path: root/examples/std_tour.zc
blob: 1ef33f3532044d2b926e874e29d6f0a8e1b2569d (plain) (blame)
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
namespace;
include rt, std;

// a tour of the standard library: one or two functions from each group, printing
// what they return. run it with: build/bin/zy < examples/std_tour.zc

int big(int x) { return x > 2; }
int dbl(int x) { return x * 2; }
int add(int a, int b) { return a + b; }

fn main() {
	// io: the terminal
	std.Io.print("io "); std.Io.put_n(7); std.Io.put_c(' '); std.Io.put_f(0.5); std.Io.nl();	// io 7 0.500000

	// text: char* strings, one character per word
	let buf[32];
	std.Text.itoa(0 - 42, buf); rt.put_s(buf); rt.put_c(10);				// -42
	rt.put_n(std.Text.find("needle in a haystack", "hay")); rt.put_c(10);	// 12

	// num: integer helpers
	rt.put_n(std.Num.gcd(84, 36)); rt.put_c(' ');							// 12
	rt.put_n(std.Num.pow(2, 10)); rt.put_c(10);								// 1024

	// host: the clock and the environment; this variable is not set
	rt.put_n(std.Host.now() > 0); rt.put_c(' ');							// 1
	let v[16];
	rt.put_n(std.Host.env("STD_TOUR_UNSET_VARIABLE", v, 16)); rt.put_c(10);	// -1

	// bytes: packed byte strings, from b"..." literals
	rt.put_n(std.Bytes.len(b"packed")); rt.put_c(' ');						// 6
	rt.put_n(std.Bytes.find(b"needle", b"ed")); rt.put_c(' ');				// 2
	rt.put_bs(std.Bytes.itoa(7)); rt.put_c(10);								// 7

	// arena: a region of words, handed out in pieces and freed all at once
	let a = std.arena(8);
	rt.put_n(std.Arena.alloc(a, 4) != 0); rt.put_c(' ');					// 1
	rt.put_n(std.Arena.alloc(a, 100) == 0); rt.put_c(10);					// 1
	std.Arena.reset(a);

	// buf: byte buffers from bnew
	let b = std.bnew(8);
	std.Buf.set(b, 0, 65); std.Buf.set(b, 1, 66);
	rt.put_n(std.Buf.length(b)); rt.put_c(' ');								// 2
	rt.put_c(std.Buf.get(b, 1)); rt.put_c(10);								// B

	// capture: send the output into a string instead of the terminal
	let out = std.capture.start();
	rt.put_n(42);
	std.capture.end(out);
	rt.put_s("captured: "); rt.put_s(out); rt.put_c(10);					// captured: 42

	// array algorithms: one function per step, applied to an array of words
	int[?] xs = rt.new(int[?], 0);
	push(xs, 1); push(xs, 3); push(xs, 5);
	rt.put_n(std.array_find(xs, 3)); rt.put_c(' ');							// 1
	rt.put_n(std.array_count(xs, big)); rt.put_c(' ');						// 2
	rt.put_n(std.array_reduce(xs, 0, add)); rt.put_c(10);					// 9
	let doubled = std.array_map(xs, dbl);
	rt.put_n(doubled[2]); rt.put_c(10);										// 10

	// the command line: std.libinit() fills argc before main runs
	rt.put_n(std.argc > 0); rt.put_c(10);									// 1
	return 0;
}