3 ms·
I don't want to write a big wall of text, but a lot of situations come up where bugs could (if you so choose) be encoded into the type system. Here are some ex
by gnuvince 13y ago
I don't want to write a big wall of text, but a lot of situations come up where bugs could (if you so choose) be encoded into the type system. Here are some examples:
- The Maybe/Option type: you explicitly declare that a value may be missing, so you cannot call methods/functions on it willy-nilly; the compiler will force you to handle both cases. Say bye-bye to NoneType object has no attribute 'foo' errors.
- Different types for objects that have the same representation: in a language like Python, text, SQL queries, HTTP parameters, etc. are all represented as strings. Using a statically-typed language, you can give them each their own representation and prevent them from being mixed with one another. See [1] for a nice description of such a system. See also how to separate different units of measurements instead of using doubles for everything.
- Prevent unexpected data injections. With Python's json module, anything that is a valid JSON representation can be decoded. This is pretty convenient, but it means you must be very careful about what you decode. With Haskell's Aeson, you parse a JSON string into a predefined type, and if there are missing/extra fields, you get an error.
- When I was doing my machine learning class homeworks, I very often struggled with matrix multiplications errors. An important part of that was that the treatment of vectors vs Nx1 matrices was different. I feel that if I could encode the matrix size in the types, I'd have had an easier time and less errors.
These are simple examples, but whenever I code in Python, I inevitably make mistakes that I know would've been caught by the compiler if I had been coding in OCaml or Haskell.
[1] http://blog.moertel.com/posts/2006-10-18-a-type-based-solution-to-the-strings-problem.html http://blog.moertel.com/posts/2006-10-18-a-type-based-soluti...
- CmonDev 13y agoAlso, if you use F# flavour of OCaml you can use units of measure that would eliminate even more compile-time errors (if those matrices had something to do with physics for example).