# Result type

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/Result_type
> Markdown URL: https://mediated.wiki/source/Result_type.md
> Source: https://en.wikipedia.org/wiki/Result_type
> Source revision: 1347450038
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

{{Short description|Concept in functional programming}}
{{Use dmy dates|date=October 2023}}
{{More citations needed|date=January 2021|bot=noref (GreenC bot)}}
In [functional programming](/source/functional_programming), a '''result type''' is a [monadic type](/source/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 [C++](/source/C%2B%2B), it is defined by the standard library as {{code|2=cpp|1=std::expected<T, E>}}.<ref>{{cite web |date=2023-08-25 |title=std::expected - cppreference.com |url=https://en.cppreference.com/w/cpp/utility/expected |url-status=live |archive-url=https://web.archive.org/web/20231009033232/https://en.cppreference.com/w/cpp/utility/expected |archive-date=2023-10-09 |access-date=2023-10-09 |website=en.cppreference.com}}</ref>
* In [Elm](/source/Elm_(programming_language)), it is defined by the standard library as {{code|2=elm|1=type Result e v = Ok v {{!}} Err e}}.<ref>{{cite web |title=Result · An Introduction to Elm |url=https://guide.elm-lang.org/error_handling/result.html |url-status=live |archive-url=https://web.archive.org/web/20231009032650/https://guide.elm-lang.org/error_handling/result.html |archive-date=2023-10-09 |access-date=2023-10-09 |website=guide.elm-lang.org}}</ref>
* In [Haskell](/source/Haskell_(programming_language)), by convention the {{code|Either|haskell}} type is used for this purpose, which is defined by the standard library as {{code|1=data Either a b = Left a {{!}} Right b|2=haskell}}, where {{code|a|haskell}} is the error type and {{code|b|haskell}} is the return type.<ref>{{cite web |date=2023-09-22 |title=Data.Either |url=https://hackage.haskell.org/package/base-4.18.1.0/docs/Data-Either.html |url-status=live |archive-url=https://web.archive.org/web/20231009031549/https://hackage.haskell.org/package/base-4.18.1.0/docs/Data-Either.html |archive-date=2023-10-09 |access-date=2023-10-09 |website=hackage.haskell.org}}</ref>
* In [Java](/source/Java_(programming_language)), it is not natively in the standard library, but is available from third party libraries. For example, [https://github.com/sviperll/result4j result4j] which includes an interface <code>Result<R, E></code> similar to Rust <code>Result<T, E></code>, and [https://github.com/vavr-io/vavr vavr] includes an interface <code>Either<L, R></code> similar to Haskell <code>Either a b</code>. Because Java and Kotlin are cross-compatible, Java can use the <code>Result</code> type from Kotlin.
* In [Kotlin](/source/Kotlin_(programming_language)), it is defined by the standard library as {{code|2=kotlin|1=value class Result<out T>}}.<ref>{{cite web |title=Result - Kotlin Programming Language |url=https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/ |url-status=live |archive-url=https://web.archive.org/web/20231009032856/https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-result/ |archive-date=2023-10-09 |access-date=2023-10-09 |website=kotlinlang.org}}</ref>
* In [OCaml](/source/OCaml), it is defined by the standard library as {{code|2=ocaml|1=type ('a, 'b) result = Ok of 'a {{!}} Error of 'b type}}.<ref>{{cite web |title=Error Handling · OCaml Tutorials |url=https://ocaml.org/docs/error-handling#using-the-result-type-for-errors |url-status=live |archive-url=https://web.archive.org/web/20231009030828/https://ocaml.org/docs/error-handling#using-the-result-type-for-errors |archive-date=2023-10-09 |access-date=2023-10-09 |website=ocaml.org}}</ref>
* In [Python](/source/Python_(programming_language)), it is not natively in the standard library, but is available from third party libraries such as [https://github.com/dry-python/returns returns] and [https://github.com/rustedpy/result result].
* In [Rust](/source/Rust_(programming_language)), it is defined by the standard library as {{code|2=rust|1=enum Result<T, E> { Ok(T), Err(E) } }}.<ref>{{cite web |title=std::result - Rust |url=https://doc.rust-lang.org/std/result/index.html |url-status=live |archive-url=https://web.archive.org/web/20231009032955/https://doc.rust-lang.org/std/result/index.html |archive-date=2023-10-09 |access-date=2023-10-09 |website=doc.rust-lang.org}}</ref><ref>{{cite web |date=2011-10-29 |title=stdlib: Add result module · rust-lang/rust@c1092fb |url=https://github.com/rust-lang/rust/commit/c1092fb6d88efe51e42df3aae2a321cc669e12a0 |url-status=live |archive-url=https://web.archive.org/web/20231009033047/https://github.com/rust-lang/rust/commit/c1092fb6d88efe51e42df3aae2a321cc669e12a0 |archive-date=2023-10-09 |access-date=2023-10-09 |website=github.com}}</ref>
* In [Scala](/source/Scala_(programming_language)), the standard library also defines an {{code|Either|scala}} type,<ref>{{cite web |title=Scala Standard Library 2.13.12 - scala.util.Either |url=https://www.scala-lang.org/api/current/scala/util/Either.html |url-status=live |archive-url=https://web.archive.org/web/20231009032237/https://www.scala-lang.org/api/current/scala/util/Either.html |archive-date=2023-10-09 |accessdate=2023-10-09 |website=www.scala-lang.org}}</ref> however Scala also has more conventional [exception handling](/source/exception_handling).
* In [Swift](/source/Swift_(programming_language)), it is defined by the standard library as {{code|2=swift|1=@frozen enum Result<Success, Failure> where Failure : Error}}.<ref>{{cite web |title=Result {{!}} Apple Developer Documentation |url=https://developer.apple.com/documentation/swift/result |url-status=live |archive-url=https://web.archive.org/web/20231009032505/https://developer.apple.com/documentation/swift/result |archive-date=2023-10-09 |access-date=2023-10-09 |website=developer.apple.com}}</ref>
* In [V](/source/V_(programming_language)), the result type is implemented natively using <code>!T</code> as the return type of a function. For example <code>fn my_function() !string { ... }</code>. [https://v-lang.dev/book/en/error_handling.md Error Handling in V].

=== C++ ===
The <code>expected<T, E></code> class uses <code>std::unexpected()</code> to return the type <code>E</code>, and can return <code>T</code> directly.
<syntaxhighlight lang="cpp">
import std;

using std::expected;
using std::ifstream;
using std::string;
using std::stringstream;
using std::unexpected;
using std::filesystem::path;

enum class FileError {
    MISSING_FILE,
    NO_PERMISSION,
    // more errors here
};

expected<string, FileError> loadConfig(const path& p) noexcept {
    if (!std::filesystem::exists(p)) {
        return unexpected(FileError::MISSING_FILE);
    }
    ifstream config{p};
    stringstream buffer;
    if (!config.is_open()) {
        return unexpected(FileError::NO_PERMISSION);
    }
    buffer << config.rdbuf();
    config.close();
    return buffer.str();
}

int main(int argc, char* argv[]) {
    path p{"configs/my_config.txt"};
    if (const expected<String, FileError> s = loadConfig(p); s.has_value()) {
        std::println("Config contents: {}", s.value());
    } else {
        switch (s.error) {
            case FileError::MISSING_FILE:
                std::println("Error: path {} not valid or missing!", p);
                break;
            case FileError::NO_PERMISSION:
                std::println("Error: no permission to read file at path {}!", p);
                break;
            // additional cases...
            default:
                std::unreachable();
        }
    }
}
</syntaxhighlight>

=== Rust ===
Enums in Rust are [tagged unions](/source/Tagged_union), which can be unpacked with strong type checking through pattern matching.
<syntaxhighlight lang="rust">
const CAT_FOUND: bool = true;

fn main() {
    let result: Result<(), String> = pet_cat();
    match result {
        Ok(_) => println!("Great, we could pet the cat!"),
        Err(error) => println!("Oh no, we couldn't pet the cat: {error}")
    }
}

fn pet_cat() -> Result<(), String> {
    if CAT_FOUND {
        Ok(())
    } else {
        Err(String::from("The cat is nowhere to be found!"))
    }
}
</syntaxhighlight>

=== Vlang ===
The <code>Error</code> type is an interface for <code>iError</code>.
<syntaxhighlight lang="rust">

const cat_found = true

fn main() {
    cat_name := get_pet_cat_name() or { 
        println("Oh no, we couldn't pet the cat!")
        exit(1)
    }

    println('Great, we could pet the cat ' + cat_name)
}

fn get_pet_cat_name() !string {
    if cat_found { return 'Max' } 
    else { return error('the cat is nowhere to be found') }
}
</syntaxhighlight>

== See also ==
* [Option type](/source/Option_type)
* [Exception handling](/source/Exception_handling)
* [Tagged union](/source/Tagged_union)
* [Return type](/source/Return_type)

== References ==
{{Reflist}}

Category:Functional programming

---
Adapted from the Wikipedia article [Result type](https://en.wikipedia.org/wiki/Result_type) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/Result_type?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
