如何为fsi添加一个普通类型的漂亮打印机



在F#Interactive(fsi)中,您可以使用AddPrinterAddPrinterTransformer为交互式会话中的类型提供漂亮的打印。如何为通用类型添加这样的打印机?对类型使用通配符_不起作用:

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

打印机就是没用。

输入类型参数也会发出警告:

> fsi.AddPrinter(fun (A : MyList<'T>) -> A.ToString());;
  fsi.AddPrinter(fun (A : MyList<'T>) -> A.ToString());;
  -------------------------------^^
d:projectsstdin(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'.

这也不是我想要的。

这对一般情况不起作用,但由于您似乎在使用自己的类型(至少在您的示例中),并且假设您不想影响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和反射来获取要显示的值。如果你有源代码,接口会更容易。

最新更新