Result type

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Qzd (talk | contribs) at 13:24, 14 May 2022 (Reverted edits by 2409:4053:13:B6BF:0:0:13DC:8A0 (talk) to last version by 2A01:110:8012:1012:8E33:21EA:B1E5:A660). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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 as data Either a b = Left a | Right b.[2]
  • In OCaml, it is defined by the standard library as type ('a, 'b) result = Ok of 'a | Error of 'b type.[3]
  • In Rust, it is defined by the standard library as enum Result<T, E> { Ok(T), Err(E) }.[4]
  • In Scala, the standard library also defines an Either type,[5] 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.[6]

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

  1. ^ "Result · An Introduction to Elm". guide.elm-lang.org.
  2. ^ "Data.Either". hackage.haskell.org.
  3. ^ "Error Handling – OCaml". ocaml.org.
  4. ^ "std::result - Rust". doc.rust-lang.org.
  5. ^ "Scala Standard Library 2.13.3 - scala.util.Either". www.scala-lang.org. Retrieved 9 October 2020.
  6. ^ "Apple Developer Documentation". developer.apple.com.