<?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 : functional programming</title><link>http://bloggingabout.net/blogs/vagif/archive/tags/functional+programming/default.aspx</link><description>Tags: functional programming</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP2 (Build: 40407.4157)</generator><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><item><title>Time to buy ReSharper?</title><link>http://bloggingabout.net/blogs/vagif/archive/2010/01/19/time-to-buy-resharper.aspx</link><pubDate>Tue, 19 Jan 2010 14:32:20 GMT</pubDate><guid isPermaLink="false">813b6dfd-644e-4573-a816-eebab56ba0d0:482713</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=482713</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/commentapi.aspx?PostID=482713</wfw:comment><comments>http://bloggingabout.net/blogs/vagif/archive/2010/01/19/time-to-buy-resharper.aspx#comments</comments><description>&lt;p&gt;Today I spent a few hours on mysterious error. One automated test failed, and since it was actually an integration test with complex setup, tracking down the failure was not easy. The problem that I’ve eventually found can be illustrated with a couple of tests:&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;[Test]
public void BadClosureTest()
{
    int[] numbers = new int[]
    {
        1, 2, 3
    };

    List&amp;gt; functions = new List&amp;gt;();
    foreach (int n in numbers)
    {
        functions.Add(new Func(() =&amp;gt; n));
    }

    // Will fail on first assertion!
    Assert.That(functions[0].DynamicInvoke(), Is.EqualTo(1));
    Assert.That(functions[1].DynamicInvoke(), Is.EqualTo(2));
    Assert.That(functions[2].DynamicInvoke(), Is.EqualTo(3));
}

[Test]
public void GoodClosureTest()
{
    int[] numbers = new int[]
    {
        1, 2, 3
    };

    List&amp;gt; functions = new List&amp;gt;();
    foreach (int n in numbers)
    {
        int m = n;
        functions.Add(new Func(() =&amp;gt; m));
    }

    Assert.That(functions[0].DynamicInvoke(), Is.EqualTo(1));
    Assert.That(functions[1].DynamicInvoke(), Is.EqualTo(2));
    Assert.That(functions[2].DynamicInvoke(), Is.EqualTo(3));
}&lt;/pre&gt;

&lt;p&gt;As you can see, the only difference between these tests is a line in the second test assigning iterator “n” to a variable “m” defined within the “foreach” scope. Why does this matter?&lt;/p&gt;

&lt;p&gt;Well, for us, procedural languages veterans the difference may be not so obvious at first glance. But if you happen to have ReSharper, it will immediately give you a warning about the first test: “Access to modified closure”. And will suggest to copy “n” to a local variable. I didn’t have ReSharper, so I came to the same conclusion in a hard way.&lt;/p&gt;

&lt;p&gt;A lambda-expression “() =&amp;gt; n” is not just a delegate – it’s a closure. It uses a variable that is defined outside its scope. Such variables are always treated by reference, even though they may be of a value type. So as long as the variable “n” lives, any changes applied to it will affect every closure where it is referenced.&lt;/p&gt;

&lt;p&gt;And apparently ReSharper can warn us about improper use of closures.&lt;/p&gt;

&lt;p&gt;By the way, if instead of “foreach” test had a “for” loop with an index, the first test would fail with IndexOutOfRangeException. Because closures were accessed after the array elements are iterated and index would be set to 3.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://bloggingabout.net/aggbug.aspx?PostID=482713" 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/ReSharper/default.aspx">ReSharper</category></item><item><title>Expression tree serialization</title><link>http://bloggingabout.net/blogs/vagif/archive/2009/10/29/expression-tree-serialization.aspx</link><pubDate>Thu, 29 Oct 2009 20:16:30 GMT</pubDate><guid isPermaLink="false">813b6dfd-644e-4573-a816-eebab56ba0d0:482394</guid><dc:creator>Vagif Abilov</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/rsscomments.aspx?PostID=482394</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/commentapi.aspx?PostID=482394</wfw:comment><comments>http://bloggingabout.net/blogs/vagif/archive/2009/10/29/expression-tree-serialization.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://reverseblade.blogspot.com/2008/11/how-to-serialize-lambda-expressions.html" target="_blank"&gt;Serializing lambda expressions&lt;/a&gt; using &lt;a href="http://www.codeplex.com/metalinq" target="_blank"&gt;MetaLinq&lt;/a&gt;, by Onur Gumus.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://metastatic.org/text/Concern/2008/03/08/remoting-lambda-expressions/" target="_blank"&gt;Remoting lambda expressions&lt;/a&gt;, by Casey Marshall.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://code.msdn.microsoft.com/exprserialization" target="_blank"&gt;Expression tree serialization&lt;/a&gt; project.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://bloggingabout.net/aggbug.aspx?PostID=482394" width="1" height="1"&gt;</description><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/lambda/default.aspx">lambda</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/serialization/default.aspx">serialization</category><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/functional+programming/default.aspx">functional programming</category></item><item><title>Functional programming for C# developers</title><link>http://bloggingabout.net/blogs/vagif/archive/2009/10/12/functional-programming-for-c-developers.aspx</link><pubDate>Mon, 12 Oct 2009 21:23:35 GMT</pubDate><guid isPermaLink="false">813b6dfd-644e-4573-a816-eebab56ba0d0:482307</guid><dc:creator>Vagif Abilov</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/rsscomments.aspx?PostID=482307</wfw:commentRss><wfw:comment xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://bloggingabout.net/blogs/vagif/commentapi.aspx?PostID=482307</wfw:comment><comments>http://bloggingabout.net/blogs/vagif/archive/2009/10/12/functional-programming-for-c-developers.aspx#comments</comments><description>&lt;p&gt;Latest &lt;a href="http://msdn.microsoft.com/en-us/magazine/ee309512.aspx" target="_blank"&gt;Jeremy Miller’s article in MSDN Magazine&lt;/a&gt; will be very helpful for C# developers who haven’t started yet exploring functional programming. What is good about this article is that it gives practical advices on how to inject some fairly small pieces of functional programming into existing C# code in order to make it better – for example by removing code duplicates.&lt;/p&gt;  &lt;p&gt;What seems to be radical for many C# developers is how functional programming handles blocks of code with variables that are not resolved within those blocks – &lt;a href="http://martinfowler.com/bliki/Closure.html" target="_blank"&gt;closures&lt;/a&gt;. A piece of code with variables defined somewhere else is traditionally viewed by programmers with background in procedural languages as an invalid construction that will cause a compiler error. But closures are fully supported now in C# (in form of anonymous delegates or lambda-expressions), and Jeremy’s article demonstrates advantages of using this technique to pass around code blocks as data.&lt;/p&gt;  &lt;p&gt;I think however that the example with ConnectedSystemConsumer could be presented somewhat simpler, without focus on Interface Segregation Principle. Here’s how the original class looks before refactoring:&lt;/p&gt;  &lt;pre class="brush: csharp;"&gt;class ConnectedSystemConsumer
{
    private readonly IConnectedResource _resource;

    public ConnectedSystemConsumer(IConnectedResource resource)
    {
        _resource = resource;
    }

    public void ManipulateConnectedResource()
    {
        try
        {
            // First, you have to open a connection
            _resource.Open();
            // Now, manipulate the connected system
            _resource.Update(buildUpdateMessage());
        }
        finally
        {
            _resource.Close();
        }
    }

    // The rest of the class is skipped
}&lt;/pre&gt;

&lt;p&gt;The article then introduces two new interfaces and one class: IResourceInvocation, IResource and Resource, where IResourceInvocation contains the “interesting” part of IConnectedResource (methods FetchData and Update) and IResource defines and Resource implements a single method Invoke that takes care of all ceremony stuff. While this helps splitting the original ConnectedSystemConsumer class into smaller logical blocks, for developer doing his first experiments with functional programming it may leave false impression that adding additional classes are required (or at least expected) steps to take advantage of functional programming in C# code. But the same effect can be achieved without adding new interfaces or classes, just by extracting all ceremony code in a separate method:&lt;/p&gt;

&lt;pre class="brush: csharp;"&gt;class ConnectedSystemConsumer
{
    private readonly IConnectedResource _resource;

    public ConnectedSystemConsumer(IConnectedResource resource)
    {
        _resource = resource;
    }

    public void ManipulateConnectedResource()
    {
        InvokeResource(x =&amp;gt;
        {
            x.Update(buildUpdateMessage());
        });
    }

    private void InvokeResource(Action&amp;lt;IConnectedResource&amp;gt; action)
    {
        try
        {
            // First, you have to open a connection
            _resource.Open();
            // Now, manipulate the connected system
            action(_resource);
        }
        finally
        {
            _resource.Close();
        }
    }

    // The rest of the class is skipped
}&lt;/pre&gt;

&lt;p&gt;As you can see, ManipulateConnectedResource no longer contains ceremonial code that opens and closes resource and handles exceptions. This code is now moved to InvokeResource method that takes as an argument a block or a closure defined in ManipulateConnectedResource or any other method that requires the same ceremony.&lt;/p&gt;

&lt;p&gt;After reading Jeremy Miller’s article I browsed some of my old code and found several classes that can be simplified using the same approach. Perhaps at first they will not look simpler – functional programming style adoption requires some time. But they will become more compact, with less or without code repetition, and this alone is worth it.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://bloggingabout.net/aggbug.aspx?PostID=482307" width="1" height="1"&gt;</description><category domain="http://bloggingabout.net/blogs/vagif/archive/tags/lambda/default.aspx">lambda</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/functional+programming/default.aspx">functional programming</category></item></channel></rss>