7

F# Interactive (fsi) では、AddPrinterorを使用AddPrinterTransformerして、インタラクティブ セッションで型のプリティ プリントを提供できます。ジェネリック型にそのようなプリンターを追加するにはどうすればよいですか? タイプにワイルドカード_を使用しても機能しません:

> fsi.AddPrinter(fun (A : MyList<_>) -> A.ToString());;

プリンターはほとんど使っていません。

型パラメーターを入れると、警告も表示されます。

> fsi.AddPrinter(fun (A : MyList<'T>) -> A.ToString());;

  fsi.AddPrinter(fun (A : MyList<'T>) -> A.ToString());;
  -------------------------------^^

d:\projects\stdin(70,51): warning FS0064: This construct causes code
to be less generic than indicated by the type annotations. The type
variable 'T been constrained to be type 'obj'.

これは私が望むものでもありません。

4

1 に答える 1

8

これは一般的なケースでは機能しませんが、(少なくともあなたの例では) 独自の型で作業しているように見えるので、 に影響を与えたくない場合はToString、次のようにすることができます:

type ITransformable =
  abstract member BoxedValue : obj

type MyList<'T>(values: seq<'T>) =
  interface ITransformable with
    member x.BoxedValue = box values

fsi.AddPrintTransformer(fun (x:obj) ->
  match x with
  | :? ITransformable as t -> t.BoxedValue
  | _ -> null)

出力:

> MyList([1;2;3])
val it : MyList<int> = [1; 2; 3]

サードパーティのジェネリック型の場合AddPrintTransformer、リフレクションを使用して表示する値を取得できます。ソースがあれば、インターフェイスは簡単です。

于 2013-02-21T22:22:35.247 に答える