Friday, July 25, 2008

F# for beginners

I'm trying to get some more breadth to my programming knowledge, so I decided to start looking into F# for some functional programming exposure.

So far, I'm liking what I'm going to call the brevity of the language. I'm not one of those people who thinks that programming languages ought to be made for the "Everyone" programmer, at least not all programming languages. It gives me the impression of condensing the programming down into little mouth-puckering shots of power, akin to some condensed tomato soup or something.

Anyway, to dig a little deeper into the language and actually try and solve problems I decided to try and do the beginner Scripting Games Events from this year in F#. There is already at least one post on another F# blog where someone is doing the first event.

I decided to try and limp through the second event, and here is what I came up with.

open System
open System.IO
open Microsoft.Win32

// Scripting Games Event 2, How many True Type Fonts installed.

// Open the registry key where fonts are stored, using .Net objects
let fontKey =

// Get the font names, convert to list
let vals = fontKey.GetValueNames() > Seq.to_list

// Defining a recursive "function" that takes a string to match and a list
of strings, returns num of matches
let rec matchEnd (srch : string) (list :
string List) =
match list with
[] -> 0 // Empty list
// The x and xs refer to the head(x) and tail(xs) of the list.
when x.Trim().EndsWith(srch) -> (1 + (matchEnd srch xs))
x::xs ->
matchEnd srch xs

// Print the true type fonts, number of fonts, and total fonts.
List.filter (fun (b : string) -> b.Trim().EndsWith("(TrueType)")) vals
> printfn "%A"
printfn "True Type Fonts Installed: %A" (matchEnd
"(TrueType)" vals)
printfn "Total Fonts Installed: %A" vals.Length

// Pause for exit

Sorry for the lack of formatting (which is actually important for the #light syntax). So I think that does the job for Event 2. I'm sure it could be better, but it's just a learning exercise so far.

No comments:

Post a Comment