Do it the OCaml way:

1
2
3
let ch = open_out "foo.dat" in
try output_value ch my_tree
finally close_out ch

Cheers,
Jon.

By on 11/27/2006 4:53 AM ()

Hi Peter,

I don't know of any F# specific way but the .NET BCL has several serialisers that will all work with F# types. I would recomend the BinaryFormatter as the XML baised ones, there are several, tend to only serialise public fields which means you have to design your types quite carelly to get them to work properly for the xml formatters.

Here's a quick example of serialising something using the BinaryFormatter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#light
open System.IO
open System.Runtime.Serialization.Formatters.Binary

type Expr = 
  | Val of string 
  | Float of System.Double
  | Multi of Expr * Expr
  | Div of Expr * Expr
  | Plus of Expr * Expr
  | Minus of Expr * Expr

let tree = Multi ( Float (8.0), Float (8.0) )

let serialiser = new BinaryFormatter()

using (File.Open("tree.ats", FileMode.Create))
    (fun treeFile -> serialiser.Serialize(treeFile, tree))

let tree2 = 
    using (File.Open("tree.ats", FileMode.Open))
        (fun treeFile -> serialiser.Deserialize(treeFile) :?> Expr)
        
printf "tree: %O\r\n" tree
printf "tree2: %O\r\n" tree2
read_line()

Of course the really problem with serialisation format is the resulting file is not easily understandable by humans, but you do not say whether this is a requirement or not.

Cheers, Rob

By on 11/26/2006 2:32 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper