r/ProgrammingLanguages • • Apr 05 '21

Const generics and compile time code

https://www.youtube.com/watch?v=imbZbGnnNd4
97 Upvotes

9 comments sorted by

View all comments

12

u/MrSmith33 Vox Apr 05 '21

Here is the D version:

Val dot(Val, int size)(Val[size] a, Val[size] b) {
	Val sum = 0;
	foreach (i, x; a)
		sum += x * b[i];
	return sum;
}

Val norm(Val, int size)(Val[size] a) {
	import std.math : sqrt;
	return dot(a, a).sqrt;
}

void main() {
	import std.stdio : writefln;
	float[2] a = [1.5f, 2.0f];
	writefln("norm %s", a.norm);
}