Result型

戻り値またはエラーコードを保持するモナディック型 From Wikipedia, the free encyclopedia

関数型プログラミングにおいて、Result型英語: Result type)は、戻り値またはエラーコードを保持するモナディック型である。これは、例外処理に頼らないエラー処理の洗練された方法を提供する。失敗する可能性のある関数がResult型を返す場合、プログラマは結果にアクセスする前に、結果が成功であるか失敗であるかを確認することが強制される。これにより、プログラマがエラー処理を忘れる可能性が排除される。

  • Elmでは、標準ライブラリでtype Result e v = Ok v | Err eとして定義されている[1]
  • Haskellでは、慣例により、標準ライブラリでdata Either a b = Left a | Right bとして定義されているEither型がこの用途に使用される[2]
  • Kotlinでは、標準ライブラリでvalue class Result<out T>として定義されている[3]
  • OCamlでは、標準ライブラリでtype ('a, 'b) result = Ok of 'a | Error of 'b typeとして定義されている[4]
  • Rustでは、標準ライブラリでenum Result<T, E> { Ok(T), Err(E) }として定義されている[5][6]
  • Scalaでは、標準ライブラリでEither型が定義されているが[7]、従来の例外処理によるエラー処理も提供している。
  • Swiftでは、標準ライブラリで@frozen enum Result<Success, Failure> where Failure : Errorとして定義されている[8]
  • C++では、標準ライブラリでstd::expected<T, E>として定義されている[9]

Rust

Result型にはis_ok()メソッドと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"))
    }
}

脚注

関連項目

Related Articles

Wikiwand AI