Saturday, June 12, 2010

This is why I love F#.

This is why I love F# (and functional programming in general). How could possibly state something so elegantly in any other type of language?

// This code is presented "as-is" and without warranty 
// or implied fitness of any kind; use at your own risk.
 
// A moving average on a sequence.
let movingAvg n s =
  s |> Seq.windowed n 
    |> Seq.map Array.sum 
    |> Seq.map (fun a->a/n) 
 
// Currying for the pure joy of it.
let movingAvg3 = movingAvg 3
 
let r = new System.Random()
 
// For test purposes, the input sequences are 
// based on lists so they can be easily examined...
let l0 = [ for i in 0..9 do yield i ]
let l1 = [ for i in 0..9 do yield r.Next(100) ]
 
// ...and the output sequences are converted to lists
// for the same reason.
let x0 = movingAvg3 l0 |> Seq.toList 
let x1 = movingAvg3 l1 |> Seq.toList

No comments: