3 ms·
Haskell already has the capability to write type-level representations of numbers, so we can have types like zipVec :: Vector a n -> Vector b n -> Vector (
by andolanra 14y ago
Haskell already has the capability to write type-level representations of numbers, so we can have types like
zipVec :: Vector a n -> Vector b n -> Vector (a, b) n
where Vector a b is the type of a vector of elements of type a that is of length n. The above function will therefore only zip together two vectors if they have the same length; otherwise it's a compile-time error. Right now, people usually roll their own representations of numbers, but this new extension means not only do we have a standard one, we can now write something like myBuffer :: Buffer Int 256 where 256 is a type-level number.
With type-level symbols, we could do something like
data StringWrapper (a :: Symbol) = S String
getUserData :: IO (StringWrapper "unsanitized")
writeToDB :: StringWrapper "sanitized" -> IO ()
sanitize :: StringWrapper "unsanitized" -> StringWrapper "sanitized"
stringLength :: StringWrapper a -> Int
so that writing code like
do x <- getUserData
putStrLn ("Length is " ++ show (stringLength x))
writeToDb x -- forgetting to sanitize
produces a compile-time error because the types don't match up.
- TylerE 14y agoAhh! Makes sense now. Thanks.
- ocharles 14y agoThis is a good example, but I'm not sure it's very real world. You wouldn't really use symbols in this case - you'd specifically introduce a Sanitized type and promote it to the kind level. But I'm picking holes, it's a good example of the power that the new type system gives us :)