Having your compile-time cake and eating it too

https://news.ycombinator.com/rss Hits: 1
Summary

Disclaimer In this post, I assume: You know a little bit about Rust. You know a little bit about Zig. I'll be using my own syntax to express ideas from both of these languages. Why "types are just values" doesn't work As programmers, we like it when our programs run well. Type systems are there to help us with that. They track the types of values in our programs before we run them, which not only saves us from runtime crashes but enforces guidelines for writing good code. Normally, type syntax (and logic) is distinct from the rest of a programming language. A rare exception to this rule is Zig, where types are just treated as values, and compile-time (comptime) operations on those values are allowed. That's all the type system is. In a normal language, the List[Int] type is a very abstract idea. But in Zig, List(Int) is just a regular function call where you're inputting a Type and getting a Type back. Simple, right? Well, if we can make a List function, why not a ListIfOddLength function that's a bit more powerful? ListIfOddLength = (T: Type) => Type: ( if (T.to_string.length % 2 == 1) then List(T) else T ) Okay, now let's make a generic function using it. (Square brackets introduce a type parameter.) weird_function = [T](value: T) => ListIfOddLength(T): ( ... ) The function above takes a value with some type (T). If that type has an odd length, it'll return a List(T), and otherwise it'll just return a T. While it may not be useful, Zig lets us express this sort of idea. The problem is that now you're putting arbitrary logic into a type signature. To understand what type weird_function returns, you'll need to understand exactly how ListIfOddLength works. You'd have to know what % means and what to_string does. Let's do more silly examples. Imagine that ListIfBHash(T) turns T into a string, then hashes it. The function usually returns T, but it'll return List(T) if the hash starts with a B. Or what about ListIfAmerica, which returns a List(T) if you're compiling fro...

First seen: 2025-05-26 21:53

Last seen: 2025-05-26 21:53