Sunday, June 13, 2010

Why I love F#, Part 2

Here’s another small sample of F# readability. When I was an undergraduate, we were taught that the first step in data analysis was the computation of basic descriptive statistics. At first we learned to do this by hand, but later we moved to computer programs like SPSS. However, if asked to imagine a how such a program might look, it would have been a struggle to come up with something in the BASIC that I was learning at the same time.

One the other hand, here is an F# example. I can’t imagine having any trouble explaining the operation of this program to someone with a basic knowledge of statistics but no computer programming experience. It simply looks like what it does in a way that is succinct and comprehensible. (I did deliberately avoid constructs like folding which might make it more difficult to understand.)

Albeit this is a simple example. However, with a little experience, seemingly incomprehensible things like workflows and continuations become just as obvious in F#.

And that’s what I love about F# and why I think it has a future.

// This code is presented "as-is" and without warranty 
// or implied fitness of any kind; use at your own risk. 
 
// Compute basic statistics.
let basicStats (l:float list) =
  let sum = l |> List.sum 
  let count = (float) l.Length 
  let avg = sum / count
  let std = 
    l 
    |> List.map (fun x->(x-avg)**2.0)
    |> List.sum
    |> (fun x->(x/(count-1.0))**0.5)
  (count,sum,avg,std)
 
// Test.
let x = 
  [ for i in 0..9 -> (float) i] 
  |> basicStats 

No comments: