Value Objects in F#

Value Objects are objects that can be shared across different parts of a program. This can have great benefits in performance. Because  the objects are shared it is very important for value objects to be immutable. If value objects are not immutable then any part of the program can change the values and all the other parts can do calculation with erroneous data.

One of my goals was to make immutable objects in F# to take advantage of parallelization and automatic compiler optimizations:


type City(Name:string, X: float, Y:float) =

member t.Name = Name

member t.X = X

member t.Y = Y

type NeighborCities(city1:string, city2:string) =

member x.fromCity = city1

member x.toCity = city2

Objects created in this manner in F# are immutable. Even when they are accessed in other projects outside their definition, their members are read-only. This was specially helpful on the distributed traveling salesman problem I built last year.

Testing F#

F# is very cool. By combining the regular iterative features of the other .NET languages with an Ocaml syntax variant, F# is extremely flexible and powerful.

Here is a simple loop:

 for i in 0..loopSize do

Here is another example for reading in contents from a file, making an object city and returning a list of cities:


let ReadFile (s:string) = match s with
    | null -> raise (ApplicationException "Please provide a non-empty string for the filename!!")
    | s ->
    let cityList = new ResizeArray<CityDef.City>() in
    let rec ReadFile (r:StreamReader) =
        if not r.EndOfStream then
            cityList.Add(ParseCityString(r.ReadLine()))
            ReadFile r
        r.Close()
    let r = new StreamReader(s) in
    ReadFile r
    cityList

F# has powerful features because it has a lot of high order functions on top of the usual map, filter and reduce. The extra high order functions (such as iter, fold, scan, skip, skipWhile, sum, take, takeWhile, truncate, unfold, windowed, zip, zip3, etc.) make it easy to compound complex tasks.

The next example is a little snippet that returns a dictionary distances between cities for a small distributed traveling salesman problem I did last year to test F# on a software engineering class.


let squared x = x*x

let CompareNeighbors = {
    new System.Collections.Generic.IEqualityComparer<CityDef.NeighborCities> with
    member x.Equals(a,b) =  (String.Compare(a.fromCity, b.fromCity) = 0 ) && ( String.Compare(a.toCity, b.toCity) = 0 )
    member x.GetHashCode(a) = a.toCity.GetHashCode() }

let Distance (distanceDic : Dictionary<CityDef.NeighborCities, double>, i: CityDef.City, j: CityDef.City ) =
    let x2 = squared (i.X - j.X)
    let y2 = squared ( i.Y - j.Y)
    let total = sqrt( x2  +  y2)
    let n = new CityDef.NeighborCities(city1 = i.Name, city2 = j.Name)
    distanceDic.Add(n, total)

type DistanceDictionary() =
    interface Infrastructure.IDistanceCalculator with
        member this.DistanceDictionary (genericListOfCities:ResizeArray<CityDef.City>)  =
            let dic = new Dictionary<CityDef.NeighborCities, double>(CompareNeighbors)
            Seq.iter(fun z -> Seq.iter(fun x->Distance(dic, z, x)) genericListOfCities) genericListOfCities
            dic

Also it is nice being able to use interfaces with F# in the simple format of “interface Infrastructure.IDistanceCalculator with”.

As a little tip, for applying something to a list that does not require a new collection, it is important to avoid using the higher order function map. Map should only be used if a new list with a different set of values is expected because it creates a new list. In this case, map was not necessary and iter was the choice.