Here are some random snippets of f# code I had lying around. mostly simple stuff for basic stats calculations. Not the most complex stuff but maybe its useful to somebody trying to learn f#.
// Learn more about F# at http://fsharp.net
open System
open System.Net
//basic arithmetic mean
let Mean (x:List<float>) =
let sum = x |> Seq.sum
let items = x |>Seq.length
sum / (float items)
//basic variance method
let Variance x =
let m = Mean x
let deviation =
x
|> Seq.map (fun x -> Math.Pow((x-m), 2.))
|> Seq.toList
Mean deviation
//Calculates standard deviation using above variance method
let StandardDeviation x =
Math.Sqrt(Variance x)
//recursively calculates the factorial of x
//will overflow long before running into recursion limits
//at larger values it will wrap back around to 0
let rec Factorial x =
if x = 0I then
1I
else
x * Factorial(x-1I)
//calculates combinations
let Combinations n r =
(Factorial n)/ ((Factorial r)*(Factorial (n-r)))
//calculates permutations
let Permutations n r =
(Factorial n)/ (Factorial (n-r))
//uses Euclids formula for the greatest common divisor
let rec GCD a b =
if b = 0UL then
a
else
GCD b (a%b)
//returns an array representing the binary version of x
let toBinary (x:uint64) =
let rec con (x:uint64) r =
if x = 0UL then
r
else
con (x/2UL) ([x%2UL] @ r)
con x []
// gets ticker price using yahoo
let GetTickerPrice (ticker:string) =
let url =
"http://download.finance.yahoo.com/d/quotes.csv?s="+
ticker+
"&f=sl1d1t1c1ohgv&e=.csv"
let wc = new WebClient()
let info = wc.DownloadString(url).Split([|','|])
float info.[1] // info.[1] is the current price will return 0.0 on invalid ticker
Link to this post!