Pages

Thursday, March 15, 2012

F# on Windows Phone - Graphic Calculator

During the recent Seattle F# Meetup, I was asked how to do the windows phone calculator with F#. It is not hard provided you know F#.

The backbone of the calculator is a string parser. It can be written from scratch or use existing one. Since I want to get it into production and not prepare for an interview, I choose to use the existing yacc parser provided by F# powerpack. If I hook the back-end yacc parser with the front-end, the majority of the work is accomplished, the rest is to brush your yacc/lex knowledge. I choose use the C# XNA as front-end because I want to draw the function diagram later and am afraid Silverlight won't meet my requirement. You can use F# XNA as front-end, but this is not the main topic.

The whole solution has 4 projects. Two of them are XNA standard projects and two of them are F# ones. The  Calculator folder contains the yacc/lex file. I use the F# Parsed Language Starter to create the project. This project is for desktop application, you have to modify the project file by adding the  the import elements:
  
And XNA project settings:

    

The most important is to make sure the project references the FSharp.Core.dll for Windows Phone.
They are located under the "Dependencies" folder.
If you go to WindowsPhoneCalculator project and find the following line in the Game.cs
    var r = Calculator.readAndProcess("1+3*2");

if you stop at that line, the r is 7. The full code is here.




No comments: