SyntaxHighlighter

Saturday, July 31, 2010

My F# awareness is improving

So today I read an article that linked to a site called language references. It's basically a site like code keep, it has some snippets of code for common programming tasks or problems. I noticed that there is a section on F# so I decided to check it out. I started scrolling through the list and came to a snippet of code for reversing a string. This coding example is near and dear to me because it's one of those interview questions programmers tend to get... much like fizbuzz. However, after reviewing the implementation which was simple Array.Reverse on a character array I decided to create an account so that I could contribute my version of reversing a string in F#. If you go to the following url: http://langref.org/fsharp/strings/reversing-a-string/reverse-characters  you'll see my implementation which is also below.

let word = "reverse me"
//reverse the word
let reversedword = 
   word.ToCharArray()
   |> Array.fold(fun acc x -> List.Cons(x,acc)) []
I'm basically using a simple fold with an empty list as the accumulator or the element that's being threaded through. I picked up that tip from a functional programming video I saw on videos.google.com. The topic was Map Reduce. I then went on to the section of the site where they have a list of problems that have not been solved yet. So I decided to tackle one of those. I came across the following and immediately thought it would be rather simple to implement and I could use a simple fold again. :-)

Here's the problem: http://langref.org/fsharp/xml/parsing/xml-parse

So I came up with the following implementation: (which you will also see on the website)
#r @"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5\System.Xml.Linq.dll"

open System
open System.Xml.Linq
//XElement Helper
let xname sname = XName.Get sname 

 let xmlsnippet = 
    let snippet = new XElement(xname "shopping")
    //create bread
    let bread = new XElement(xname "item")
    bread.SetAttributeValue(xname "name","bread")
    bread.SetAttributeValue(xname "quantity",3)
    bread.SetAttributeValue(xname "price",2.50)
    //add bread to snippet
    snippet.Add(bread)
    //create milk
    let milk = new XElement(xname "item")
    milk.SetAttributeValue(xname "name","milk")
    milk.SetAttributeValue(xname "quantity",2)
    milk.SetAttributeValue(xname "price",3.50)
    //add milk to snippet
    snippet.Add(milk)
    snippet

let totalprice (xe: XElement) =
    xe.Descendants(xname "item")
        |> Seq.map(fun i -> Double.Parse(i.Attribute(xname "price").Value))
        |> Seq.fold(fun acc x -> acc + x) 0.0

F# is awesome!!

No comments:

Post a Comment