Practical Uses of Dependent Types in Programming

type-systems

I've been reading about this thing called dependent types.

So for example imagine a function firstNPrimes(int n) which returns an array of length n. In other words the type it returned would be int[n]. (In normal programming languages without dependent types all we can say is it returns int[] where the type doesn't specify the array length.)

I'm not entirely sure how useful this is though. I suppose if you had a cross product (into which that first function could be sent as arguments):

int[3] Cross(int[3] A, int[3] B){..}

which only worked on 3 dimensional vectors then maybe the compiler could type check this and avoid pointer issues.

Are there any real practical uses of dependent types that would be useful in everyday programming? Or are they mainly just useful for abstract logic?

Best Answer

I think what you might be missing is the value you are depending on doesn't have to be a constant like 3. The length is often specified generically, so you may not know the exact length, but you can specify constraints on that length between your return values and different arguments.

There are a lot of functions that require n > 0, like head for example.

There are a lot of functions that take an index that must be within the size of the vector.

There are a lot of functions that take two vectors that must be the same size as each other, like a dot product for example.

Dependent typing allows you to verify all of these sorts of constraints at compile time, validating at the very edge of your system.

Related Topic