<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://bloggingabout.net/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Vagif Abilov's blog on .NET : F#</title><link>http://bloggingabout.net/blogs/vagif/archive/tags/F_2300_/default.aspx</link><description>Tags: F#</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP2 (Build: 40407.4157)</generator><item><title>Mock framework challenges in F#</title><link>http://bloggingabout.net/blogs/vagif/archive/2010/08/04/mock-framework-challenges-in-f.aspx</link><pubDate>Wed, 04 Aug 2010 16:30:43 GMT</pubDate><guid isPermaLink="false">813b6dfd-644e-4573-a816-eebab56ba0d0:483846</guid><dc:creator>Vagif Abilov</dc:creator><slash:comments>7</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/rsscomments.aspx?PostID=483846</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/commentapi.aspx?PostID=483846</wfw:comment><comments>http://bloggingabout.net/blogs/vagif/archive/2010/08/04/mock-framework-challenges-in-f.aspx#comments</comments><description>&lt;p&gt;Getting mock framework API rigth is uneasy task. Mock framework designers don’t have as much freedom as designers of other libraries: the purpose of a mock framework is not to expose an arbitraty API (unknown at the time of mock framework design) and intercept it in a transarent way, so developers can use mocked object as they were using real instances.&lt;/p&gt;  &lt;p&gt;This is why API of modern mock frameworks is full of technique such as extension methods and lambda expressions. In addition these frameworks use so called fluent approach to API. Unfortunately such methods are not easily portable to other, especially non-imperative languages. Being fluent in one language does not mean fluent in the other one.&lt;/p&gt;  &lt;p&gt;I decided to try various mock frameworks with F#. I realized that their C#-friendly syntax will look in F# clumsy, but I coudl overcome it by writing small wrappers. What concerned me more is incomatibility of F# functional delegates and expressions comparing to C#. For my tests I’ve chosen a Zoo example listed in an &lt;a href="http://www.richard-banks.org/search/label/mocking" target="_blank"&gt;excellent series of blog posts&lt;/a&gt; by Richard Banks dedicated to mock framework comparison. Richard ran his comparison on free frameworks:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Rhino.Mocks &lt;/li&gt;    &lt;li&gt;NSubstitute &lt;/li&gt;    &lt;li&gt;Moq &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I’ve extended this set with two commercial products:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Typemock Isolator &lt;/li&gt;    &lt;li&gt;Telerick JustMock &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So far I only tried very basic mocking described in the &lt;a href="http://www.richard-banks.org/2010/07/mocking-comparison-part-1-basics.html" target="_blank"&gt;first post&lt;/a&gt; of Richard’s series: faking return value. As I expected, even such a simple operation became a challenge when executed from F# code. I managed to make tests work only for two and half frameworks. Below is a description of what I did and how it was possible to have half of success.&lt;/p&gt;  &lt;h3&gt;1. Rhino.Mocks: success&lt;/h3&gt;  &lt;p&gt;&lt;a href="http://ayende.com/projects/rhino-mocks.aspx" target="_blank"&gt;Rhino.Mocks&lt;/a&gt; is the most popular .NET mock framework. This was the test code that I wanted to port to F#:&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;[Test]
public void Return()
{
    var monkey = MockRepository.GenerateMock&amp;lt;IMonkey&amp;gt;();
    monkey.Stub(m =&amp;gt; m.Name).Return(&amp;quot;Spike&amp;quot;);

    var actual = monkey.Name;

    Assert.AreEqual(&amp;quot;Spike&amp;quot;, actual);
}&lt;/pre&gt;

&lt;p&gt;As you can see, “monkey” is used both as an instance of an object that implements IMoney interface (so we can call money.Name directly) and as an object exposing mocking API (so we can call a Stub method on it). This is achieved by using extension methods, and extension methods are language specific – being defined in C# code they are not available in F# as extensions. But they can be used from a static class where they are originally defined:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;[&amp;lt;Test&amp;gt;]
member this.Return() =
    let monkey = MockRepository.GenerateMock&amp;lt;IMonkey&amp;gt;()
    RhinoMocksExtensions.Stub&amp;lt;IMonkey, string&amp;gt;(monkey, fun m -&amp;gt; m.Name).Return(&amp;quot;Spike&amp;quot;);

    monkey.Name
    |&amp;gt; should equal &amp;quot;Spike&amp;quot;&lt;/pre&gt;

&lt;p&gt;The test works, but RhinoMocksExtensions class has not been meant to be exposed to general public, so I put it in a little wrapper:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;module FsMock.RhinoMocks

open Rhino.Mocks

type mock&amp;lt;&amp;#39;T when &amp;#39;T : not struct&amp;gt;() =

    let instance = MockRepository.GenerateMock&amp;lt;&amp;#39;T&amp;gt;()

    member this.Object = instance

module Mock =

    let arrange&amp;lt;&amp;#39;T, &amp;#39;R when &amp;#39;T : not struct&amp;gt; (f : (&amp;#39;T -&amp;gt; &amp;#39;R)) (r : &amp;#39;R) (m : mock&amp;lt;&amp;#39;T&amp;gt;) = 
        RhinoMocksExtensions.Stub&amp;lt;&amp;#39;T, &amp;#39;R&amp;gt;(m.Object, Function&amp;lt;&amp;#39;T, &amp;#39;R&amp;gt;(f)).Return(r)&lt;/pre&gt;

&lt;p&gt;Now I can rewrite the origianl test in a F# style:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;[&amp;lt;Test&amp;gt;]
member this.Return() =
    let monkey = mock&amp;lt;IMonkey&amp;gt;()
    monkey
    |&amp;gt; Mock.arrange (fun m -&amp;gt; m.Name) &amp;quot;Spike&amp;quot;
    let monkey = monkey.Object

    monkey.Name
    |&amp;gt; should equal &amp;quot;Spike&amp;quot;&lt;/pre&gt;

&lt;p&gt;Both the original and rewritten tests passed.&lt;/p&gt;

&lt;h3&gt;2. NSubstitute: success&lt;/h3&gt;

&lt;p&gt;&lt;a href="http://github.com/nsubstitute/NSubstitute" target="_blank"&gt;NSubstitute&lt;/a&gt; is a new kid on the block. The framework prioritizes simplicity over coverage of all possible mocking scenarios. Unlike other frameworks, NSubstitutes avoids using lambda expressions. This makes it easier to use in F#.&lt;/p&gt;

&lt;p&gt;Here’s the C# code using NSubstitute:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;[Test]
public void Return()
{
    var monkey = Substitute.For&amp;lt;IMonkey&amp;gt;();
    monkey.Name.Returns(&amp;quot;Spike&amp;quot;);

    var actual = monkey.Name;

    Assert.AreEqual(&amp;quot;Spike&amp;quot;, actual);
}&lt;/pre&gt;

&lt;p&gt;Like Rhino.Mocks, NSubstitute also uses extension methods, so porting the above test to F# results in the following code:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;[&amp;lt;Test&amp;gt;]
member this.Return() =
    let monkey = Substitute.For&amp;lt;IMonkey&amp;gt;()
    SubstituteExtensions.Returns(monkey.Name, &amp;quot;Spike&amp;quot;)

    monkey.Name
    |&amp;gt; should equal &amp;quot;Spike&amp;quot;&lt;/pre&gt;

&lt;p&gt;Again, I created a little helper to make syntax F# friendly:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;module FsMock.NSubstitute

open NSubstitute

type mock&amp;lt;&amp;#39;T when &amp;#39;T : not struct&amp;gt;() =

    let instance = Substitute.For&amp;lt;&amp;#39;T&amp;gt;()

    member this.Object = instance


module Mock =

    let arrange&amp;lt;&amp;#39;T, &amp;#39;R when &amp;#39;T : not struct&amp;gt; (f : (&amp;#39;T -&amp;gt; &amp;#39;R)) (r : &amp;#39;R) (m : mock&amp;lt;&amp;#39;T&amp;gt;) = 
        SubstituteExtensions.Returns&amp;lt;&amp;#39;R&amp;gt;(f(m.Object), r)&lt;/pre&gt;

&lt;p&gt;Now the test code looks identical to Rhino.Mocks example:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;[&amp;lt;Test&amp;gt;]
member this.Return() =
    let monkey = mock&amp;lt;IMonkey&amp;gt;()
    monkey
    |&amp;gt; Mock.arrange (fun m -&amp;gt; m.Name) &amp;quot;Spike&amp;quot;
    let monkey = monkey.Object

    monkey.Name
    |&amp;gt; should equal &amp;quot;Spike&amp;quot;&lt;/pre&gt;

&lt;p&gt;And the test passed!&lt;/p&gt;

&lt;p&gt;NB! I have deliberately unified mocking API when creating F# wrappers for different frameworks. Since F# API will be quite different from it’s C# counterpart, I didn’t want to multiply number of API sets. Instead I came up with a common and easy to understand set of names (“mock”, “arrange”) that is used in each wrapper.&lt;/p&gt;

&lt;h3&gt;3. Moq: half success&lt;/h3&gt;

&lt;p&gt;Now that sounds strange. A test should either succeed of fail. So what has happenned to Moq? Here’s the story.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://code.google.com/p/moq/" target="_blank"&gt;Moq&lt;/a&gt; is a second most popular framework after Rhino.Mocks, and it has pioneered act-arrange-assert API based on lambda-expressions. This is how the C# test looks when using Moq:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;[Test]
public void Return()
{
    var monkey = new Mock&amp;lt;IMonkey&amp;gt;();
    monkey.Setup(m =&amp;gt; m.Name).Returns(&amp;quot;Spike&amp;quot;);

    var actual = monkey.Object.Name;

    Assert.AreEqual(&amp;quot;Spike&amp;quot;, actual);
}&lt;/pre&gt;

&lt;p&gt;Although the expression “m =&amp;gt; m.Name” looks exactly like in Rhino.Mocks, there is a big difference behind. Rhino.Mocks uses Func&amp;lt;T&amp;gt; delegate, and Moq is based on LINQ expressions.&amp;#160; Working with such expressions in F# requires use of so called quotation expressions that should be converted to LINQ and then downcasted to a generic LINQ expression. The corresponding code looks quite criptic:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;[&amp;lt;Test&amp;gt;]
member this.Return() =
    let monkey = new Mock&amp;lt;IMonkey&amp;gt;()
    let expr = (&amp;lt;@@ System.Func&amp;lt;IMonkey, string&amp;gt;(fun (m : IMonkey) -&amp;gt; m.Name) @@&amp;gt;).ToLinq()
    monkey.Setup(expr :?&amp;gt; System.Linq.Expressions.Expression&amp;lt;System.Func&amp;lt;IMonkey, string&amp;gt;&amp;gt;).Returns(&amp;quot;Spike&amp;quot;);
    let monkey = monkey.Object

    monkey.Name
    |&amp;gt; should equal &amp;quot;Spike&amp;quot;&lt;/pre&gt;

&lt;p&gt;But this does not work. Here’s the output:&lt;/p&gt;

&lt;pre&gt;Test &amp;#39;MoqTests+MoqTests.Return&amp;#39; failed: System.NullReferenceException : Object reference not set to an instance of an object.
	at Moq.MethodCall.SetFileInfo()
	at Moq.MethodCall..ctor(Mock mock, Expression originalExpression, MethodInfo method, Expression[] arguments)
	at Moq.MethodCallReturn..ctor(Mock mock, Expression originalExpression, MethodInfo method, Expression[] arguments)
	at Moq.MethodCallReturn`2..ctor(Mock mock, Expression originalExpression, MethodInfo method, Expression[] arguments)
	at Moq.Mock.&amp;lt;&amp;gt;c__DisplayClass15`2.b__14()
	at Moq.PexProtector.Invoke[T](Func`1 function)
	at Moq.Mock.SetupGet[T1,TProperty](Mock mock, Expression`1 expression)
	at Moq.Mock.&amp;lt;&amp;gt;c__DisplayClass12`2.b__11()
	at Moq.PexProtector.Invoke[T](Func`1 function)
	at Moq.Mock.Setup[T1,TResult](Mock mock, Expression`1 expression)
	at Moq.Mock`1.Setup[TResult](Expression`1 expression)
	C:\Projects\NET\MockComparison\TempTests\MoqTests.fs(20,0): at MoqTests.MoqTests.Return()&lt;/pre&gt;

&lt;p&gt;So why half success then? Well, if I execute the same code from F# interactive window, it works!&lt;/p&gt;

&lt;pre&gt;&amp;gt; let monkey = new Mock&amp;lt;IMonkey&amp;gt;()
let expr = (&amp;lt;@@ System.Func&amp;lt;IMonkey, string&amp;gt;(fun (m : IMonkey) -&amp;gt; m.Name) @@&amp;gt;).ToLinq()
monkey.Setup(expr :?&amp;gt; System.Linq.Expressions.Expression&amp;lt;System.Func&amp;lt;IMonkey, string&amp;gt;&amp;gt;).Returns(&amp;quot;Spike&amp;quot;);
printfn &amp;quot;%s&amp;quot; monkey.Object.Name;;
Spike

val monkey : Mock&amp;lt;IMonkey&amp;gt;
val expr : Expression = m =&amp;gt; m.Name&lt;/pre&gt;

&lt;p&gt;Note the word “Spike” printed right after the line that begins with “printfn”. This is the output.&lt;/p&gt;

&lt;p&gt;So I don’t really have a clue why the same code works in F# interactive session but fails being compiled in an assembly. I may need to investigate some more.&lt;/p&gt;

&lt;h3&gt;4. Typemock Isolator: failure&lt;/h3&gt;

&lt;p&gt;Ironically, both commercial frameworks failed to be used with F#. The C# code that used to test Typemock Isolator looks like this:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;[Test]
public void Return()
{
    var monkey = Isolate.Fake.Instance&amp;lt;IMonkey&amp;gt;();
    Func&amp;lt;string&amp;gt; func = () =&amp;gt; monkey.Name;
    Isolate.WhenCalled(func).WillReturn(&amp;quot;Spike&amp;quot;);

    var actual = monkey.Name;

    Assert.AreEqual(&amp;quot;Spike&amp;quot;, actual);
}&lt;/pre&gt;

&lt;p&gt;Here&amp;#39;s the corresponding F# code:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;[&amp;lt;Test&amp;gt;]
member this.Return() =
    let monkey = Isolate.Fake.Instance&amp;lt;IMonkey&amp;gt;();
    Isolate.WhenCalled(System.Func&amp;lt;string&amp;gt;(fun ignore -&amp;gt; monkey.Name)).WillReturn(&amp;quot;Spike&amp;quot;);

    monkey.Name
    |&amp;gt; should equal &amp;quot;Spike&amp;quot;&lt;/pre&gt;

&lt;p&gt;This test fails with the following output:&lt;/p&gt;

&lt;pre&gt;Test &amp;#39;TypeMockTests+TypeMocksTests.Return&amp;#39; failed: TypeMock.TypeMockException : 

*** Cannot call Isolate.WhenCalled() with method group fake.Invoke. Try using Isolate.WhenCalled( () =&amp;gt; fake.Invoke()) instead
	at ec.a()
	at dm.b(Boolean A_0)
	at im.c(Boolean A_0)
	at im.a(Object A_0, Boolean A_1, Func`1 A_2, Action A_3, Action A_4, Action A_5)
	at im.c(Object A_0)
	at TypeMock.ArrangeActAssert.ExpectationEngine`1.a(TResult A_0)
	C:\Projects\NET\MockComparison\TempTests\TypeMockTests.fs(21,0): at TypeMockTests.TypeMocksTests.Return()&lt;/pre&gt;

&lt;p&gt;I described the problem to Typemock developers and was advised to try a different approach presented by Roy Osherove in &lt;a href="http://weblogs.asp.net/rosherove/archive/2009/10/23/typemoq-api.aspx" target="_blank"&gt;his blog post&lt;/a&gt;. Unfortunately the modified test still fails, although with a different exception.&lt;/p&gt;

&lt;h3&gt;5. JustMock: failure&lt;/h3&gt;

&lt;p&gt;JustMock is also a commercial product, and it’s API also lacked F# compatibility. This is the original C# code:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;[Test]
public void Return()
{
    var monkey = Mock.Create&amp;lt;IMonkey&amp;gt;();
    Mock.Arrange(() =&amp;gt; monkey.Name).Returns(&amp;quot;Spike&amp;quot;);

    var actual = monkey.Name;

    Assert.AreEqual(&amp;quot;Spike&amp;quot;, actual);
}&lt;/pre&gt;

&lt;p&gt;JustMock also uses LINQ expressions, so I had to use a similar trick to what I had to do with Moq:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;[&amp;lt;Test&amp;gt;]
member this.Return() =
    let monkey = Mock.Create&amp;lt;IMonkey&amp;gt;();
    let expr = (&amp;lt;@@ System.Func&amp;lt;string&amp;gt;(fun ignore -&amp;gt; monkey.Name) @@&amp;gt;).ToLinq()
    Mock.Arrange&amp;lt;string&amp;gt;(expr :?&amp;gt; System.Linq.Expressions.Expression&amp;lt;System.Func&amp;lt;string&amp;gt;&amp;gt;).Returns(&amp;quot;Spike&amp;quot;);

    monkey.Name
    |&amp;gt; should equal &amp;quot;Spike&amp;quot;&lt;/pre&gt;

&lt;p&gt;The code compiles and does not throw any expection during the execution. But the “Name” property is not set, so “should equal” assertion fails.&lt;/p&gt;

&lt;h3&gt;Conclusion: no offence, just exploring possibilities&lt;/h3&gt;

&lt;p&gt;One thing that I want to get straigh is that these tests say absolutely nothing about general design quality of respective mock frameworks. As I mentioned in the beginning, API design requirements of such frameworks require their developers to apply language-specific tricks to make mocking simple. So the fact that some API fits another programming language is more luck rather than conscious vision. Moreover, I only tried the simplest of a large variety of functions exposed by mock frameworks. A slightly more complicated scenario would fail all frameworks, I am sure.&lt;/p&gt;

&lt;p&gt;However, since more developers express interests in F# and start using it in their projects, I believe it’s time for mock frameworks developers to consider this new territory and extend their products to offer full suport for this exciting language.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://bloggingabout.net/aggbug.aspx?PostID=483846" width="1" height="1"&gt;</description><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/TypeMock/default.aspx">TypeMock</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/mocking/default.aspx">mocking</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/F_2300_/default.aspx">F#</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/Moq/default.aspx">Moq</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/NSubstitute/default.aspx">NSubstitute</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/Rhino.Mocks/default.aspx">Rhino.Mocks</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/JustMock/default.aspx">JustMock</category></item><item><title>Exploring Amazon S3 with F#</title><link>http://bloggingabout.net/blogs/vagif/archive/2010/07/15/exploring-amazon-s3-with-f.aspx</link><pubDate>Thu, 15 Jul 2010 20:51:54 GMT</pubDate><guid isPermaLink="false">813b6dfd-644e-4573-a816-eebab56ba0d0:483720</guid><dc:creator>Vagif Abilov</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/rsscomments.aspx?PostID=483720</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/commentapi.aspx?PostID=483720</wfw:comment><comments>http://bloggingabout.net/blogs/vagif/archive/2010/07/15/exploring-amazon-s3-with-f.aspx#comments</comments><description>&lt;h3&gt;Introduction&lt;/h3&gt;  &lt;p&gt;Traditional imperative languages teach developers that program code requires ceremony. You can’t just write a line and expect it to do something. When programming book writers explain how easy is it to display &amp;quot;Hello world&amp;quot; string in their favorite language, they actually start with an explanation that every call should be wrapped in a method, and the method typically takes some arguments etc. And of course they have to let beginners know how to compile the resulting program and how to execute it. Without all these steps the world won’t get its greeting.&lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;All these steps have valid reasons, but as a result development environment based on major imperative languages does not really encourage exploration. It’s best suited towards large scale development, but if a developer wants to have a quick look on something new, and he can’t proceed without creating a new project, then he will often postpone this work until he has enough time or enough reasons to go ahead.&lt;/p&gt;  &lt;p&gt;Luckily, there’ve always been alternatives to languages like C# or Java that worked better for rapid prototyping or technology exploration. One of the late additions is F#, and when I recently introduced myself to Amazon Simple Storage Service, I realized that if I need to get a quick overview of its programming facilities, using F# would be much more efficient than if write a test program in C#.&lt;/p&gt;  &lt;p&gt;The purpose of this article is to show how fast you can dig into low level details of an unknown technology using F#, and how little code you need to write. Therefore I keep the text of the article short, focusing just on the required steps. If you need more information about F# or Amazon S3, there’s plenty of books and articles available. Just google for them. Instead of numbering steps that I’ve gone through, I’ll provide timing information: I started the exercise at about 17:00 CET on July 15th. It took me about 45 minutes to display a picture extracted from my S3 bucket. And all code was written in F#.&lt;/p&gt;  &lt;h3&gt;17:00. Getting Amazon Web Services SDK&lt;/h3&gt;  &lt;p&gt;Amazon Web Services SDK, also known as AWS SDK is available at &lt;a href="http://aws.amazon.com/sdkfornet"&gt;http://aws.amazon.com/sdkfornet&lt;/a&gt;. Once downloaded, it’s installer copies binaries and samples, and optionally registers AWSSDK.dll in the GAC.&lt;/p&gt;  &lt;h3&gt;17:10. You can’t go wrong with Reflector&lt;/h3&gt;  &lt;p&gt;Before firing a Visual Studio F# session, I checked the content of the installed binaries and loaded into Red Gate .NET Reflector the only .NET assembly that I found: AWSSDK.dll. I could probably manage without it, but it would take longer time. After I created an S3 client session, I mostly relied on Intellisense support for F# in Visual Studio, but spending few minutes looking at namespaces and classes hinted me about entry points. For example, I assumed that I would need to create an instance of AmazonS3Client and probably use classes from Amazon.S3.Model.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/5428.Reflector_5F00_122E6CEB.jpg"&gt;&lt;img title="Reflector" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="675" alt="Reflector" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/8546.Reflector_5F00_thumb_5F00_68508966.jpg" width="429" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;h3&gt;17:15. Opening F# Interactive session&lt;/h3&gt;  &lt;p&gt;I started Visual Studio and immediately was able to use comparative advantage of F# environment. I didn’t have to create a project – in fact I didn’t know what kind of project I would need to create if I had to: should be a console application? Or maybe a Windows Form program? I didn’t know yet what to expect, all I wanted to get from an IDE is a notepad where I could write code lines and execute them one by one. So F# was a very good fit for my intention: I created a new F# script file and started sending individual lines to an FSI window. The first lines referenced AWSSDK and imported Amazon.S3 namespace that I expected to be useful (thanks Reflector):&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;#r &amp;quot;AWSSDK&amp;quot;
open Amazon.S3&lt;/pre&gt;

&lt;p&gt;Later I imported another namespace (Amazon.S3.Model), but these two lines above were enough to connect to Amazon S3 storage.&lt;/p&gt;

&lt;h3&gt;17:20. Connecting to Amazon S3 and accessing a bucket&lt;/h3&gt;

&lt;p&gt;The fun part began. My guess was that since AmazonS3Client class has a constructor with two string parameters, this is the one I should use and assign parameters to AWS key ID and secret key. F# Intellisense confirmed it. So here’s my first call to Amazon S3 in F# (I removed actual access key values).&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;let s3Client = new AmazonS3Client(&amp;quot;KEY-ID&amp;quot;, &amp;quot;SECRET-KEY&amp;quot;)&lt;/pre&gt;

&lt;p&gt;After a few seconds F# Interactive came with a response:&lt;/p&gt;

&lt;pre&gt;val s3Client : AmazonS3Client&lt;/pre&gt;

&lt;p&gt;Now I had a mighty client with many interesting methods to try. The next logical step would be to list available buckets. I had only one, so I could retrieve only the first element of the list.&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;let response = s3Client.ListBuckets()
response.Buckets&lt;/pre&gt;

&lt;p&gt;Here’s an FSI output:&lt;/p&gt;

&lt;pre&gt;val it : System.Collections.Generic.List =
  seq
    [Amazon.S3.Model.S3Bucket {BucketName = &amp;quot;abilov.com&amp;quot;;
                               CreationDate = &amp;quot;to, 15 jul 2010 10:17:18 GMT&amp;quot;;}]
&lt;/pre&gt;

&lt;p&gt;Great! This looked like a real thing. Encouraged with a quick success, I wanted to start retrieving the bucket contents.&lt;/p&gt;

&lt;h3&gt;17:25. Failed attempt to retrieve bucket objects&lt;/h3&gt;

&lt;p&gt;The bucket collection was wrapped in a sequence, so I only needed to get it’s head to obtain the only bucket I had at S3:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;let bucket = Seq.head response.Buckets&lt;/pre&gt;

&lt;p&gt;I thought in order to retrieve bucket objects, I had to send the obtained bucket to some method, but I was wrong. Actually I didn’t need to obtain a bucket at all – since I knew the name of the bucket, I could construct a ListObjectRequest from the name and send it to a ListObjects. But I didn’t know about it 5 minutes ago. Anyway, here’re new calls, to retrieve bucket objects – data files with images from our home photo gallery.&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;let request = new ListObjectsRequest(BucketName = bucket.BucketName)
let objects = s3Client.ListObjects(request)&lt;/pre&gt;

&lt;p&gt;Bang!!! Exception!&lt;/p&gt;

&lt;pre&gt;System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
---&amp;gt; System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
   at System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, Exception exception)
   at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
   at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)

(The rest of the call stack is skipped)&lt;/pre&gt;

&lt;p&gt;Now when I am writing this article, I am in fact glad that I had this problem. If everything went smooth, you might look at my timing information with a grain of disbelief: the guy probably knew what he was doing. No I didn’t! So I had to check around. Since the error came after so basic steps, I hoped that I wasn’t alone who experienced it, and luckily I was not. Several people complained at Amazon forum, and they were recommended a simple workaround in case they would accept using HTTP instead of HTTPS. And for the purpose of exploration it was just fine.&lt;/p&gt;

&lt;h3&gt;17:30. Connection to Amazon S3 revisited&lt;/h3&gt;

&lt;p&gt;Here’s an updated version of connection code, taking now two lines instead of one.&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;let s3Config = new AmazonS3Config(CommunicationProtocol = Protocol.HTTP)
let s3Client = new AmazonS3Client(&amp;quot;KEY-ID&amp;quot;, &amp;quot;SECRET-KEY&amp;quot;, s3Config)&lt;/pre&gt;

&lt;p&gt;Then I replayed the other two lines requesting bucket objects. And now I successfully received results:&lt;/p&gt;

&lt;pre&gt;    {AmazonId2 = &amp;quot;//VkK6Mb7Xe26pNPG7nt40GkYcp4GDyNV45I1E1mfZVCL67aak9/0Txmrk8X+JAE&amp;quot;;
     CommonPrefix = seq [];
     CommonPrefixes = seq [];
     Delimiter = null;
     Headers = seq
                 [&amp;quot;x-amz-id-2&amp;quot;; &amp;quot;x-amz-request-id&amp;quot;; &amp;quot;Transfer-Encoding&amp;quot;;
                  &amp;quot;Content-Type&amp;quot;; ...];
     IsTruncated = true;
     MaxKeys = &amp;quot;1000&amp;quot;;
     Metadata = seq [];
     Name = &amp;quot;abilov.com&amp;quot;;
     NextMarker = &amp;quot;private/photo/2005/2005-06-10-12 Elverum/IMG_6803.JPG&amp;quot;;
     Prefix = &amp;quot;&amp;quot;;
     RequestId = &amp;quot;3A27D1A4495A747A&amp;quot;;
     ResponseStream = null;
     S3Objects = seq {…}

     (The rest of results is skipped)&lt;/pre&gt;

&lt;h3&gt;17:35. Retrieving object data&lt;/h3&gt;

&lt;p&gt;I inspected the response and found the property that I needed: S3Objects. It was a collection of bucket objects representing the photo gallery files I uploaded to S3. Taking a further look at available AmazonS3Client methods I’ve found a method that I should use to retrieve an individual object: GetObject. It took an instance of GetObjectRequest. I first created a GetObjectRequest instance without assigning a Key property. But after receiving exception with error message about missing a key I corrected my mistake. Here’s a code that worked:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;let objectRequest = new GetObjectRequest(BucketName=bucket.BucketName, Key=&amp;quot;private/photo/2005/2005-01 Kolbotn/IMG_5645.JPG&amp;quot;)
let obj = s3Client.GetObject(objectRequest)&lt;/pre&gt;

&lt;p&gt;The &amp;quot;Key&amp;quot; property is just a file path within the bucket, so it’s easy to figure it out.&lt;/p&gt;

&lt;p&gt;I sent &amp;quot;obj&amp;quot; to an FSI window, and it printed it’s properties:&lt;/p&gt;

&lt;pre&gt;{AmazonId2 = &amp;quot;zUH8IaRglPSPQuC+8m5pzAR59paJTi/L5M1DnxNympp9HcU5RigrntS7NGvpxQQf&amp;quot;;
     ContentLength = 1138630L;
     ContentType = &amp;quot;image/jpeg&amp;quot;;
     ETag = &amp;quot;&amp;quot;ea02192ee842d3b1987a8de4ac879595&amp;quot;&amp;quot;;
     Headers = ?;
     Metadata = seq [&amp;quot;x-amz-meta-cb-modifiedtime&amp;quot;];
     RequestId = &amp;quot;A93CF70A966E4A56&amp;quot;;
     ResponseStream = System.Net.ConnectStream;
     ResponseXml = null;
     VersionId = null;}&lt;/pre&gt;

&lt;p&gt;One of the properties was called ReponseStream. This sounded very promising – perhaps I could try to create an image out of this stream and display it in a Windows Form?&lt;/p&gt;

&lt;h3&gt;17:40. Displaying an image&lt;/h3&gt;

&lt;p&gt;What should you do if you want to display an image in a Windows Form in C#? You have to start from creating a new project using Windows Forms Application template. Then you can edit form class and add an Image control to it in a Form designer. How do you do it in F#? You simply create a form with an image right from the script. Here’s the code:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;#r &amp;quot;System.Drawing&amp;quot;
#r &amp;quot;System.Windows.Forms&amp;quot;
 
open System.Windows.Forms
open System.Drawing

let img = Image.FromStream(obj.ResponseStream)
let frm = new Form(ClientSize = img.Size)
frm.Paint.Add(fun e -&amp;gt; e.Graphics.DrawImage(img, new Point(0,0)))
frm.Show()&lt;/pre&gt;

&lt;p&gt;Note that first four lines are just to reference required DLLs and import namespaces. The rest of the code is equally short and complete the task. Look at the Image.FromStream call: I wasn’t quite sure I could do this, but the property name &amp;quot;ResponseStream&amp;quot; was too tempting not to give it a try. And suddenly I saw this window:&lt;/p&gt;

&lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/6888.Figaro_5F00_622BCD7C.jpg"&gt;&lt;img title="Figaro" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="474" alt="Figaro" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/4784.Figaro_5F00_thumb_5F00_46202FF3.jpg" width="630" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;This is our house cat Figaro (unfortunately not with us anymore). And no, I didn’t specifically select this photo for my test. This was a random choice, perhaps hinting about what kind of pictures some families tend to take.&lt;/p&gt;

&lt;h3&gt;17:45. Done!&lt;/h3&gt;

&lt;p&gt;Yes, we are! Perhaps just to show my environmentalist attitude, I’ll make one last call:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;s3Client.Dispose()&lt;/pre&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;So it was three quarters of exploration. Completely new API, combined with my relatively poor experience with Amazon S3, but a picture from a family photo gallery retrieved from an S3 bucket and shown in a Windows form proves that we managed the full stack of operations. All done in F#. This experiment does not expose other (and far more important) language qualities, but I deliberately wanted to focus on a different topic: language efficiency for the purpose of technology exploration and rapid prototyping. Being .NET language, F# can access any .NET area or feature, and its REPL support ensures that developer’s time is spent in a most optimal way.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://bloggingabout.net/aggbug.aspx?PostID=483720" width="1" height="1"&gt;</description><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/F_2300_/default.aspx">F#</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/Amazon+S3/default.aspx">Amazon S3</category></item><item><title>Symbolic calculation in F#. Part 3: parsing and formatting expressions</title><link>http://bloggingabout.net/blogs/vagif/archive/2010/06/11/symbolic-calculation-in-f-part-3-parsing-and-formatting-expressions.aspx</link><pubDate>Fri, 11 Jun 2010 08:24:00 GMT</pubDate><guid isPermaLink="false">813b6dfd-644e-4573-a816-eebab56ba0d0:483514</guid><dc:creator>Vagif Abilov</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/rsscomments.aspx?PostID=483514</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/commentapi.aspx?PostID=483514</wfw:comment><comments>http://bloggingabout.net/blogs/vagif/archive/2010/06/11/symbolic-calculation-in-f-part-3-parsing-and-formatting-expressions.aspx#comments</comments><description>&lt;p&gt;NB! For some strange reason some sample code for this post was rejected by the server with “BLOCKED EXPRESSION” error. After several attempts to fix the problem, I converted code snippets to images. All three blog posts are combined now in an &lt;a href="http://www.codeproject.com/KB/net-languages/SymbolicCalcInFS.aspx" target="_blank"&gt;article that is published at CodeProject&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;The &lt;a href="http://bloggingabout.net/blogs/vagif/archive/2010/06/08/symbolic-calculation-in-f-part-1-derivatives.aspx" target="_blank"&gt;first post&lt;/a&gt; about symbolic calcutaion in F# showed how to calculate derivatives, and the &lt;a href="http://bloggingabout.net/blogs/vagif/archive/2010/06/08/symbolic-calculation-in-f-part-2-simplifying-algebraic-expressions.aspx" target="_blank"&gt;sequel&lt;/a&gt; demonstrated how the algebraic expressions can be simplified. Still, the most natural would be to write expressions in plain text, so the program could take an input like “sin(x ^ 2)” and generate an output “2 * x * cos(x ^ 2)”.&lt;/p&gt;  &lt;p&gt;Let’s see how this can be approached with F#. We start with a formatter – formatting is usually easier than parsing. First we define a couple of helper functions to format operators and function names:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/7266.Code1_5F00_4AEB13DE.jpg"&gt;&lt;img title="Code1" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="229" alt="Code1" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/1541.Code1_5F00_thumb_5F00_4D279C9A.jpg" width="495" border="0" /&gt;&lt;/a&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Then the rough implementation of the expression formatter does not take many lines of code:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/0525.Code2_5F00_4CBB69A5.jpg"&gt;&lt;img title="Code2" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="125" alt="Code2" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/5417.Code2_5F00_thumb_5F00_3353666B.jpg" width="711" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;There is only one problem with this code: it always surrounds algebraic operations with parenthesis, and this is only necessary in case the expression is contained in an outer expression. This is an example of redundant parenthesis:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/4237.Output1_5F00_54E66182.jpg"&gt;&lt;img title="Output1" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="79" alt="Output1" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/2337.Output1_5F00_thumb_5F00_3B7E5E48.jpg" width="380" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;It’s not complicated however to modify the original code, so it does not embrace top-level expressions with parenthesis:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/4744.Code3_5F00_47D8B5E9.jpg"&gt;&lt;img title="Code3" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="206" alt="Code3" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/4670.Code3_5F00_thumb_5F00_0A4B5820.jpg" width="787" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Now we’re getting nice-looking output:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/8103.Output2_5F00_1E0C0D3C.jpg"&gt;&lt;img title="Output2" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="239" alt="Output2" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/4188.Output2_5F00_thumb_5F00_4B8D2CFF.jpg" width="527" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Satisfied with expression formatting, we can now proceed with expression parsing which appeared to be a more challenging tasks. First we need a tokenizer that would convert an input string into a list of tokens – atoms that will be building blocks of the resulting expression. Here is a simple tokenizer:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/7028.Code4_5F00_689036F1.jpg"&gt;&lt;img title="Code4" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="203" alt="Code4" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/4101.Code4_5F00_thumb_5F00_45CEFF34.jpg" width="642" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/8103.Output2_5F00_1E0C0D3C.jpg"&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/5672.Output3_5F00_7C3FB136.jpg"&gt;&lt;img title="Output3" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="65" alt="Output3" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/5482.Output3_5F00_thumb_5F00_1BEE8AFF.jpg" width="824" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;The tokenizer includes one rule that is specific for processing exponential functions (e ^ x). Unlike other functions (log, sin, cos), the exponent uses power operator notation, so adding proper support for it would devote large part of the post series just to this specific case. So I made a light constraint on use of exponent: its argument is always enclosed in parenthesis (so the input string should look like “e ^ (x)”, not “e ^ x”, and during the tokenization process the expression is converted into notation similar to other functions: e(x). So when proceeding with expression parsing, we won’t need to handle exponential functions in a special way.&lt;/p&gt;  &lt;p&gt;Next step is to eleminate parenthesis and divide tokens into groups, each group representing a trivial expression construct. For example, an expression “(2 + x) * (5 - x) can be split into groups containing expressions “2 + x”, “5 – x” and the operator “*” binding them together. We achive this in a few steps: first by assigning each token a level (incremented with each opening parentheses and decremeneted with a closing parentheses), and then by putting contiguous tokens with the same level in a list. Here is the code that handles these operations and an example of its use:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/3716.Code5_5F00_37CC77E3.jpg"&gt;&lt;img title="Code5" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="207" alt="Code5" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/8267.Code5_5F00_thumb_5F00_654D97A6.jpg" width="681" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/6266.Output4_5F00_2D427609.jpg"&gt;&lt;img title="Output4" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="133" alt="Output4" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/1565.Output4_5F00_thumb_5F00_56B947FA.jpg" width="797" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;We will also need some auxilliary functions: to test if a string represent an operator or a function, a couple of active pattern definitions to match numeric constants and variables, and methods to apply parsed operators or functions to expressions that they bind:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/7077.Code6_5F00_59B7DA67.jpg"&gt;&lt;img title="Code6" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="655" alt="Code6" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/3056.Code6_5F00_thumb_5F00_4E221D28.jpg" width="547" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;With supporting stuff in place, here’s the code that converts text input into expression trees:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/8176.Code7_5F00_043A67BE.jpg"&gt;&lt;img title="Code7" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="715" alt="Code7" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/8623.Code7_5F00_thumb_5F00_58899DC1.jpg" width="1018" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;Now it’s just to test how this all works:&lt;/p&gt;  &lt;p&gt;&lt;a href="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/4431.Output5_5F00_1370D08B.jpg"&gt;&lt;img title="Output5" style="border-top-width:0px;display:inline;border-left-width:0px;border-bottom-width:0px;border-right-width:0px;" height="377" alt="Output5" src="http://bloggingabout.net/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/vagif.metablogapi/4011.Output5_5F00_thumb_5F00_439AABFF.jpg" width="608" border="0" /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;So we’re done: we can now enter math expressions in plain text and obtain results of symbolic derivative calculation also in plain text. All in F#!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://bloggingabout.net/aggbug.aspx?PostID=483514" width="1" height="1"&gt;</description><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/functional+programming/default.aspx">functional programming</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/F_2300_/default.aspx">F#</category></item><item><title>Symbolic calculation in F#. Part 2: simplifying algebraic expressions</title><link>http://bloggingabout.net/blogs/vagif/archive/2010/06/08/symbolic-calculation-in-f-part-2-simplifying-algebraic-expressions.aspx</link><pubDate>Tue, 08 Jun 2010 19:54:55 GMT</pubDate><guid isPermaLink="false">813b6dfd-644e-4573-a816-eebab56ba0d0:483478</guid><dc:creator>Vagif Abilov</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/rsscomments.aspx?PostID=483478</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/commentapi.aspx?PostID=483478</wfw:comment><comments>http://bloggingabout.net/blogs/vagif/archive/2010/06/08/symbolic-calculation-in-f-part-2-simplifying-algebraic-expressions.aspx#comments</comments><description>&lt;p&gt;In the &lt;a href="http://bloggingabout.net/blogs/vagif/archive/2010/06/08/symbolic-calculation-in-f-part-1-derivatives.aspx" target="_blank"&gt;previous post&lt;/a&gt; we have shown an F# program that calculates derivatives. It has a room for improvement in its presentation part: resulting expressions often can be rewritten in a simpler form, and F# suits very well to solve such task.&lt;/p&gt;  &lt;p&gt;We will be using the same set of expression primitives and active pattern helpers “Op” and “Func”:&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;type Expression =
    | X
    | Const of float
    | Neg of Expression
    | Add of Expression * Expression
    | Sub of Expression * Expression
    | Mul of Expression * Expression
    | Div of Expression * Expression
    | Pow of Expression * Expression
    | Exp of Expression
    | Log of Expression
    | Sin of Expression
    | Cos of Expression

let (|Op|_|) (x : Expression) =
    match x with
    | Add(e1, e2) -&amp;gt; Some(Add, e1, e2)
    | Sub(e1, e2) -&amp;gt; Some(Sub, e1, e2)
    | Mul(e1, e2) -&amp;gt; Some(Mul, e1, e2)
    | Div(e1, e2) -&amp;gt; Some(Div, e1, e2)
    | Pow(e1, e2) -&amp;gt; Some(Pow, e1, e2)
    | _ -&amp;gt; None

let (|Func|_|) (x : Expression) =
    match x with
    | Exp(e) -&amp;gt; Some(Exp, e)
    | Log(e) -&amp;gt; Some(Log, e)
    | Sin(e) -&amp;gt; Some(Sin, e)
    | Cos(e) -&amp;gt; Some(Cos, e)
    | _ -&amp;gt; None&lt;/pre&gt;

&lt;p&gt;Now we define a recursive function Simplify that converts an input of Expression type to an output of the same type attempting to rewrite an expression in a simpler form. Like with Derivative function, the definition is a list of rules rather than a sequential algorithm:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;let rec Simplify x : Expression =
    match x with
    | Add(Const(n1), Const(n2)) -&amp;gt; Const(n1 + n2)
    | Sub(Const(n1), Const(n2)) -&amp;gt; Const(n1 - n2)
    | Mul(Const(n1), Const(n2)) -&amp;gt; Const(n1 * n2)
    | Div(Const(n1), Const(n2)) -&amp;gt; Const(n1 / n2)
    | Neg(Const(0.)) -&amp;gt; Const(0.)
    | Neg(Neg(e)) -&amp;gt; e |&amp;gt; Simplify
    | Add(e, Const(0.)) -&amp;gt; e |&amp;gt; Simplify
    | Add(Const(0.), e) -&amp;gt; e |&amp;gt; Simplify
    | Add(Const(n), e) -&amp;gt; Add(e, Const(n)) |&amp;gt; Simplify
    | Add(e1, Neg(e2)) -&amp;gt; Sub(e1, e2) |&amp;gt; Simplify
    | Add(Neg(e1), e2) -&amp;gt; Sub(e2, e1) |&amp;gt; Simplify
    | Sub(e, Const(0.)) -&amp;gt; e |&amp;gt; Simplify
    | Sub(Const(0.), e) -&amp;gt; Neg(e) |&amp;gt; Simplify
    | Mul(e, Const(1.)) -&amp;gt; e |&amp;gt; Simplify
    | Mul(Const(1.), e) -&amp;gt; e |&amp;gt; Simplify
    | Mul(e, Const(0.)) -&amp;gt; Const(0.)
    | Mul(Const(0.), e) -&amp;gt; Const(0.)
    | Mul(e, Const(n)) -&amp;gt; Mul(Const(n), e) |&amp;gt; Simplify
    | Mul(Div(Const(n), e1), e2) -&amp;gt; Mul(Const(n), Div(e2, e1)) |&amp;gt; Simplify
    | Mul(e1, Div(Const(n), e2)) -&amp;gt; Mul(Const(n), Div(e1, e2)) |&amp;gt; Simplify
    | Mul(Neg(e1), e2) -&amp;gt; Neg(Mul(e1, e2)) |&amp;gt; Simplify
    | Mul(e1, Neg(e2)) -&amp;gt; Neg(Mul(e1, e2)) |&amp;gt; Simplify
    | Div(Const(0.), e) -&amp;gt; Const(0.)
    | Div(e, Const(1.)) -&amp;gt; e |&amp;gt; Simplify
    | Div(Neg(e1), e2) -&amp;gt; Neg(Div(e1, e2)) |&amp;gt; Simplify
    | Div(e1, Neg(e2)) -&amp;gt; Neg(Div(e1, e2)) |&amp;gt; Simplify
    | Pow(Const(0.), e) -&amp;gt; Const(0.)
    | Pow(Const(1.), e) -&amp;gt; Const(1.)
    | Pow(e, Const(0.)) -&amp;gt; Const(1.)
    | Pow(e, Const(1.)) -&amp;gt; e |&amp;gt; Simplify
    | Op (op, e1, e2) 
        -&amp;gt;
        let e1s = Simplify e1
        let e2s = Simplify e2
        if e1s &amp;lt;&amp;gt; e1 || e2s &amp;lt;&amp;gt; e2 then
            op(Simplify e1, Simplify e2) |&amp;gt; Simplify
        else
            op(e1, e2)
    | _ -&amp;gt; x&lt;/pre&gt;

&lt;p&gt;The set of rules is not complete. For example, there is no rule to rewrite “2 * (3 + X)” as “6 + 2*X”, but it should be enough to eliminate most obvious redundancies, such as multiplication by one and zero addition. So if we can fire F# interactive window, we can test how it works:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;&amp;gt; let s = Simplify(Add(Mul(Const 0., X), Mul(Const 5., Const 1.)));;

val s : Expression = Const 5.0&lt;/pre&gt;

&lt;p&gt;What we can do now is extend the Derivative function written in the previous post, so it can take advantage of our new Simplify function:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;let rec Derivative x : Expression =
    let y =
        match x with
        | X -&amp;gt; Const(1.)
        | Const(n) -&amp;gt; Const(0.)
        | Neg(e) -&amp;gt; Neg(Derivative(e))
        | Add(e1, e2) -&amp;gt; Add(Derivative(e1), Derivative(e2))
        | Sub(e1, e2) -&amp;gt; Sub(Derivative(e1), Derivative(e2))
        | Mul(e1, e2) -&amp;gt; Add(Mul(Derivative(e1), e2), Mul(e1, Derivative(e2)))
        | Pow(e, Const(n)) -&amp;gt; Mul(Const(n), Pow(e, Const(n-1.)))
        | Exp(X) -&amp;gt; Exp(X)
        | Log(X) -&amp;gt; Div(Const(1.), X)
        | Sin(X) -&amp;gt; Cos(X)
        | Cos(X) -&amp;gt; Neg(Sin(X))
        | Func(g, f) -&amp;gt; 
            let dg = Derivative(g(X))
            let df = Derivative(f)
            match dg with
            | Func(dgf, dge) -&amp;gt; Mul(dgf(f), df)
            | Op (op, e1, e2) -&amp;gt; Mul(op(e1, e2), df)
            | _ -&amp;gt; failwith(sprintf &amp;quot;Unable to match compound function [%A]&amp;quot; dg)
        | _ -&amp;gt; failwith(sprintf &amp;quot;Unable to match expression [%A]&amp;quot; x)
    Simplify y&lt;/pre&gt;
Now let&amp;#39;s test what we have by calculating derivative for various functions: 

&lt;pre class="brush: csharp;"&gt;&amp;gt; let d1 = Derivative(Add(Mul(Const(5.), X), Const(3.)))
let d2 = Derivative(Add(Pow(X, Const(3.)), Const(3.)))
let d3 = Derivative(Sin(Mul(Const(2.), X)))
let d4 = Derivative(Log(Mul(Const(2.), X)))
let d5 = Derivative(Exp(Mul(Const(2.), X)))
let d6 = Derivative(Exp(Pow(X, Const(2.))))
let d7 = Derivative(Log(Sin(X)))
let d8 = Derivative(Log(Cos(X)));;

&amp;gt; 
val d1 : Expression = Const 5.0
val d2 : Expression = Mul (Const 3.0,Pow (X,Const 2.0))
val d3 : Expression = Mul (Const 2.0,Cos (Mul (Const 2.0,X)))
val d4 : Expression = Div (Const 2.0,X)
val d5 : Expression = Mul (Const 2.0,Exp (Mul (Const 2.0,X)))
val d6 : Expression = Mul (Exp (Pow (X,Const 2.0)),Mul (Const 2.0,X))
val d7 : Expression = Div (Cos X,X)
val d8 : Expression = Neg (Div (Sin X,X))&lt;/pre&gt;

&lt;p&gt;Can we improve anything? Well, maybe… Since it’s getting so easy, why not set an ultimate goal: present input and output as a plain text, not as Expression items. So we can pass “log(cos(x))” and get back “-sin(x)/x”. I guess this will be slightly more work to achieve, but should be fun once we get there. In the next part.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://bloggingabout.net/aggbug.aspx?PostID=483478" width="1" height="1"&gt;</description><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/functional+programming/default.aspx">functional programming</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/F_2300_/default.aspx">F#</category></item><item><title>Symbolic calculation in F#. Part 1: derivatives</title><link>http://bloggingabout.net/blogs/vagif/archive/2010/06/08/symbolic-calculation-in-f-part-1-derivatives.aspx</link><pubDate>Tue, 08 Jun 2010 18:59:51 GMT</pubDate><guid isPermaLink="false">813b6dfd-644e-4573-a816-eebab56ba0d0:483477</guid><dc:creator>Vagif Abilov</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/rsscomments.aspx?PostID=483477</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/commentapi.aspx?PostID=483477</wfw:comment><comments>http://bloggingabout.net/blogs/vagif/archive/2010/06/08/symbolic-calculation-in-f-part-1-derivatives.aspx#comments</comments><description>&lt;p&gt;I am learning F#, and one of the best areas to use a functional language is to apply it to symbolic calculations. Like evaluating function derivatives. I remember how I was impressed many years ago when I looked at a program in Prolog that occupied not more than one computer screen but could tell me that derivative of sin(x) was cos(x). So I wanted to do the same in F#.&lt;/p&gt;  &lt;p&gt;If you ask a developer who is only using procedural languages to write a program that calculates derivatives in a symbolic form, chances are pretty good that he will start with parsing input strings. That’s the nature of procedural languages: you solve a task by building a sequence of steps that it takes to convert input to output. A developer focusing on a higher level abstraction migh start with building classes for expression trees, so he can implement derivative calculation on the top of them. But what derivative calculation has with creating classes to store tree nodes? Why should we care?&lt;/p&gt;  &lt;p&gt;In procedural languages we need to care. As Niklaus Wirth stated in his book title, &lt;a href="http://www.amazon.com/Algorithms-Structures-Prentice-Hall-Automatic-Computation/dp/0130224189" target="_blank"&gt;&amp;quot;Algorithms + Data Structures = Programs&amp;quot;&lt;/a&gt;. So we express our imperative programs in algorithms and apply them to data structures.&lt;/p&gt;  &lt;p&gt;With F# it’s completely different. You simply describe your domain, your rules. And things just happens…&lt;/p&gt;  &lt;p&gt;So we’ll do derivatives. First we need to define the scope of our calculations, our symbols. Note that Expression type doesn’t define a data structure – it’s just a collection of symbols that we will be using to form functional expressions.&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;type Expression =
    | X
    | Const of float
    | Neg of Expression
    | Add of Expression * Expression
    | Sub of Expression * Expression
    | Mul of Expression * Expression
    | Div of Expression * Expression
    | Pow of Expression * Expression
    | Exp of Expression
    | Log of Expression
    | Sin of Expression
    | Cos of Expression&lt;/pre&gt;

&lt;p&gt;What we just declared is called in F# &lt;em&gt;discriminated union&lt;/em&gt;. I won’t be spending time on F# syntax details, I am learning F# from two great books: &lt;a href="http://www.amazon.com/Programming-comprehensive-writing-complex-problems/dp/0596153643" target="_blank"&gt;&amp;quot;Programming F#&amp;quot;&lt;/a&gt; and &lt;a href="http://www.amazon.com/Real-World-Functional-Programming-Examples/dp/1933988924/ref=pd_bxgy_b_img_b" target="_blank"&gt;&amp;quot;Real World Functional Programming: With Examples in F# and C#&amp;quot;&lt;/a&gt; (I started with the second one but had to switch to the first one that in my opinion provides a better transition to a functional programming and F# style).&lt;/p&gt;

&lt;p&gt;As you can see, we made some restrictions to expression syntax: we assume that numeric constants are of type float, and we only support four functions: exponent, natural logarithm, sine and cosine. But this should be sufficient for a purpose of language demo. In addition, there is only one variable symbol (X).&lt;/p&gt;

&lt;p&gt;Before we proceed with derivative definition, there is a couple of helper construction I’d like to define. We may need to have a common match for binary operators (Add, Sub, Mul, Div) and supported functions (Exp, Log, Sin, Cos). So we’ll define so called &lt;em&gt;active patterns&lt;/em&gt; that can be used to match such constructs:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;let (|Op|_|) (x : Expression) =
    match x with
    | Add(e1, e2) -&amp;gt; Some(Add, e1, e2)
    | Sub(e1, e2) -&amp;gt; Some(Sub, e1, e2)
    | Mul(e1, e2) -&amp;gt; Some(Mul, e1, e2)
    | Div(e1, e2) -&amp;gt; Some(Div, e1, e2)
    | Pow(e1, e2) -&amp;gt; Some(Pow, e1, e2)
    | _ -&amp;gt; None

let (|Func|_|) (x : Expression) =
    match x with
    | Exp(e) -&amp;gt; Some(Exp, e)
    | Log(e) -&amp;gt; Some(Log, e)
    | Sin(e) -&amp;gt; Some(Sin, e)
    | Cos(e) -&amp;gt; Some(Cos, e)
    | _ -&amp;gt; None&lt;/pre&gt;

&lt;p&gt;Again, I am afraid I can’t use this post to define the meaning of active patterns, banana clips (“(|” and “|)”), and options syntax (“Some” and “None”), there is a lot of information online, but you can think about the definitions above as something similar to regular expression matching: an expression “Add(e1, e2)” will be matched as “Op” (Add, e1, e2), and an expression “Exp(e)” is matched as “Func (Exp, e)”. We will see in a moment how this can become useful.&lt;/p&gt;

&lt;p&gt;Now what’s left is just a definition of a derivative. Here it is:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;let rec Derivative x : Expression =
    match x with
    | X -&amp;gt; Const(1.)
    | Const(n) -&amp;gt; Const(0.)
    | Neg(e) -&amp;gt; Neg(Derivative(e))
    | Add(e1, e2) -&amp;gt; Add(Derivative(e1), Derivative(e2))
    | Sub(e1, e2) -&amp;gt; Sub(Derivative(e1), Derivative(e2))
    | Mul(e1, e2) -&amp;gt; Add(Mul(Derivative(e1), e2), Mul(e1, Derivative(e2)))
    | Pow(e, Const(n)) -&amp;gt; Mul(Const(n), Pow(e, Const(n-1.)))
    | Exp(X) -&amp;gt; Exp(X)
    | Log(X) -&amp;gt; Div(Const(1.), X)
    | Sin(X) -&amp;gt; Cos(X)
    | Cos(X) -&amp;gt; Neg(Sin(X))
    | Func(g, f) -&amp;gt; 
        let dg = Derivative(g(X))
        let df = Derivative(f)
        match dg with
        | Func(dgf, dge) -&amp;gt; Mul(dgf(f), df)
        | Op (op, e1, e2) -&amp;gt; Mul(op(e1, e2), df)
        | _ -&amp;gt; failwith(sprintf &amp;quot;Unable to match compound function [%A]&amp;quot; dg)
    | _ -&amp;gt; failwith(sprintf &amp;quot;Unable to match expression [%A]&amp;quot; x)&lt;/pre&gt;

&lt;p&gt;As you can see, it’s not an algorithm – it’s a description of &lt;em&gt;what&lt;/em&gt; derivative is. You can also why we needed to introduce “Op” and “Func” active patterns: they are used in declaration of complex function derivative evaluation. Without these patterns we would need to list all supported operators and functions.&lt;/p&gt;

&lt;p&gt;To test how this works, we can open a F# interactive window (FSI) and type a function to test:&lt;/p&gt;

&lt;pre class="brush: csharp"&gt;&amp;gt; let d = Derivative(Sin(X));;

val d : Expression = Cos X

&amp;gt; let d = Derivative(Exp(Pow(X,Const(2.))));;

val d : Expression = Mul (Exp (Pow (X,Const 2.0)),Mul (Const 2.0,X))&lt;/pre&gt;

&lt;p&gt;That’s it! But while we are on symbolic calculations, we can improve the presentation part of it. Right now, if there is no attempt to simplify resulting expressions, so if we calculate a derivative of an expression corresponding to “5 * x + 3”, we will get a correct but silly looking answer:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;&amp;gt; let d = Derivative(Add(Mul(Const(5.), X), Const(3.)));;

val d : Expression =
  Add (Add (Mul (Const 0.0,X),Mul (Const 5.0,Const 1.0)),Const 0.0)&lt;/pre&gt;

&lt;p&gt;But if it was so simple to calculate derivatives in F#, it should not be difficult to write a function to simplify algebraic expressions. That will be in the next part.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://bloggingabout.net/aggbug.aspx?PostID=483477" width="1" height="1"&gt;</description><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/functional+programming/default.aspx">functional programming</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/F_2300_/default.aspx">F#</category></item></channel></rss>