harec

[hare] Hare compiler, written in C11 for POSIX OSs
Log | Files | Refs | README | LICENSE

14-switch.ha (1156B)


      1 fn basics() void = {
      2 	let cases = [[0, 1], [1, 3], [10, 20], [11, 21], [12, 22], [13, 13]];
      3 	for (let i = 0z; i < len(cases); i += 1) {
      4 		let x = cases[i][0];
      5 		let y: int = switch (x) {
      6 		case 0 =>
      7 			yield x + 1;
      8 		case 1 =>
      9 			yield x + 2;
     10 		case 10, 11, 12 =>
     11 			yield x + 10;
     12 		case =>
     13 			yield x;
     14 		};
     15 		assert(y == cases[i][1]);
     16 	};
     17 };
     18 
     19 fn termination() void = {
     20 	let x = 42;
     21 	let y: int = switch (x) {
     22 	case 42 =>
     23 		yield 1337;
     24 	case 24 =>
     25 		abort();
     26 	case =>
     27 		abort();
     28 	};
     29 	assert(y == 1337);
     30 };
     31 
     32 fn tagged_result() void = {
     33 	let x = 42;
     34 	let y: (int | uint) = switch (x) {
     35 	case 42 =>
     36 		yield 1337i;
     37 	case =>
     38 		yield 1337u;
     39 	};
     40 	assert(y is int);
     41 
     42 	x = 24;
     43 	y = switch (x) {
     44 	case 42 =>
     45 		yield 1337i;
     46 	case =>
     47 		yield 1337u;
     48 	};
     49 	assert(y is uint);
     50 };
     51 
     52 fn str_switching() void = {
     53 	let result = switch ("hare") {
     54 	case "world" =>
     55 		abort();
     56 	case "hare" =>
     57 		yield true;
     58 	case =>
     59 		abort();
     60 	};
     61 	assert(result == true);
     62 };
     63 
     64 fn binding() void = {
     65 	switch (1) {
     66 	case =>
     67 		let x = 42;
     68 	};
     69 };
     70 
     71 export fn main() void = {
     72 	basics();
     73 	termination();
     74 	tagged_result();
     75 	str_switching();
     76 	binding();
     77 	// TODO: Test exhaustiveness and dupe detection
     78 };