Result type

Last updated

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.

Contents

Examples

C++

The expected<T, E> class uses std::unexpected() to return the type E, and can return T directly.

importstd;usingstd::expected;usingstd::ifstream;usingstd::string;usingstd::stringstream;usingstd::unexpected;usingstd::filesystem::path;enumclassFileError{MISSING_FILE,NO_PERMISSION,// more errors here};expected<string,FileError>loadConfig(constpath&p)noexcept{if(!std::filesystem::exists(p)){returnunexpected(FileError::MISSING_FILE);}ifstreamconfig{p};stringstreambuffer;if(!config.is_open()){returnunexpected(FileError::NO_PERMISSION);}buffer<<config.rdbuf();config.close();returnbuffer.str();}intmain(intargc,char*argv[]){pathp{"configs/my_config.txt"};if(constexpected<String,FileError>s=loadConfig(p);s.has_value()){std::println("Config contents: {}",s.value());}else{switch(s.error){caseFileError::MISSING_FILE:std::println("Error: path {} not valid or missing!",p);break;caseFileError::NO_PERMISSION:std::println("Error: no permission to read file at path {}!",p);break;// additional cases...default:std::unreachable();}}}

Rust

The result object has the methods is_ok() and is_err().

constCAT_FOUND:bool=true;fnmain(){letresult:Result<(),String>=pet_cat();ifresult.is_ok(){println!("Great, we could pet the cat!");}else{leterror:String=result.unwrap_err();println!("Oh no, we couldn't pet the cat: {}",error);}}fnpet_cat()->Result<(),String>{ifCAT_FOUND{Ok(())}else{Err(String::from("The cat is nowhere to be found!"))}}

Vlang

The Error type is an interface for iError.

constcat_found=truefnmain(){cat_name:=get_pet_cat_name()or{println("Oh no, we couldn't pet the cat!")exit(1)}println('Great,wecouldpetthecat'+cat_name)}fnget_pet_cat_name()!string{ifcat_found{return'Max'}else{returnerror('thecatisnowheretobefound')}}

See also

References

  1. "std::expected - cppreference.com". en.cppreference.com. 25 August 2023. Archived from the original on 9 October 2023. Retrieved 9 October 2023.
  2. "Result · An Introduction to Elm". guide.elm-lang.org. Archived from the original on 9 October 2023. Retrieved 9 October 2023.
  3. "Data.Either". hackage.haskell.org. 22 September 2023. Archived from the original on 9 October 2023. Retrieved 9 October 2023.
  4. "Result - Kotlin Programming Language". kotlinlang.org. Archived from the original on 9 October 2023. Retrieved 9 October 2023.
  5. "Error Handling · OCaml Tutorials". ocaml.org. Archived from the original on 9 October 2023. Retrieved 9 October 2023.
  6. "std::result - Rust". doc.rust-lang.org. Archived from the original on 9 October 2023. Retrieved 9 October 2023.
  7. "stdlib: Add result module · rust-lang/rust@c1092fb". github.com. 29 October 2011. Archived from the original on 9 October 2023. Retrieved 9 October 2023.
  8. "Scala Standard Library 2.13.12 - scala.util.Either". www.scala-lang.org. Archived from the original on 9 October 2023. Retrieved 9 October 2023.
  9. "Result | Apple Developer Documentation". developer.apple.com. Archived from the original on 9 October 2023. Retrieved 9 October 2023.