2010-05-15 17 views

回答

8

我想獲得any_to_string功能的唯一方法是使用 「%A」 格式。警告告訴你這一點。

let any_to_string = sprintf "%A"

這並不調用的ToString()。對於像列表這樣的簡單類型,.ToString()已經產生了很好的表示。但是,當使用自己的自定義類型時,%A格式化程序更有用。例如,在樹結構的情況下,它沿着樹行走。

如果你想在對象上調用的ToString(),您可以用「%O」格式化。

例子:

type Tree = Node of Tree * Tree | Leaf 
let myTree = Node(Node(Leaf,Leaf),Node(Leaf,Node(Leaf,Leaf))) 

和FSI:

> myTree.ToString();; 
val it : string = "FSI_0002+Tree+Node" 
> sprintf "%O" myTree;; 
val it : string = "FSI_0002+Tree+Node" 
> sprintf "%A" myTree;; 
val it : string = "Node (Node (Leaf,Leaf),Node (Leaf,Node (Leaf,Leaf)))" 
3

你可以用sprintf:

let a = [1;2;3] 
let b = sprintf "%A" a 
+0

是它唯一的其他可能的替代? – Stringer 2010-05-15 05:45:32

+0

我這麼認爲。 (更多的字符達到評論最低) – Brian 2010-05-15 09:12:01

1

怎麼樣string功能?

> string [1..3];; 
val it : string = "[1; 2; 3]" 
相關問題