F# and SignalR Stock Ticker Example

I was looking at the server broadcast SignalR tutorial found here for a current project when I got to the StockTicker class.  In this class, the interesting code surrounds making a singleton instance because SignalR hubs are transient.  Here is the full text:

You’ll use the SignalR Hub API to handle server-to-client interaction. A StockTickerHub class that derives from the SignalR Hub class will handle receiving connections and method calls from clients. You also need to maintain stock data and run a Timer object to periodically trigger price updates, independently of client connections. You can’t put these functions in a Hub class, because Hub instances are transient. A Hub class instance is created for each operation on the hub, such as connections and calls from the client to the server. So the mechanism that keeps stock data, updates prices, and broadcasts the price updates has to run in a separate class, which you’ll name StockTicker.

So then it hit me – we need an immutable class that can handle multiple requests.  This sounds like a job for Captain F#!  Unfortunately, Captain F# is on vacation, so I went with Private 1st class F#.  So this is what I did.

I created an empty solution.  I then added in a C# Empty Web Application just to have a point of comparison to the FSharp project.  Then I added in a new F# MVC4 project from on the on-line template that Daniel Mohl created:

image

The problem is that the C# is the web app and the F# is just the controller.  Since I want a full-on double rainbow F# only MVC application, I tossed the template and just created a bare-bones F# project.  I then opened the .fsproj file and added a web ProjectType GUID (basically parroting what was in the .cs project file):

image

I posted this to stack overflow here.  So I am back to using C# as the Web application and F# as the plug in code.  I re-started with a couple of skeleton projects like so:

image

I then added a class for Stock like so:

  1. namespace Tff.SignalRServerBroadcast.FS
  2.  
  3. open System
  4.  
  5. type Stock() =
  6.     member val Symbol = String.Empty with get, set

 

I then added some unit tests to verify that I could create the Stock class and that I could assign the Symbol property:

  1. [TestClass]
  2. public class StockTests
  3. {
  4.     [TestMethod]
  5.     public void CreateStock_ReturnsValidInstance()
  6.     {
  7.         Stock stock = new Stock();
  8.         Assert.IsNotNull(stock);
  9.     }
  10.  
  11.     [TestMethod]
  12.     public void VerifyStockSymbolCanBeMutated()
  13.     {
  14.         Stock stock = new Stock();
  15.         stock.Symbol = "TEST";
  16.  
  17.         String notExpected = String.Empty;
  18.         String actual = stock.Symbol;
  19.  
  20.         Assert.AreNotEqual(notExpected, actual);
  21.     }
  22. }

 

And sure enough, they run green:

image

Just then, Captain F# swooped in from vacation and exclaimed “What are you doing?  The tenants of functional programming is immutability.  What happens if you change the Symbol after the object is created – does it really represent the same thing?  In fact, allowing the Symbol to be changed after it is created will lead to bugs and potentially unexpected behaviors in your system!”  With that, he left for a 10-day tour of the eastern Mediterranean.

I then changed the Stock class to be immutable like so:

  1. namespace Tff.SignalRServerBroadcast.FS
  2.  
  3. open System
  4.  
  5. type Stock =
  6.     {Symbol: String;
  7.      Price: Decimal;
  8.      DayOpen: Decimal;
  9.      }
  10.  
  11.      member x.GetChange () =
  12.         x.Price – x.DayOpen

 

and then updated my unit tests like so:

  1. [TestClass]
  2. public class StockTests
  3. {
  4.     [TestMethod]
  5.     public void CreateStock_ReturnsValidInstance()
  6.     {
  7.         Stock stock = new Stock("TEST", 10, 10.25M);
  8.         Assert.IsNotNull(stock);
  9.     }
  10.  
  11.     [TestMethod]
  12.     public void PriceChangeUsingValidNumbers_ReturnsCorrectChange()
  13.     {
  14.         Stock stock = new Stock("TEST", 10, 10.25M);
  15.         Decimal expected = .25M;
  16.         Decimal actual = stock.GetChange();
  17.         Assert.AreEqual(expected, actual);
  18.     }
  19. }

And then I ran my tests and got red

image

Ugh, I reversed the parameters – I intended to have the stock go up $.25.  Instead, the constructor expects the Price to come before the DayOpen.  This is not intuitive – you have implicit temporal coupleing in these parameters and since DayOpen occurs sooner in the space-time continuum, I reversed the parameters and the tests ran green:

  1. type Stock =
  2.     {Symbol: String;
  3.      DayOpen: Decimal;
  4.      Price: Decimal;
  5.      }

 

image

With that done, I looked at the last PercentChange  calculation.  The only thing remarkable about it is that the code in the on-line tutorial is incorrect.  The tutorial uses Price as the denominator, but my unit tests shows that it wrong:

  1. [TestMethod]
  2. public void PercentChangeUsingValidNumbers_ReturnsCorrectChange()
  3. {
  4.     Stock stock = new Stock("TEST", 10, 11M);
  5.     Decimal expected = .1M;
  6.     Decimal actual = stock.GetPercentChange();
  7.     Assert.AreEqual(expected, actual);
  8. }

 

image

If a stock goes from $10.00 to $11.00, it increases $1.00 and $1.00 divided by $10.00 is 10% – the stock increased 10%.

So I went back and changed the implementation to get the test to run green.

  1. member x.GetPercentChange() =
  2.     Math.Round(x.GetChange()/x.DayOpen,4)

 

image

 

So looking at this class, why is F# better than C#?

1) Less noise.  Compare the code between C# and F#

imageimage

All of the code in the Price setter is irrelevant.  In the F# implementation, you don’t need to worry about assigning DayOpen for the 1st time. 

 

2) Fewer Bugs: 

What happens if you are looking at Pets.com (IPET) on November 6, 2000 when it opened at $.16 and then went to $0.00 at noon when they finalized their liquidation?  You need to change your code b/c the C# implementation is wrong – the price was $0.00 and it was not the open price.

Also, what prevents me from changing the Symbol?  I could create a ticker class for APPL at $519 and then change the ticker to MSFT – volia MSFT’s price goes from $37.57 to $519.00!  And all of the unit tests for the Stock still run green.

3) More readable. 

Less noise – more signal (SignalR in fact)…

 

This blog post is getting a bit long so I will continue this project on another post.

Thanks to the RHCP, I listened to this 2-3 times when doing this blog post…

Advertisements

F#, Chain Of Responsibility, And High Ordered Functions

I was working though Tao Liu’s F# for C#  Developers book

image

when I got to the chapter on F# and Design Patterns.  This is a great chapter.    Typically F# books introduce the language from the language on out.  This chapter takes a different approach – it shows the language in action using commonly accepted design patterns.  I was working through the section on the Chain Of Responsibility pattern when I got to this code snippet

  1. let check f (record,result) =
  2.     if not result then record, false
  3.     else record, f(record)

 

Looking at the code, I get that we are assigning a function called check that has a tuple with record called ‘record” and a Boolean called ‘result’.  However, what is that ‘f’?  Basically, what the F is that f in F#?  Looking at the REPL results, I see that it was this signature:

image

Basically, f is a function called ‘f’ that I am passing in.  I am then invoking this function here:

  1. let chainOfResponsibility = check validAge >> check validHeight >> check validWeight
  2.  
  3. let test1 = {Name="Test"; Age=45; Weight=175.; Height=175.}
  4.  
  5. printfn "test result = %A" (chainOfResponsibility (test1, true) |> snd)

 

So this is an example, I think, of two language constructs.  The first is high ordered functions – where check takes in a function as a parameter.  Next, this is an example of currying – where chainOfResponsibility only passes in the function, not the tuple.  I think.

To further research this, I looked up Chain of Responsibility on Wikipedia and took a look at the C# example.  To do it the C# way, created 6 files

image

with each file having the implementation found on the Wikipedia article.  The Logger class defines the behavior:

  1. public abstract class Logger
  2. {
  3.     protected LogLevel logMask;
  4.     protected Logger next;
  5.  
  6.     public Logger(LogLevel mask)
  7.     {
  8.         this.logMask = mask;
  9.     }
  10.  
  11.     public Logger SetNext(Logger nextlogger)
  12.     {
  13.         next = nextlogger;
  14.         return nextlogger;
  15.     }
  16.  
  17.     public void Message(string msg, LogLevel severity)
  18.     {
  19.         if ((severity & logMask) != 0)
  20.         {
  21.             WriteMessage(msg);
  22.         }
  23.         if (next != null)
  24.         {
  25.             next.Message(msg, severity);
  26.         }
  27.     }
  28.  
  29.     abstract public void WriteMessage(string msg);
  30.  
  31. }

 

and the individual implementations in the classes:

  1. public class FileLogger : Logger
  2. {
  3.     public FileLogger(LogLevel mask)
  4.         : base(mask)
  5.     { }
  6.  
  7.     public override void WriteMessage(string msg)
  8.     {
  9.         //Placeholder for File writing logic
  10.         Debug.WriteLine("Writing to Log File: " + msg);
  11.     }
  12. }

What is interesting to me is the Logger.SetNext() method is used to move to the next implementation in the chain.  I then set to write the example in FSharp using Liu’s template.  I did this:

  1. type Logger() =
  2.     let LogToConsole logLevel =
  3.         //Implementation
  4.         true
  5.  
  6.     let LogToEmail logLevel =
  7.         //Implementation
  8.         true
  9.  
  10.     let LogToFile logLevel =
  11.         //Implementation
  12.         true
  13.  
  14.     let check f (logLevel, result) =
  15.         if not result then logLevel, false
  16.         else logLevel, f(logLevel)
  17.  
  18.     let chainOfResponsibility =
  19.         check LogToConsole >> check LogToEmail >> check LogToFile
  20.  
  21.     let mutable logLevel = LogLevel.None
  22.     member this.CurrentLogLevel with get() = logLevel
  23.                                 and set(v) = logLevel <- v
  24.  
  25.     member this.WriteMessage () =
  26.         chainOfResponsibility (logLevel,true) |> snd

So there are a couple of observations.

1) F# is more terse – and more readable

2) Instead of creating a MoveNext function, the chainOfResponsibility uses the >> operator to move to the next.

3) These 2 code bases are not functionally equivalent – I have to keep working on the F# one.

4) How much fun is F#?

 

2013 TRINUG Code Camp

All of my materials for my presentations can be found here.

Here are a couple of pictures from code camp.  The Eject-A-Bed presentation:

image

And the F# One:

image

 

My own impression is that the eject-a-bed presentation was just OK – I had network problems so people could not see it in action.  Also, the presentation was about PWMs and servos and I should have had one slide explaining what PWMs are and one slide explaining what servos are and how to program them.  There were about 10 people in that session.

The F# presentation also was OK+ – I had 30+ people in the room and there were some great comments/questions (esp from Jim Christopher).  I think I said “I don’t know” about 4-5 times over the hour and a half – which is better than trying to BS something.  At the end, 3 people said they were interested in doing a F#/Analytics SIG at TRINUG so perhaps we can get some critical mass going.

Finally, Lobbyguard was a sponsor so we had a kiosk in the lobby doing sign ins.  When the conference was over, I took the registrations and compared it to the people who signed into the kiosk.  Appx 50% of the registered people showed up.  There does not appear to be any correlation between when a person signed up and if they attended.

image

 

image

Also, here is the registrations by time (rounded to the nearest 15 minutes)

image

(The keynote started at 8AM and the 1st session was at 9AM)

Note that 60% of attendees where here by the keynote and 93% of our attendees where here by the 1st session.  We shut the kiosk down at 10:30 so there might have been some stragglers after that.  There are 2 possible action items coming out of this:

1) Should TRINUG start the code camp later so that more people attend the keynote (or put the keynote in the middle/end of the day)?

2) What should TRINUG do to increase the attended/registered ratio?  There was lots of food left over – which is a waste.  If you have an idea, just shoot me an email (jamie@tenfingersfree.com) or leave it on this blog.

Tech Jam and Team Islington Green

IslingtonGreen

 

So a couple of friends from TRINUG – Ian Cillay and David Green – invited me to join them at a 36 hour continuous code fest called Tech Jam. Tech Jam was put on Met Life and the Department of Veterans Affairs on Nov 1 and 2 in RTP. This team of 3 developers was joined by Ian Henshaw who helped with some primary data provision and much of the user story development. David handled the MongoDB part, Ian took care of the UI (Bootstrap and Knockout), and I did the analytics (F# and R) and security piece.

The problem domain was that the Veterans Administration has this format of medical records called Blue Button. Blue Button is an unstructured format which make typical parsing and analysis very difficult. Here is a sample:

clip_image002

Also, the VA wanted some kind of mutli-platform solution that a vet can use that can make sense of this data and allow him/her to provide it to a care giver when needed.

Some random thoughts about the contest:

  • MongoDB makes a lot of sense for the data because of it being so unstructured. Note that the VA has now introduced BlueButton+, which is XML format – so that is a step in the right direction. I was impressed how easy Mongo was to use and how powerful it is to tackle unstructured data – but note that even MongoDb still needs some kind of structure – just not xNF relational…
  • Bootstrap was awesome – we used an out of the box template and it was great to knock out an easy design.
  • F# made analytics and predictive analysis a snap. 
  • There were 15 teams registered, 10 actually presented at the end. There were 2 community teams (us and another), 1 high school team (awesome), and a bunch of corporate teams (Deutsche Bank, IBM, Tata(X3!), etc…).
  • One of the teams (Infusion) was a vendor for Met Life already (they worked on the wall project and the infinity project). Unsurprisingly, they won the grand prize.  My only comment on that is that civic/community hackers already view events like this with a skeptical eye – and this did nothing to help MetLife in the eyes of those kind of people – in fact probably did the opposite.
  • I was amazed by how many teams did not actually address the primary problems that the VA needed fixed.  The problems were taming unstructured data and presenting it in a platform-agnostic way.  Most teams used HTML5/Phonegap for req #2 – which is the easier one.  I think only 3 teams actually addressed requirement #1?
  • I am proud to say that my team did address both requirements.  As I sometimes say “I listen to two things in life: my wife and the requirements.  It goes better for me if I do that.”
  • Another team was from a company where the boss showed up on Saturday to present the team’s work. I guess that is the difference with a corporate hack-a-thon.  Also, you can tell the corporate teams because they had more powerpoint and less code in their final presentation.  Not that there is anything wrong with that….
  • The best line this weekend was when I asked a D level person at Metlife why no one at Metlife was retweeting my tweets with their hashtags (#techjam) and he said "we have a guy for that." Sure enough, they had 1 person who was their tweet guy.
  • MetLife really know how to put on a contest. The MC for this – Gary Hoberman – was awesome – a V-Level techie that really could communicate with the coders. The food was good (they took into account different dietary needs), the working space was good and the swag was useable.  Also, they had dev mentors circulating around the room, though they seemed to spend their time with other teams – so we didn’t interact with them.  They also had reps from MongoDB and MSFT helping out – which is great because we leaned on them for specific problems.

The problem with a code contest is that you have little time to learn from your fellow devs – it is pretty much heads down and check-in. In any event, the best part was hanging out great developers like Ian and David and working on a worthwhile project for our country’s vets.  At the end, it was a fun time and my team delivered that the VA can use to springboard into a real application.