4 ms·
Rather, (in Go) errors are values that violate type safety and destroy any correctness guarantees the compiler makes. Languages like Rust and Haskell do this r
by wyager 12y ago
Rather, (in Go) errors are values that violate type safety and destroy any correctness guarantees the compiler makes.
Languages like Rust and Haskell do this right. Both make heavy use of optionals for failable functions, and Haskell's support for HKTs (and therefore Monads) allows awesome stuff like Maybe or Either chaining.
Monads allow you to write code that, syntactically, looks like you're not doing any error handling. In reality, the error handling semantics are baked in at the Monad level. This makes sense, because error handling is usually very repetitive (e.g. "Check if the function we just called failed. If it did, return early. Otherwise, keep going." ad infinitum). As a (pseudcoded) example:
parseTimeString :: String -> Either Error Time
parseTimeString string = parse string $ do
hours <- readHours
semicolon
minutes <- readMinutes
semicolon
seconds <- readSeconds
return (Time hours minutes seconds)
If any of those steps fails, the entire computation will stop and the error message will be returned. This is roughly equivalent to checking for "nil" (in Go) after every function call, except you don't actually have to do it. This is defined in the code for the Either monad, which is at https://hackage.haskell.org/package/base-4.7.0.2/docs/src/Data-Either.html#Either https://hackage.haskell.org/package/base-4.7.0.2/docs/src/Da... . As you can see, it's 4 lines of code.
(Side note: this is pretty much how you write parsers in Haskell using the Parsec library)
- JadeNB 12y ago> Both make heavy use of optionals for failable functions …. Haskell doesn't do so enough, though (I don't know Rust and so won't comment), so that we still need manually to choose to use the safe library (http://hackage.haskell.org/package/safe http://hackage.haskell.org/package/safe).
- tome 12y agoYes, some unfortunate historical choices there.
- JadeNB 12y ago> Yes, some unfortunate historical choices there. Do you know anything about the motivation of those choices? Surely it won't have escaped anyone's notice, especially not the designers', that this is a wart on the language, and that there is an easy solution; so I can only imagine that the easy solution was rejected for its inelegance—which seems strange, given the devotion to theoretical purity of the rest of the language. (I contrast the situation here to that of the numeric tower, which is clearly flawed but for which, even now, the 'right' approach is not so clear.)