将对象转换为字符串的标准(惯用)方式

时间:2013-05-07 11:12:46

标签: dylan

我试图打印这个类的对象:

define class <bill> (<object>)
    slot num :: <string>;
    slot ref :: <string>;
end class <bill>;

我可以制作像say

这样的方法
define method say (bill : <bill>) => ();
    format-out("num:%s\n", bill.num);
    format-out("ref:%s\n", bill.ref);
end method say;

但我想要一个方法将对象转换为<string>,可以像

一样使用
format-out("%s\n", bill);

or

format-out("%s\n", as(<string>, bill));

or

format-out("%=\n", bill);

我试过

define method as(type == <string>, bill :: <bill>) 
  => (s :: <string>);
  let result :: <stretchy-vector> = make(<stretchy-vector>);
  add!(result, bill.num);
  add!(result, bill.ref);
  join(result, " ");
end method as;

但是:

format-out("\%s\n", as(<string>,bill)); 

我有这个结果

Object {<bill>} cannot be converted to class {<class>: <string>}
Object {<bill> 0x1ff8180} cannot be converted to class {class <string> 0x7f5d5c645c00}
Breaking into debugger.
Trace/breakpoint trap

An with this:

format-out("%s\n", bill);

结果:

{<bill> #x00000000025EF1B0}

我做错了什么? 什么是打印对象的标准(惯用)方式?

1 个答案:

答案 0 :(得分:2)

添加支持打印对象的惯用方法是专门化print-object。但是,如果您希望能够将对象表示转换为字符串,那么专门用作通用就行了,就像您一样。它在这里工作,所以也许某处有一个错误:

module: bill

define class <bill> (<object>)
  constant slot num :: <string>, init-keyword: num:;
  constant slot ref :: <string>, init-keyword: ref:
end class <bill>;

define method as(type == <string>, bill :: <bill>) => (s :: <string>);
  join(vector(bill.num, bill.ref), " ");
end method as;

format-out("%=\n", as(<string>, make(<bill>, num: "1", ref: "a")));

结果:

$ bill 
"1 a"