Hi,
first of all, I should mention that the { x with ... } syntax isn't currently supported for classes and there is no similar feature that would make cloning of immutable classes easier (but I've heared that F# team is considering some possibilities for the future...).

Anyway, you can use many of the class features with record types as well, so you can for example implement the addition that you have in your example as a non-static member. It is also common to provide a static "Create" method for the type and expose the fields as public properties (which makes it possible to modify the type implementation without changing the code that uses the type in the future, so I would say it is a good practice), so one polished version using (..what I consider to be..) the best F# practices would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
type 'a Foo = 
 { bar : int
   whatever : 'a } 
  with 
    member x.Bar = x.bar
    member x.Whatever = x.whatever
    member x.Add amount = { x with bar = x.bar + amount} 
    static member Create(b, wh) = { bar = b; whatever = wh }

let f1 = Foo.Create(20, "Hello")
let f2 = f1.Add(22)
print_int f2.Bar

You can implement the same thing with F# classes, in which case you'll just change the way 'bar' and 'whatever' are stored and change the way the object is constructed in the 'Create' method. Using the implicit constructor syntax (which makes arguments to the constructor implicitly visible in the whole class) we get quite nice syntax (The only limitation is that because we can't use the 'with' syntax when creating a copy in the 'Add' member, we'll have to modify the code of the 'Add' member every time the constructor arguments change - but that's usually not a big problem):

1
2
3
4
5
type 'a Foo(bar:int, whatever:'a) = 
  member x.Bar = bar
  member x.Whatever = whatever
  member x.Add amount = Foo(bar+amount, whatever)
  static member Create(b, wh) = new Foo<_>(b, wh)

The code that uses the class will be the same as the code which use the record earlier.

By on 12/11/2007 6:27 PM ()
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