Result type
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.
Examples
- In Elm, it is defined by the standard library as
type Result e v = Ok v | Err e
.[1] - In Haskell, by convention the
Either
type is used for this purpose, which is defined by the standard library asdata Either a b = Left a | Right b
, wherea
is the error type andb
is the return type.[2] - In Kotlin, it is defined by the standard library as
value class Result<out T>
.[3] - In OCaml, it is defined by the standard library as
type ('a, 'b) result = Ok of 'a | Error of 'b type
.[4] - In Rust, it is defined by the standard library as
enum Result<T, E> { Ok(T), Err(E) }
.[5][6] - In Scala, the standard library also defines an
Either
type,[7] however Scala also has more conventional exception handling. - In Swift, it is defined by the standard library as
@frozen enum Result<Success, Failure> where Failure : Error
.[8] - In C++, it is defined by the standard library as
std::expected<T, E>
.[9]
Rust
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")) } }
See also
References
- ↑ "Result · An Introduction to Elm". https://guide.elm-lang.org/error_handling/result.html.
- ↑ "Data.Either". 2023-09-22. https://hackage.haskell.org/package/base-4.18.1.0/docs/Data-Either.html.
- ↑ "Result - Kotlin Programming Language". https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/.
- ↑ "Error Handling · OCaml Tutorials". https://ocaml.org/docs/error-handling#using-the-result-type-for-errors.
- ↑ "std::result - Rust". https://doc.rust-lang.org/std/result/index.html.
- ↑ "stdlib: Add result module · rust-lang/rust@c1092fb". 2011-10-29. https://github.com/rust-lang/rust/commit/c1092fb6d88efe51e42df3aae2a321cc669e12a0.
- ↑ "Scala Standard Library 2.13.12 - scala.util.Either". https://www.scala-lang.org/api/current/scala/util/Either.html. Retrieved 2023-10-09.
- ↑ "Result | Apple Developer Documentation". https://developer.apple.com/documentation/swift/result.
- ↑ "std::expected - cppreference.com". 2023-08-25. https://en.cppreference.com/w/cpp/utility/expected.
Original source: https://en.wikipedia.org/wiki/Result type.
Read more |