From Handwiki In functional programming, a result type is a monadic type holding a returned value or an error code. They provide an elegant way of handling errors, without resorting to exception handling; when a function that may fail returns a result type, the programmer is forced to consider success or failure paths, before getting access to the expected result; this eliminates the possibility of an erroneous programmer assumption.
type Result e v = Ok v | Err e.[1]Either type is used for this purpose, which is defined by the standard library as data Either a b = Left a | Right b, where a is the error type and b is the return type.[2]value class Result<out T>.[3]type ('a, 'b) result = Ok of 'a | Error of 'b type.[4]enum Result<T, E> { Ok(T), Err(E) }.[5][6]Either type,[7] however Scala also has more conventional exception handling.@frozen enum Result<Success, Failure> where Failure : Error.[8]std::expected<T, E>.[9]The result object has the methods is_ok() and is_err().
const CAT_FOUND: bool = true;
fn main() {
let result = pet_cat();
if result.is_ok() {
println!("Great, we could pet the cat!");
} else {
println!("Oh no, we couldn't pet the cat!");
}
}
fn pet_cat() -> Result<(), String> {
if CAT_FOUND {
Ok(())
} else {
Err(String::from("the cat is nowhere to be found"))
}
}
![]() |
Categories: [Functional programming]