Archive for the ‘F#’ Category

F# string to object model

06 Nov

A while back I wrote about a nice little piece of code that I wrote which converted an object into a string, and vice versa, in order to be sent and retrieved from a transactional main frame. Check it out here – C# string to object model using method attributes, reflection, anonymous types and LINQ.

A while back I also dabbled in a bit of F# – The new functional programming language from Microsoft. F# is a fantastic language! It took me a while to get used to not having curly braces and the layout of F#, but once I got around that I was away.

My first venture into F# was to convert my string to object model code, mentioned above, into F#!

Here is my F# version of my C# code:

//The Validation Attribute
type public InputRegexAttribute public (format : string) as this =
    inherit Attribute()
    member self.Format with get() = format

//The class definition
type public Foo public (firstName, familyName) as this =
    member self.FirstName with get() = firstName 

    member self.FamilyName with get() = familyName 

module ObjectExtensions =
    type System.Object with
        member this.BuildString template =
            let mutable updatedTemplate : string  = template
            for prop in this.GetType().GetProperties() do
                for attribute in prop.GetCustomAttributes(typeof,true)
                                           .Cast() do
                    let regex = new Regex(attribute.Format)
                    let value = prop.GetValue(this, null).ToString()
                    if regex.IsMatch(value) then
                        updatedTemplate <- updatedTemplate.Replace("{" + prop.Name + "}", value)
                        raise (new Exception "Regex Failed")

open ObjectExtensions
    let foo = new Foo("Jane", "Doe")
    let out = foo.BuildInputString("Hello {FirstName} {FamilyName}! How Are you?")
    printf "%s" out
with | e -> printf "%s" e.Message

The methods are not purely functional as I have used a mutable string, but as you can see there is a lot less code to do, effectively, the same thing!

Maybe if I get some time I will investigate a way of making the code purely functional without any mutable objects.

Comments Off

Posted in F#