Having a Result[T, Err] monad that could represent either the data from a successful operation or an error. This can be generalised to the Either[A, B] monad too.
Nope. Monads enable you to redefine how statements work.
Let's say you have a program and use an Error[T] data type which can either be Ok {Value: T} or Error:
var a = new Ok {Value = 1};
var b = foo();
return new Ok {Value = (a + b)};
Each statement has the following form:
var a = expr;
rest
You first evaluate the "expr" part and bind/store the result in variable a, and evaluate the "rest" of the program.
You could represent the same thing using an anonymous function you evaluate right away:
(a => rest)(expr);
In a normal statement you just pass the result of "expr" to the function directly. The monad allows you to redefine that part.
You instead write:
bind((a => rest), expr);
Here "bind" redefines how the result of expr is passed to the anonymous function.
If you implement bind as:
B bind(Func[A, B] f, A result_expr) {
return f(result_expr);
}
Then you get normal statements.
If you implement bind as:
Error[B] bind(Func[A, Error[B]] f, Error[A] result_expr) {
switch (result_expr) {
case Ok { Value: var a}:
return f(a);
case Error:
return Error;
}
}
You get statements with error handling.
So in an above example if the result of foo() is Error, the result of the statement is Error and the rest of the program is not evaluated. Otherwise, if the result of foo() is Ok {Value = 3}, you pass 3 to the rest of the program and you get a final result Ok {Value = 4}.
So the whole idea is that you hide the if Error part by redefining how the statements are interpreted.
"Some generic class" with specific methods and laws, Monads are an algebraic structure and you want those laws included same as if you enable some type to use + you want to have a 0 somewhere and x + 0 == x to hold. Like "foo" + "" == "foo" in the case of strings, just as an example.
In Rust, Result and Option actually are monads. Let's take Option as example:
Why those laws? Because following them avoids surprises like x + 0 /= x.
Rust's type system isn't powerful enough to have a Monad trait (lack of HKTs) hence why you can't write code that works with any type that implements that kind of interface. Result names >>=and_then, just like Option does so the code reads the same but you'll have to choose between Option or Result in the type signature, the code can't be properly generic over it.
Its how rust does error handling for example, you have to test a return value for "something or nothing" but you can pass the monadic value and handle the error later, in go you have to handle the error explicitly (almost) all the time.
Here's an example (first in Haskell then in Go), lets say you have some types/functions:
type Possible a = Either String a
data User = User { name :: String, age :: Int }
validateName :: String -> Possible String
validateAge :: Int -> Possible Int
then you can make
mkValidUser :: String -> Int -> Possible User
mkValidUser name age = do
validatedName ← validateName name
validatedAge ← validateAge age
pure $ User validatedName validatedAge
for some reason <- in lemmy shows up as <- inside code blocks, so I used the left arrow unicode in the above instead
in Go you'd have these
(no Possible type alias, Go can't do generic type aliases yet, there's an open issue for it)
In the Haskell, the fact that Either is a monad is saving you from a lot of boilerplate. You don't have to explicitly handle the Left/error case, if any of the Eithers end up being a Left value then it'll correctly "short-circuit" and the function will evaluate to that Left value.
Without using the fact that it's a functor/monad (e.g you have no access to fmap/>>=/do syntax), you'd end up with code that has a similar amount of boilerplate to the Go code (notice we have to handle each Left case now):
mkValidUser :: String -> Int -> Possible User
mkValidUser name age =
case (validatedName name, validateAge age) of
(Left nameErr, _) => Left nameErr
(_, Left ageErr) => Left ageErr
(Right validatedName, Right validatedAge) =>
Right $ User validatedName validatedAge
Swift and Rust have a far more elegant solution. Swift has a pseudo throw / try-catch, while Rust has a Result<> and if you want to throw it up the chain you can use a ? notation instead of cluttering the code with error checking.
The exception handling question mark, spelled ? and abbreviated and pronounced eh?, is a half-arsed copy of monadic error handling. Rust devs really wanted the syntax without introducing HKTs, and admittedly you can't do foo()?.bar()?.baz()? in Haskell so it's only theoretical purity which is half-arsed, not ergonomics.
It's not a half-arsed copy, it's borrowing a limited subset of HKT for a language with very different goals. Haskell can afford a lot of luxuries that Rust can't.
It's a specialised syntax transformation that has nothing to do with HKTs, or the type system in general. Also HKTs aren't off the table it's just that their theory isn't exactly trivial in face of the rest of Rust's type system but we already have GATs.
It actually wouldn't be hard writing a macro implementing do-notation that desugars to and_then calls on a particular type to get some kind of generic code (though of course monomorphised), but of course that would be circumventing the type system.
Anyhow my point stands that how Rust currently does it is imitating all that Haskell goodness on a practical everyday coding level but without having (yet) to solve the hard problem of how to do it without special-cased syntax sugar. With proper monads we e.g. wouldn't need to have separate syntax for async and ?
Note: Lemmy code blocks don't play nice with some symbols, specifically < and & in the following code examples
This isn't a language level issue really though, Haskell can be equally ergonomic.
The weird thing about ?. is that it's actually overloaded, it can mean:
call a function on A? that returns B?
call a function on A? that returns B
you'd end up with B? in either case
Say you have these functions
toInt :: String -> Maybe Int
double :: Int -> Int
isValid :: Int -> Maybe Int
and you want to construct the following using these 3 functions
fn :: Maybe String -> Maybe Int
in a Rust-type syntax, you'd call
str?.toInt()?.double()?.isValid()
in Haskell you'd have two different operators here
str >>= toInt <&> double >>= isValid
however you can define this type class
class Chainable f a b fb where
(?.) :: f a -> (a -> fb) -> f b
instance Functor f => Chainable f a b b where
(?.) = (<&>)
instance Monad m => Chainable m a b (m b) where
(?.) = (>>=)
and then get roughly the same syntax as rust without introducing a new language feature
str ?. toInt ?. double ?. isValid
though this is more general than just Maybes (it works with any functor/monad), and maybe you wouldn't want it to be. In that case you'd do this
class Chainable a b fb where
(?.) :: Maybe a -> (a -> fb) -> Maybe b
instance Chainable a b b where
(?.) = (<&>)
instance Chainable a b (Maybe b) where
(?.) = (>>=)
restricting it to only maybes could also theoretically help type inference.
I was thinking along the lines of "you can't easily get at the wrapped type". To get at b instead of Maybe b you need to either use do-notation or lambdas (which do-notation is supposed to eliminate because they're awkward in a monadic context) whereas Rust will gladly hand you that b in the middle of an expression, and doesn't force you to name the point.
Or to give a concrete example, if foo()? {...} is rather awkward in Haskell, you end up writing things like
foo x y = bar >>= baz x y
where
baz x y True = x
baz x y False = y
, though of course baz is completely generic and can be factored out. I think I called it "cap" in my Haskell days, for "consequent-alternative-predicate".
Flattening Functors and Monads syntax-wise is neat but it's not getting you all the way. But it's the Haskell way: Instead of macros, use tons upon tons of trivial functions :)
I actually kind of like the error handling. Code should explain why something was a problem, not just where it was a problem. You get a huge string of "couldn't foobar the baz: target baz was not greebleable: no greeble provider named fizzbuzz", and while the strings are long as hell they are much better explanations for a problem than a stack trace is.
The language was designed to be as simple as possible, as to not confuse the developers at Google. I know this sounds like something I made up in bad faith, but it's really not.
The key point here is our programmers are Googlers, they’re not researchers. They’re typically, fairly young, fresh out of school, probably learned Java, maybe learned C or C++, probably learned Python. They’re not capable of understanding a brilliant language but we want to use them to build good software. So, the language that we give them has to be easy for them to understand and easy to adopt. – Rob Pike
"It must be familiar, roughly C-like. Programmers working at Google are early in their careers and are most familiar with procedural languages, particularly from the C family. The need to get programmers productive quickly in a new language means that the language cannot be too radical. – Rob Pike
The infamous if err != nil blocks are a consequence of building the language around tuples (as opposed to, say, sum types like in Rust) and treating errors as values like in C. Rob Pike attempts to explain why it's not a big deal here.
a desperate fear of modular code that provides sound and safe abstractions over common patterns. that the language failed to learn from Java and was eventually forced to add generics anyway - a lesson from 2004 - says everything worth saying about the language.