Speaking in Code

Saturday, December 22, 2007

Learning F#

I heard about the new functional programming language, F#, recently by listening to Hanselminutes and .NET Rocks podcasts. It sounded interesting, and I am making a point of trying to broaden my exposure to multiple languages, so I bought a book, Foundations of F# by Apress, read a lot of it, and began to hatch a plan to write a new bingo program in F# for Silverlight and see if I can get it hosted on Silverstream.com.
For step one, I chose to learn how to work with arrays in F# so that I can replace the functionality I used SQL Server 2005 Express for in my first Bingo program. I also know that I need to work with random numbers, so my first project was to fill an array with truly random numbers.
Here's what I came up with in F# to work with the .NET cryptography class and a byte array:

#light

// open references to .NET namespaces used in the following code.
open System
open System.IO
open System.Text
open System.Security.Cryptography

(*
Initialize an RNGCryptoServiceProvider,which is a .NET Framework method capable of generating truly random numbers.
*)

let Gen = new RNGCryptoServiceProvider()

// Initialize a byte array with one value
let myByteArray:byte[] = [|0uy|]

// Define a function to load the byte array with a random byte
let funcRanNumArray x = Gen.GetBytes(x)

// Call the function, passing in the array. The array will be loaded by the GetBytes method.
funcRanNumArray myByteArray

// Print the results to the console
printfn "%u" myByteArray.(0)



Here is a screen shot of my output, after compiling my project, called LearnFSharp and running it from the command line:


1 Comments:

At 12:36 PM, Blogger Bop-op said...

As a brass instrument musician, I found that playing in F# was the most difficult key, since it had sharps on nearly every step of the scale. So it just makes the hair on the back of my neck stand up just to think of writing code in F#.

Seriously, it looks interesting, and I look forward to seeing where you go with this.

 

Post a Comment

<< Home