SyntaxHighlighter

Wednesday, January 4, 2012

Functional Programming Topics Have Moved

From here on out all functional programming related posts can be found over at The Last Expression
Go check it out! :-)

Tuesday, August 2, 2011

Bringing F# to the Microsoft Surface Table














Within the last month or so Microsoft has dropped some really cool
SDK's for the public to try out. One of them is the Microsoft -
Surface 2.0 SDK & Runtime available here. Once you download
and install the tools and runtime you'll notice a few new applications
in your start menu. Input Simulator and Input Visualizer. These two
apps are designed to help you interact with your custom surface
application if your dev box is not touch enabled. Now that we
have the basics its a good time to figure out what you're going to build
to get familiar with the surface API's. Luckily, we have a few things
to help us get started. Existing WPF/Silverlight skills and a little sample
documentation. Anytime I start hacking against a new API I always look
for some sample code or quick start to get me going. Unfortunately, the
sample code at the link above has no support for F#. However we know
better. We know that anything C# or VB can do F# can do better. :-)
So let's fire up VS2010 and create an new F# console application using
the console application template. Once you've done that you'll need to
add the following references to your project. These references will make
the console application wpf & surface enabled.

System
System.Xaml
Microsoft.Surface
Microsoft.Surface.Core
Microsoft.Surface.Presentation
PresentationCore
PresentationFramework
WindowsBase

Now to tip our toes in the Surface SDK water. We'll start by creating a
simple Scatter View application which basically scatters a bunch of
images on the screen for the user to interact with. This is also the
recommended "first application" in the above documentation.


open System
open System.IO
open System.Windows.Media.Imaging
open System.Windows
open System.Windows.Controls
open Microsoft.Surface
open Microsoft.Surface.Presentation.Controls

let app = new Application()
let window =
     new SurfaceWindow(Title= "F# ScatterView Surface Demo",
                                                      AutoOrientsOnStartup = true)
(* scatter view control bound to windows folder - my pictures*)
let path = @"C:\Users\Public\Pictures\Sample Pictures"
let scatter = new ScatterView()
scatter.ItemsSource <-
        seq {
                 for f in Directory.GetFiles(path, "*.jpg") do
                     yield new Image(Source=
                                         new BitmapImage(Uri(f, UriKind.Relative)))
            }

window.Content <- scatter
[] ignore <| (app).Run window

As you can see from the code above the API is very similar to
WPF/Silverlight, their is however a gotcha that I experienced when
playing around with the API (which you may be able to see).

When creating a SurfaceWindow you must have an application instance
already created otherwise you can not create an instance of a
Surface Window. :-(
Other than that it is really just a matter of new'ing up controls specific
to surface and placing them on the window or user control as normal.
Also, it's worth mentioning that you can do all this in Xaml and still have
your logic in F#. :-)


-Sample screen shot-












Until next time...
-Develop with passion





Monday, June 13, 2011

The Lonely WAIF Project

The lonely waif project is a animation library written entirely in F#.
I'll just take a brief moment to explain the name. If you look up waif
on Wikipedia you'll find  that it's more or less defined as such:
waif (from the Old French guaif, stray beast)[1] is a living creature removed,
by hardship, loss or other helpless circumstance, from his original surroundings.
I like to think of this projects original surroundings as the C# version
and well, its lonely because I'm currently the only contributor and user. :)

At this point you're probably wondering a few things...
a) Why an animation library in F#?
b) Why not just use the C# library from F#?

Well, I already use the library in my C#/F# polyglot project at work.
It's nice and all, but I'm trying to reduce my code footprint.
And unfortunately this mixed support is not helping very much.
Besides, I'm working on a really clean and simple visualization
component which will allow me to visualize time series, having a way
to animate the interactivity of that time series would be even nicer.
Which brings us to the main reason why I'm doing it in F#.
Trying off the shelf reporting controls is nice until you want that
extra level of sophistication only to find yourself stuck. I really
want that google charting level of sophistication but I know I will
not come close to getting it with componentone charting controls.
After all, google is not using off the shelf charting controls. :)

Now that we understand the name of this library and the
motivation behind it, let's take a look at it.








If you head over to google code where the project is hosted you'll
find two F# projects.
1) The animation library
2) WPF test application which uses the library

Let's take a look at one of the sample snippets.

- Say you have a window with a simple rectangle shape on it
and you want to animate the rotation of the angle.
- Or maybe you want to simply move it across the screen.

Here's what the code might look like :

let uri = new System.Uri("/AnimationTest;component/MainView.xaml",
                                           UriKind.Relative)
let window =  Application.LoadComponent(uri) :?> Window
let animator = new Animator() // animation time!
(* Grab UIElements *)
let rect = window.FindName("rectangle") :?> Rectangle


(* ===== Rotate Rectangle ===== *)
let rtf = castAs(rect.RenderTransform).Children.[2] :?> RotateTransform
 (* Angle *)
(* DependencyObject - rotate transform *)
animator.AnimateDouble(rtf,
(* DependencyProperty *)
    RotateTransform.AngleProperty,
(* EventHandler - callback function *)
    null,
(* Duration - in milliseconds *)
    250.0,
(* Acceleration *)
   None,
(* Deceleration *) 
   None,
(* From *)
   None,
(* To *) 
   Some(90.0)) |> ignore)

(* ===== Translate Rectangle ===== *)
let ttf = castAs(rect.RenderTransform).Children.[0] :?> TranslateTransform
(* Y Axis *)
animator.AnimateDouble(ttf,
   TranslateTransform.YProperty,
   null,250.0,None,None,None,Some(90.0)) |> ignore)

There are a few more samples in the sample application but that's really
all there is to it. I use the C# library all the time for creating custom
controls and widgets to use in my WPF applications.
Now I get to use it in F#! Over time I'll be adding more to the library
so it has total parity with the C# library.

Enjoy!

Tuesday, June 7, 2011

Simple Data Visualization using F# & WPF/Silverlight

For several weeks now I've been getting back into Data Visualization
projects (on the weekends). I've also gone back to basics by re-reading
Ben Fry's Visualizing Data while sketching in Processing. Re-gaining the
data visualization perspective has helped me out recently in my WPF
application that I'm working on (day job). The scenario was quite simple
and I could have used any standard WPF control to solve the problem
but I wanted to do something that convey'd the data in a more obvious
way. So I went looking around the web for inspiration and came across
the following flowing data post.

 














The visualization above is (in my opinion) a great way to compare two
values of information to one another with out using standard controls.
In the above situation the two values are likes vs dislikes. Straight
away we can get a sense (as a end user) of how many people like a
video vs dislike a video based on color. In my WPF application I
need to do something similar. I need to show how many 3D geometric
objects on a particular 3D Model are being used in other parts
of the system vs how many 3D objects are not being used at all in other
parts of the system. So I thought to myself, how might I be able to pull
off the above visualization in WPF? I fired up blend and started sketching.
After about thirty minutes I came up with a similar yet simpler visualization.


























You can probably tell from the blend screen shots above
that we can use a simple gradient color to represent the
two values that we need to visualize for the user to
compare. So I tried creating a border with a large corner
radius of about 90 to get a circle that I can apply a border
gradient color to. Unfortunately I wasn't able to get the
effect that I wanted so I tried something simpler below
the border. I created a simple rectangle and applied the
gradient color to the fill of the rectangle. This allowed me
to visually pull off the similar effect in the flowing data post!
Now that I have a visual way to do this I just need to apply
the data so that the rectangle gradient changes dynamically.

#I "path to assemblies below (here)"

#r "PresentationFramework.dll"
#r "WindowsBase.dll"
#r "PresentationCore.dll"

open System
open System.Windows
open System.Windows.Shapes
open System.Windows.Media
open System.Windows.Controls

let r = new Random()
let total_count_of_all_objects = 4556

(* Helper functions - remember the (: byte) & (: float)
   is just annotation for the return type of the function *)
let to_byte (v: int) : byte = Convert.ToByte(v)
let to_float (v: int) : float = Convert.ToDouble(v)

let to_color (r: int) (g: int) (b: int) : Color =
    Color.FromRgb(r |> to_byte, g |> to_byte, b |> to_byte)


(* Tuple to hold total number of objects used in the 3D Model
(random) and total number of objects in the 3D Model *)
let used_total = (r.Next(2000,4556),total_count_of_all_objects)

(* Calculate the number of objects used relative to the total *)
let simulation_result (used_total: int * int): float =
    let used,total = used_total
    used * 100 / total |> to_float



let construct_visualization (used_total: int * int): Grid =
    (* Get simulation result and convert to value between 0 and 1
       for the gradient stops to understand *)
    let v = simulation_result used_total / 100.0
    let actual_color =  to_color 3 129 51
    let total_color =  to_color 255 5 5
    let start_point = new Point(0.0, -0.925) //gradient start point
    let end_point = new Point(1.0, - 0.893) // gradient end point
    let brush = new LinearGradientBrush(actual_color, total_color, start_point, end_point)
    let gradientStopColor1 = new GradientStop(actual_color, v)
    let gradientStopColor2 = new GradientStop(total_color, v)
    brush.GradientStops.Add gradientStopColor1
    brush.GradientStops.Add gradientStopColor2
 
    let rect = new Rectangle(Fill=brush)
    let grd = new Grid(Width=260.0, Height=30.0,
                       HorizontalAlignment=HorizontalAlignment.Center,
                       VerticalAlignment=VerticalAlignment.Center)

    grd.Children.Add rect |> ignore
    grd
                     
let shell = new Window(Width=300.0,Height=300.0)
let viz = construct_visualization used_total
shell.Content <- viz

[] ignore <| (new Application()).Run shell


It's worth noting that even though this was shown as a WPF sample it
could easily be applied to Silverlight, which is why I included it in the title
of the post. =)


F# is great for prototyping and executing ideas! 
Just seeing something on the web and hopping right
into Blend/VS2010 to execute an idea in about an 
hour is why I love this language on top of this platform.


Until next time...
-Develop with passion

Saturday, May 28, 2011

F#'n like a MLer

Dear reader, for those of you who have been following my tweets know
that I've been doing quite a bit of functional programming research
mainly in the ML family of functional languages, specifically Ocaml.
Greg Morriset
I've been learning a great deal about how to think and write like a functional programmer. So far the experience has been non-stop excitement and a lot of fun. In this post I want to take a break from the normal stuff related to how to do something in F# and share with you what I think is a more meaningful topic that I've recently learned from
Professor Greg Morrisett.
"How to Engineer a Function in ML"
It's worth noting that Greg has done an amazing job adapting this technique to ML from Matthias Felleisen who outlined this same technique in Scheme & Rackett which can be found in the classic book


Even though the topic says ML I can tell you that it directly applies to F#. As I discover ML like techniques I quickly move from the top level (Ocaml REPL) to FSI to ensure that it works and makes sense.

The formula or recipe for how to engineer a function is actually not that difficult... "It's almost brainless"
Let's take an example from Greg's lecture to help illustrate this technique:

Given a list of pairs of integers, produce the list of products of the pairs.
e.g., Given [ (2,3); (4,7);(5,2) ] return [6;28;10]

The formula consists of the following 4 steps :
Note: In plain English write down the input data and the output data of the function. 

1) "Write down the types" or the function signature
This can be done a couple of ways in F# 
a)  let rec prods ( l : (int * int)  list ) = 
(*explicit - type after the : is the return type of the function*)
b) let rec prods ( l: (int * int) list ) : int list = 

2) "Examine the inputs of the function and start tearing them apart."
"Decompose the problem in to sub problems (usually by matching)"
From our example above how do we tear apart a list?
In general its the same two ways a list is constructed.
Empty List [ ] or Cons : : "So we get two patterns - which is automatic"

Note: pattern matches can nest which is what allows us 
to tear apart the tuple on the head : : tail pattern match

let rec prods ( l: (int * int) list ) : int list =
    match l with
    | [ ] ->
    | (x,y) : : tail ->

It's worth noting here that the above code is completely type directed.
Meaning - we can look at the types and know exactly how to write
the implementation of the function which is to satisfy the two cases.
We know that the return type is a list so that really narrows our
search space for what the possible code will be.
We can almost tell right away that one of these cases is going to involve
an empty list and the other a cons.


let rec prods ( l: (int * int) list ) : int list = 
    match l with
    | [ ] -> [ ]
    | (x,y) : : tail ->  ? 1 : : ? 2

Again, by looking at the types we're able to determine that we need integers to satisfy the return type.
So for the head we need a way to take the pair and produce an int. 
Likewise for the tail we need a way to produce an int list.
"We need something that can give us an int list - which is prods".

3) Reconstruct the types relative to the output or return type of the function.

let rec prods ( l: (int * int) list ) : int list = 
    match l with
    | [ ] -> [ ]
    | (x,y) : : tail ->  (x * y) : : prods tail

4) Finally, test the function to determine correctness. 
Note: Don't forget to test the empty list case. This is analogous to writing a failing test in TDD. 

That's it! I've found this technique to be very pragmatic. 
Greg put it perfectly when he said that "Looking at the types
and thinking in terms of types really narrows your search space
for what code you need to write, that power makes it easier
to write functions".

To all the F# and ML hakers out there...
-Develop with Passion

Wednesday, April 20, 2011

Controlling Your Tunes In F#

Every so often I find myself in the interactive window while listening to iTunes in the background. Today I thought to myself "It would be really cool to change the track, mute the sound, or even rewind the track of a song in FSI." Conveniently enough iTunes allows us to generate a typed library out of the executable. There's a couple of ways to get at this library, you could use the visual studio command prompt and generate a typed library to store in some known location or you can let visual studio do it for you. I'm lazy so I opted for the latter. =)

To generate an iTunes library for consumption in F# using visual studio simply do the following:
1) create a new F# console application.
2) right + click references and add a new reference off the COM tab. We want the iTunes Type Library. I happen to have version 1.13 but you may have a newer version which is fine, go ahead an add the type library.















3) You can see from the screen shot above that the reference got added
and generated a typed library for us in the project bin or obj directory.
The name of the generated library is Interop.iTunesLib.dll


Now the fun begins, we can open a new F# script file
and dot into this library to see what it offers.
Below is the F# script file that I came up with.


#i @"path-to-dll-here"
#r "Interop.iTunesLib.dll"

open iTunesLib

(*** Grab a handle to iTunes ***)
let appcls = new iTunesAppClass()

(*** Play the current playlist ***)
appcls.Play()

(*** Shuffle the current playlist ***)
do appcls.CurrentPlaylist.Shuffle <- true

(*** Next Track  ***)
do applcs.NextTrack()
(*** Previous Track  ***)
do applcs.PreviousTrack()
(*** Back Track (Go back to the beginning of the track  ***)
do appcls.BackTrack()
(*** Sound Volume ***)
do appcls.SoundVolume <-75
(*** Pause ***)
do appcls.Pause()
(*** Rewind ***)
do appcls.Rewind()
(*** FastFoward ***)
do appcls.FastFoward()
(*** Co-worker interruption ***)
do appcls.Mute <- true

//Lets have some fun with tracks
(*** Helper function to play a track ***)
let play (track: IITTrack) = track.Play()

(*** Print out All tracks in current playlist ***)
do
    for item: IITTrack in appcls.CurrentPlaylist.Tracks do
        printf "%s \n" item.Name

(*** Retrieve track by name & play it ***)
do appcls.CurrentPlaylist.Tracks.ItemByName "Too Much" |> play

(*** Just found out about a new FP Podcast ***)
do appcls.SubscribeToPodcast("url-of-podcast-here")
(*** What's New on iTunes!? ***)
do appcls.GotoMusicStoreHomePage()


A couple of things worth noting here.
1) iTunes needs to be open and running before you can manipulate it.
2) The above script just scratches the surface of what's possible with communicating with iTunes.
You can also convert files,  tap into the browser and other operations
that you'd normally have to use the UI to do.
Personally I like staying in the fsharp interactive window. =)

-Develop with passion

Sunday, April 3, 2011

Exploring MongoHQ with F#

Recently, I've been working on a Silverlight 4 project which will hopefully go live soon.
This project started off nice and light as all green field projects do, and then the unavoidable requirement came up... storage. A few customers utter'd access. After I finished  laughing I thought to myself- maybe SQL?
So I turned to my data structure and immediately realized that its not structured for SQL. I've played around with a few object databases... db4o, ravendb, etc. Then I remembered Mongodb, over the past several years this object database has received quite a bit of attention. I must admit I haven't paid much attention to it, so I decided to give it a world. Headed over to the spot, read through some of the docs and realized I need essentially two dll's.
1) MongoDB.Bson.dll
2) MongoDB.Driver.dll

So I downloaded it and ran through the introduction tutorial.
After I got the Mongod server up and running on my local box I was able to store and retrieve some mock data (using the mongo client) with ease.  Now it was finally time to write some code and see it in action.
So, I fired up FSI and produced the simple F# script.

#I @"D:\ODev Solutions\MongoDb\CSharpDriver"
#r "MongoDB.Bson.dll"
#r "MongoDB.Driver"

open MongoDB.Bson
open MongoDB.Bson.Serialization
open MongoDB.Driver
open MongoDB.Bson.IO

// helper func insert name_value in Bson document
let Bson_NameValue (name,value) =
 new BsonElement(name,BsonValue.Create value)

// helper func get all keys in a Bson document
let getkeys (document: BsonDocument) =
    document.Names

(* Connect to Mongo Server *)
let connectionString = "mongodb://localhost"
let server = MongoServer.Create connectionString
server.Connect

(* Get Database - if it does not exists then one is created. *)
let test = server.GetDatabase "test"

(* Store usernames and passwords *)
let profilescollection = test.GetCollection "mockprofiles"

(* Create the mock structure that will store a single user profile *)
type profile = {UserName : string; Password : string; }
let p = { UserName = "someuser@somedomain.com"; Password = "password"; }

let convert_profile_to_BsonDocument (p: profile) =
     let d = new BsonDocument()
    d.Add(Bson_NameValue("UserName",p.UserName)) |> ignore
    d.Add(Bson_NameValue("Password",p.Password)) |> ignore
    d
let profilebson = convert_profile_to_BsonDocument p

(* Insert the mock profile into the newly created profiles collection *)
profilescollection.Insert profilebson

*Retrieve mock profile*

(* Mongodb Query Document - can think of it as a where clause *)
let qd = new QueryDocument(Bson_NameValue("UserName","someuser@somedomain.com"))

let mockprofile = profilescollection.FindOne(qd)
printf  "UserName: %s   Password: %s" mockprofile.UserName mockprofile.Password

Okay, all good right? Wait... if I'm going to use this as production solution how do I even go about deploying something like Mongodb? Do I look for a hosting account that knows about monogo? Do I look for a hosting account that will give me full access to the box so that I can run mongo and manage it myself? After some searching around I found MongoHQ.













The guys over at monogohq make it super simple to setup a production object database.
They charge monthly or annually based on the disk space you use. Starting at free accounts up to 16mb and then progressively goes up from there. I like this solution a lot because I don't have to think about the maintenance and they provide an admin portal so I can manage the database and get reports from their web interface. As for the code changes there was only one. the connection string. =)

example: mongodb://username:password@flame.mongohq.com:portnumber/databasename

If you're considering a project with an object database check out Mongodb and MongoHQ.
Really slick!