Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

自動導出

💡 お知らせ: このドキュメントはAIによって翻訳されています。表現に違和感がある場合は、原文(英語)を参照するか、翻訳にご協力ください。

Flix は、いくつかのトレイトに対する自動導出(Automatic derivation)をサポートしています。これには以下が含まれます:

  • Eq — 型の値に対する構造的等価性を導出します。
  • Order — 型の値に対する全順序を導出します。
  • ToString — 型の値に対する人間が読みやすい文字列表現を導出します。
  • Coerce - 単純なデータ型をその基となる表現に変換します。

Eq と Order の導出

enum 宣言の with 節を使うことで、Eq トレイトと Order トレイトのインスタンスを自動的に導出できます。例えば:

enum Shape with Eq, Order {
    case Circle(Int32)
    case Square(Int32)
    case Rectangle(Int32, Int32)
}

導出された実装は構造的であり、case 宣言の順序に依存します:

def main(): Unit \ IO = 
    println(Circle(123) == Circle(123)); // `true` を出力
    println(Circle(123) != Square(123)); // `true` を出力
    println(Circle(123) <= Circle(123)); // `true` を出力
    println(Circle(456) <= Square(123))  // `true` を出力

注意: EqOrder の自動導出には、enum の内部の型自身が EqOrder を実装していることが必要です。

ToString の導出

ToString インスタンスも自動的に導出できます:

enum Shape with ToString {
    case Circle(Int32)
    case Square(Int32)
    case Rectangle(Int32, Int32)
}

これにより、文字列補間を活用して次のように書けます:

def main(): Unit \ IO = 
    let c = Circle(123);
    let s = Square(123);
    let r = Rectangle(123, 456);
    println("A ${c}, ${s}, and ${r} walk into a bar.")

これは次のように出力します:

A Circle(123), Square(123), and Rectangle(123, 456) walk into a bar.

Coerce の導出

Coerce トレイトの実装も自動的に導出できます。 Coerce トレイトは、単純な(case が1つの)データ型をその基となる実装に変換します。

enum Shape with Coerce {
    case Circle(Int32)
}

def main(): Unit \ IO =
    let c = Circle(123);
    println("The radius is ${coerce(c)}")

case が2つ以上ある enum に対して Coerce を導出することはできません。 例えば、次のように書こうとすると:

enum Shape with Coerce {
    case Circle(Int32)
    case Square(Int32)
}

Flix コンパイラはコンパイルエラーを出力します:

❌ -- Derivation Error --------------------------------------------------

>> Cannot derive 'Coerce' for the non-singleton enum 'Shape'.

1 | enum Shape with Coerce {
                    ^^^^^^
                    illegal derivation

'Coerce' can only be derived for enums with exactly one case.