1

Ocaml の初心者として、私は型で遊んでいて、バリアントがどのように機能するかを理解しようとしています。

サンプルは次のとおりです。

type 'a component =
  { foo : int;
    bar : 'a }

type string_or_float_component =
  | Str of string component
  | Flt of float component

let get_foo_1 (comp: 'a component) = comp.foo
(* works *)

let get_foo_2 (Str comp) = comp.foo
(* works *)

let get_bar_3 (comp : string_or_float_component) = comp.foo
(* This expression has type string_or_float_component
   but an expression was expected of type 'a component *)

私は最善の解決策 (パターン マッチングなど) を見つけようとしているわけではありません。なぜ ocaml が get_bar_3 でコンポーネントが Str | であると推論できないのかを理解するだけです。フリット。

多分そのようなトリックは何とか可能ですか?

type 'a string_or_float =
  | Str of string 'a
  | Flt of float 'a

ありがとう

(バックルスクリプトを使用しています)

編集 :

私の問題はよりデザインに関連していることに気付きました。私はこのようなもので作業することができます:

type string_or_float  =
    | Str of string
    | Flt of float


type 'a component = { foo: int; bar: 'a }

let get_bar_3 (comp : string_or_float component) ...
4

1 に答える 1